Comments: Raspberry Pi Twitter Monitor


Comments 59 comments

  • Thanks for posting this project. I have used the foundation to create two variants on the concept. Build page links include source code, etc. Pretty basic. It looks for a color to be mentioned on Twitter then displays that color on a RGB LED. Little more difficult. This program tracks two Twitter terms and graphs how often the terms are mentioned.

    Thanks again, Sparkfun; for posting up the original project!

    • These were cool projects. Thanks for sharing! The Hash Vote project reminds me of the Twitter race we attempted to do a while ago :)

  • So I am trying to do this - copied the code and put in my auth tokens etc – it will not blink or pick up the TERMS=# Does this only work when someone I am following does one of these hashtags? I want it to blink when I hashtag something - im using it for like a remote notification for someone when I am gone I can hash tag them and the light blinks..

    Help and or thoughts would be greatly appreciated.

    Thanks -Rick

    • There’s a good chance that the Twitter API has changed in the last year, and I have not revisited this project in a long time. That being said, it should pick up any hashtag. What hashtag are you trying? I’ve had issues with the Pi not being fast enough to pick up an obscure hashtag within a few minutes when Twitter is particularly busy. Try a common hashtag, like #lol, and see if you can blink or print it to the console.

      • Shawn: I have tried random hashtags, I have tried posting from my account, I have tried on my wall from another account.. I have tried from accounts that I am following.. its not picking up ANYTHING :( I know the OAUTH codes are working - because the post twitter commands post tweets to my account from my PI.. so .. any help would be sincerely appreciated - I really want this working as its part of a project for my Girlfriend.. Thanks

        • Sounds like a fun project :) I’ll see if I can help you out.

          First, regenerate your Access Token and Token Secret on This seemed to help me, as I had a old code from months/years ago.

          Next, create a new Python file and enter this:

          from twython import TwythonStreamer
          TERMS = 'lol'
          APP_KEY = '<YOUR API KEY>'
          class MyStreamer(TwythonStreamer):
                  def on_success(self, data):
                          if 'text' in data:
                                  print data['text'].encode('utf-8')
                  def on_error(self, err, data):
                          print err, data

          Run it, and you should see tons of Tweets fly past (‘lol’ is pretty common). I just tried this on my laptop and it worked.

  • Confused: I was under the impression that GPIO.setmode(GPIO.BOARD) means you use the numbers printed on the board, yet the diagram shows the LED hooked up to Pin 25 and the code reads LED = 22

    Researching this made me feel that the tutorial was using BCM numbering where pin 22 on the board is actually GPIO 25 in the code

    I’m using a Pi 2 in this case.
    The tutorial works but I was expecting the PINS to match the board due to the use of GPIO.setmode(GPIO.BOARD) in the code Confused?

    • The GPIO.BOARD means you are using the actual pin number (1-40) whereas GPIO.BCM refers to the GPIO designator (e.g. GPIO2, GPIO3, etc.). If you count the pins, pin 22 refers to GPIO25. The code is correct, as GPIO.BOARD means that the LED is attached to pin 22, which is GPIO25. For a better explanation, see here.

  • Hi

    I am attempting to adapt the code provided in this article to search for multiple hashtags which then activate different LEDs. E.g. if #lol is tweeted, LED1 lights; if #yes is tweeted, LED2 lights, etc.

    I am a Python newbie and have the following code adapted from the article. At present on the first term (‘#yes’) in the code returns any tweets. Could you please advise on the best way of achieving this?

    import time
    import RPi.GPIO as GPIO
    from twython import TwythonStreamer
    # Search terms
    TERMS1 = '#yes'
    TERMS2 = '#lol'
    # GPIO pin number of LED
    LED1 = 22
    LED2 = 32
    # Twitter application authentication
    APP_KEY = ''
    APP_SECRET = ''
    OAUTH_TOKEN = ''
    # Setup callbacks from Twython Streamer
    class BlinkyStreamer(TwythonStreamer):
            def on_success(self, data):
                if 'text' in data:
                print data['text'].encode('utf-8')
                GPIO.output(LED1, GPIO.HIGH)
                GPIO.output(LED1, GPIO.LOW)
    class BlinkyStreamer2(TwythonStreamer):
        def on_success(self, data):
            if 'text' in data:
            print data['text'].encode('utf-8')
            GPIO.output(LED2, GPIO.HIGH)
            GPIO.output(LED2, GPIO.LOW)
    # Setup GPIO as output
    GPIO.setup(LED1, GPIO.OUT)
    GPIO.output(LED1, GPIO.LOW)
    GPIO.setup(LED2, GPIO.OUT)
    GPIO.output(LED2, GPIO.LOW)
    # Create streamer
        stream1 = BlinkyStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        stream2 = BlinkyStreamer2(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    except KeyboardInterrupt:
    • Were you able to get it working? I can swap the pin numbers and both LEDs work. It just seems like it doesn’t run the second stream code.

      • I get the feeling the API won’t let you connect with 2 streamers at the same time. As a result, I recommend using 1 streamer and setting the track terms to a list: ['#yes', '#lol']. The on_success() function will be called whenever either of those tags are found. Then, you can search through the tweet and turn on the LED depending on which tag is found.

        • Could you explain that idea better? I am very new in this thanks

          • Are you able to get the basic example code running? If so, try changing the line

            TERMS = '#yes'


            TERMS = ['#yes', '#lol']

            This will allow you to look for multiple hashtags in real time on Twitter.

  • This may be far too late, but to anyone trying to get to the twitter developer page to make the app…

  • Hi. I got the first part of my problem solved. There were a few things which I was doing wrong. Firstly, the resistor was too strong for my LED. Changed it to 50 ohms. Secondly, updated the RPi GPIO library. Worked like a charm.

    Now trying to figure how to customize this as a personal timeline hashtag based blink.

    • When you say someone tweets you, you mean they include your Twitter handle with @<your name>? If so, then you can look to see if you were mentioned in the tweet with if "@<your name>" in data['text'].encode('utf-8'): See this post.

  • Has anyone received the following error message? Any suggestions on a fix? The program runs fine for several minutes and then I receive the following:

    Traceback (most recent call last): File “/home/pi/TweetBlinky/”, line 27, in <module> stream.statuses.filter(track=TERMS) File “/usr/local/lib/python3.2/dist-packages/twython/streaming/”, line 65, in filter self.streamer.request(url, ‘POST’, params=params) File “/usr/local/lib/python3.2/dist-packages/twython/streaming/”, line 141, in request for line in response.iter_lines(self.chunk_size): File “/usr/local/lib/python3.2/dist-packages/requests/”, line 715, in iter_lines for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode): File “/usr/local/lib/python3.2/dist-packages/requests/”, line 673, in generate for chunk in, decode_content=True): File “/usr/local/lib/python3.2/dist-packages/requests/packages/urllib3/”, line 303, in stream for line in self.read_chunked(amt, decode_content=decode_content): File “/usr/local/lib/python3.2/dist-packages/requests/packages/urllib3/”, line 450, in read_chunked chunk = self.handle_chunk(amt) File “/usr/local/lib/python3.2/dist-packages/requests/packages/urllib3/”, line 411, in handle_chunk value = self.fp.safe_read(amt) File “/usr/lib/python3.2/http/”, line 592, in _safe_read raise IncompleteRead(b'‘.join(s), amt) http.client.IncompleteRead: IncompleteRead(0 bytes read, 1 more expected)

  • Two questions; odds are at least one is a dumb one.

    Does “TERMS” have to be a hashtag, or can “stream.statuses.filter” track for any text?

    I take it that in the line “if ‘text’ in data”, ‘text’ is one part of the “data” array, so it should say “‘text’” and not “‘whatyouwanttosearchfor’”. Can someone point me to documentation on what all is in “data”?


    • To answer your first question, TERMS can be any text.

      As for your second question, ‘text’ is an actual keyword inside of the data “dictionary.” Here is the layout of a Twitter status object. Notice that “text” is the second field within the object. You can print all of “data” if you want to see what’s in the Tweet.

      Hope that helps!

  • tried using code but python said the third “data” right after “print” and before “[‘text’]” was invalid syntax. does anyone know what is wrong or something else i need to download or update on my pi.

    • I’m brand new to this myself, but my suggestion: Maybe you’re using Python 3 rather than Python 2? In 3, print() is a function rather than a direct command. Try putting the argument in parentheses, thus:


  • For some reason, my monitor will not show tweets that are sent from mobile apps. Can anyone help me figure this out? Thanks!

    • Is the Twitter Monitor printing tweets from other sources?

      The one thing I found was that the Raspberry Pi can’t keep up with the volume of tweets if you use a common search phrase. Try something that’s uncommon or no one would use. Additionally, you could try running the Twitter Monitor from a computer to see if that helps.

      • I tried tweeting a less common search phrase from my own Twitter account and it still didn’t show up. This is driving me crazy! Any other ideas?

      • It’s definitely printing tweets from other sources. I will try that and let you know if it helps. Thank you!

  • Hello,

    I just copy /past the code , addapted the APIkey, Auth key… But nothing appears. No error message.

    While I tried the bellow SendMessage worked. :=> API keys and tweeter account are OK

    Any Idea?

    Lol is indeed very common !

    • I know that recently, Twitter has been requiring a mobile phone number to be associated with your account before you can use the API. You’re saying that you can post things to your Twitter account, right?

      • Yes this works.., I can update status… twitter.update_status(status=“Ca marche! :D”)

        But your nice code does not responds I did try this code yesterday night:

        from twython import TwythonStreamer
        class TweetStreamer(TwythonStreamer):
            def on_success(self, data):
                if 'text' in data:
                    print data['text'].encode('utf-8')
            def on_error(self, status_code, data):
                print status_code
        APP_KEY = "xxxxxx"
        APP_SECRET = "xxxxxxxx"
        OAUTH_TOKEN = 'xxxxxxxxx'
        OAUTH_TOKEN_SECRET = 'xxxxxxxxx'
        streamer = TweetStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        streamer.statuses.filter(track = 'python')

        Then I get 401

        • That actually looks right to me. It might be a weird, esoteric problem like your system time being off. See this StackExchange post:

  • I needed sudo pip install -U distribute==0.6.45

    before sudo pip install Adafruit_BBIO

  • While installing * pip install Adafruit_BBIO*

    I get this error message: InstallationError: Command python egg_info failed with error code 2 in /home/pi/build/Adafruit-BBIO

  • second try

    from twython import Twython 
    APP_KEY = “xxxx” 
    APP_SECRET = “xxxxx”
    OAUTH_TOKEN = ‘xxxx’ 
    OAUTH_TOKEN_SECRET = ‘xxxxx’
    #startTime =
    #Sends a private message
    twitter.send_direct_message(user_id=“FromUserNo@”, screen_name=“FromUserNo@”, text= ‘ bonjour ’)
    #sends a public message
    twitter.update_status(status=“Ca marche! :D”)
    print (“DM SENT IN”)
    #print (
  • here just a small code to make the opposit using the same Twython. Has to be improved to link it to the Gpio: Once the gpio gets an input: sends a tweet:

    from twython import Twython
    APP_KEY = "xxxx"
    APP_SECRET = "xxxxx"
    OAUTH_TOKEN = 'xxxx'
    OAUTH_TOKEN_SECRET = 'xxxxx'
    #startTime =
    #Sends a private message
    twitter.send_direct_message(user_id="FromUserNo@", screen_name="FromUserNo@", text= ' bonjour ')
    #sends a public message
    twitter.update_status(status="Ca marche! :D")
    print ("DM SENT IN")
    #print (

    P.S. Sorry for the layout of this comment.

  • A big thanks anyhow..

  • I had to add

    sudo pip install rpi.gpio

    And there is a small error between thje code Led pin and the schema (Pin 22 vs 25)..

    • Interesting….good to know. The version of Raspbian I used in the tutorial came with RPi.GPIO already installed.

      Also, If you do


      You should be able to reference the pin by pin number (e.g. 22) as opposed to the GPIO number (e.g. 25).

  • Thanks for the explanation. I understand. I will have to look closer at the code you linked to, the tweeting game, that might help me… in the mean time I will experiment with: terms = [‘#rasberrypi’, ‘#Helpful’, ‘@ShawnHymel’]

    Thanks again for your help… :)


  • Thank you Shawn,

    So I should be able to use the following?: terms = [‘#omg OR #hello OR #diy’]

    Would that be the correct syntax? As a result, any tweets that contain any one of the above three words would be displayed?

    Would the following also work?: terms = [‘#omg AND #hello AND #diy’] Would this display tweets that only include those three words?

    I’m at the office and cannot test, but i hope it’s that simple :)

    • Sort of. The code looks for strings that are contained between the single quotes: ' '. So, your code would be looking for the entire phrase “#omg OR #hello OR #diy” to appear in a tweet (which probably won’t happen). To do ORs like in your first example, you need to set terms to an array of strings (like in my example below): terms = ['#omg', '#hello', '#diy']

      Each term in the array is its own string because of the ' '. For example, '#omg' is one search term, '#hello' is another, and '#diy' is a third. The program will call back to the on_success(self, data) function when any one of those strings appears in a tweet (which is what you are trying to do with the OR statements).

      There is no way (that I’m aware of) to set AND statements for your search terms. You will need to perform a check in on_success(self, data) that all of the search terms are present in the tweet.

  • Cool project… I’m hoping to expand on it, but I’m very new to Python…

    in the line: TERMS = ‘#lol’ in the dissecting code, it says TERMS holds a string (or Strings)

    how would i change it if I wanted to search for more than one Term? for instance, say I want to find tweets to @RobFord that also say “drunk” how would i change that line? The above example is just for fun, but should help with my project…

    I’m hoping to either increment a counter, if Drunk is used, increment another counter if Drugs is used. then either adjust the brightness or the color of an rgb led…. i tried a couple of things like TERMS = ‘#lol’ AND ‘#Haha" but nothing came of it…

    help? :)

    • To use multiple search terms, you can use an array:

      terms = ['#omg', '#hello', '#diy', '#robot', '#fun']

      I actually worked on something similar to what you’re describing… It was a game that counted the number of times a term appeared in a specific time. You can see my example code here:

      • Note that although Twitter has some pretty lenient API restrictions, if you do start approaching your limits you can get the number of accesses down by using e.g. ‘#omg OR #hello OR #diy’ to get all tweets that match any one of those terms, and then use device-side code to figure out which was/were matched.

  • Oh, and here’s what I had to do to get it working:

    apt-get update
    apt-get install python-pip
    apt-get install python-dev
    pip install twython
    pip install Adafruit_BBIO
    • Awesome! Thanks, Prof. Yoder :) If you don’t mind, I’ll include a section in the tutorial about what to install for the BeagleBone Black.

  • Shawn, what a fun project. Yesterday I got it working on a BeagleBone Black.


  • Works great, except I thought I was getting duplicate tweets, so I added printing the screen_name from the tweet. Turns out it was not duplicate tweets, but re-tweets.

  • I got nothing when running it… ;-(

    • You made sure to run as superuser (sudo), right? Were there any errors that appeared?

      Also, what search term did you use (e.g. #lol)?

  • On the “Required Components” page, you forgot the led.

  • Nothing happens when I run the command: sudo python

    My Pi just sits and thinks…until I kill it w/ ctrl+c. Nothing prints to the terminal. What am I doing wrong?

  • Hi Shawn. Thank you for this project. I am using a RasPi B+ and with the 40 pin breakout board to connect to the breadboard using the bus cable. I have connected 3.3V pin and the GND pin to the LED using 390 ohm resistor. I do get the tweets with the hashtag on my console bu the LED doesn’t blink. I have double checked the circuit and it looks fine to me. Do you have any suggestions?

    Also, how do I modify the code wherein I receive the tweets only sent to my timeline and not universal tweets with the hashtag ? i.e. if someone tweets me with the hashtag it should appear on my timeline and the LED should blink.

    Thanks in advance.


If you've found a bug or have other constructive feedback for our tutorial authors, please send us your feedback!