Skip to content

Instantly share code, notes, and snippets.

@actuino
Forked from sandyjmacdonald/twitter-mood-light.py
Created March 12, 2017 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save actuino/4b0872826bbba2efc602a7d599dde762 to your computer and use it in GitHub Desktop.
Save actuino/4b0872826bbba2efc602a7d599dde762 to your computer and use it in GitHub Desktop.
Turn your Pimoroni Unicorn pHAT or Mood Light Kit into a Twitter-connected mood light that tracks the mood of your most recent tweets.
## This script will turn your Unicorn pHAT or Mood Light Kit into
## a Twitter-connected mood light that tracks the mood of your most
## recent tweets.
## You'll need to install the unicornhat, textblob, and tweepy Python
## libraries, and run "python -m textblob.download_corpora" to download
## the corpora for textblob the first time you run it.
## Change the start_hue and end_hue values to use a different portion of
## the colour wheel. Change num_tweets to track a larger number of recent
## tweets.
## Remember to add create an app. at https://dev.twitter.com/ and add the
## consumer and access keys and secrets below.
import tweepy
import time
import colorsys
import unicornhat as uh
from textblob import TextBlob
consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
start_hue = 220
end_hue = 320
range_hue = (end_hue - start_hue)
num_tweets = 3
weightings = range(1, num_tweets)
uh.set_layout(uh.PHAT)
uh.brightness(0.5)
while True:
avg_polarities = []
for status in tweepy.Cursor(api.user_timeline).items(num_tweets):
status = " ".join([word for word in status.text.split() if not ("@" in word or "http" in word)])
blob = TextBlob(status)
sent_polarities = [sentence.sentiment.polarity for sentence in blob.sentences]
polarity = sum(sent_polarities) / len(sent_polarities)
avg_polarities.append(polarity)
weighted = [x / y for x, y in zip(avg_polarities, weightings)]
avg_polarity = sum(weighted) / len(weighted)
avg_polarity = ((avg_polarity + 1) / 2)
hue = (start_hue + (avg_polarity * range_hue)) / 360.0
r, g, b = [int(c * 255) for c in colorsys.hsv_to_rgb(hue, 1.0, 1.0)]
uh.clear()
for x in range(8):
for y in range(4):
uh.set_pixel(x, y, r, g, b)
uh.show()
time.sleep(25)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment