Building a “Flash LED on Twitter Search” with a Raspberry Pi and Python

Building a “Flash LED on Twitter Search” with a Raspberry Pi and Python

This project provides a way of not only providing an on-screen Twitter search result stream, but also logs it to a file, AND flashes an LED each time there’s a “hit”. Like all my projects, it’s rough and ready but it’s a reasonable starting point.

What you’ll need:

  • A Raspberry Pi
  • An LED and some way of connecting that to the Pi
  • Python (along with the tweepy and GPIO libraries)
  • Your Twitter API tokens (see here, and choose Add New App)

With those in hand, wire your LED up to pin 22 and ground on your Pi (with a resistor if necessary), and plug your access token codes into the lines in the following code:

#!/usr/bin/env python
# @deKay01 2016/01/20

# Pull in all the required library stuff
import time
import sys
import RPi.GPIO as gpio
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy.streaming import StreamListener

# These are needed from dev.twitter.com
access_token = "***"
access_token_secret = "***"
consumer_key = "***"
consumer_secret = "***"

# Pulls your search term in from the command's argument
searchterm = sys.argv[1]

# Opens a file to put results into
f = open(searchterm+".txt",'w')

# Assumes LED is connected to pin 22 on the Pi
led = 22

# Initialises LED
gpio.setmode(gpio.BOARD)
gpio.setup(led, gpio.OUT)
gpio.output(led, gpio.LOW)

# A class to listen to the Twitter stream
class myListener(StreamListener):
  def on_status(self, status):

    # When there's a match...
    try:
       # Output to stdout
       print ("@{}: {}, ID={}\n".format(  str(status.user.screen_name.encode('utf-8')) , str(status.text.encode('utf-8')) , status.user.id_str  ))
       # Also output to file
       f.write("@{}: {}, ID={}\n".format(  str(status.user.screen_name.encode('utf-8')) , str(status.text.encode('utf-8')) , status.user.id_str  ))
       f.write("\n\n")
       # Flash that LED
       gpio.output(led, gpio.HIGH)
       time.sleep(0.2)
       gpio.output(led, gpio.LOW)
       
    except Exception as e:
      print(e)
                                            
  def on_error(self, status_code):
    print(status_code)
                                                        
while True:
  try:
    # Pull in the stream and loop forever
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    twitterStream = Stream(auth, myListener())
    twitterStream.filter(track=[searchterm],languages=['en'])

  except Exception as e:
    print(e)

(You can download a zip of this here)

To run it, run ./ledtweet.py searchterm from the command line (or whatever you called the file). Once a public tweet with your search term appears (try testing it with a search for help or java – they’re pretty common), you’ll get it shown on stdout, appended to the a text file (called searchterm.txt) and – the best bit – the LED will flash. Woo!

0 Comments

      1. Thanks for the reply!

        when running the code on your instructions we appear to be getting a result of

        401

        did you have this problem before? do you have any ideas how to resolve this issue

        Rob Baker
        1. Have you filled in this bit correctly?

          # These are needed from dev.twitter.com
          access_token = “***”
          access_token_secret = “***”
          consumer_key = “***”
          consumer_secret = “***”

          A 401 code means invalid credentials.

          deKay
  1. This code:

    # Flash that LED
    gpio.output(led, gpio.HIGH)
    time.sleep(0.2)
    gpio.output(led, gpio.LOW)

    is the bit that turns the LED on for 0.2 seconds, then off. You can make it stay on by increasing the number from 0.2 to 2 (for 2 seconds) or whatever suits you.

    Be aware that while this bit of the program is running, it won’t be actively looking for more matching tweets, so may miss some. The longer it waits, the more likely it is to miss them – this may or may not be an issue to you!

    deKay
  2. Pingback: Improving the “Flash LED on Twitter Search" program - deKay's Blog

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.