How to Build a Raspberry Pi Twitter Bot
Twitter is the world biggest repository of short messages from people with nothing to say – and now you too can contribute to that epic project with an automated Twitter bot, powered by your Raspberry Pi. I’m kidding, of course – some people actually tweet interesting things . I’m not one of them though – I use my mine for shameless product promotion in exchange for free stuff, competition entries, and auto-posting new episodes of our very own Technophilia Podcast. Whatever – my followers love me!
@w0lfiesmith I hate your Twitter account. So much.
— Justin Pot (@jhpot) August 21, 2013
Now I’m going to add to the usefulness of my personal Twitter stream by having a Raspberry Pi automatically tweet its current CPU temperature every hour, and a webcam picture!
This project uses Python; a simple programming language ideal for DIY projects. We’ll begin by installing Twython on the Pi – a Python module for interfacing with Twitter; setting up a Twitter “application” to get an API key; then go onto make the Pi tweet stuff on our behalf. It’s going to be so much fun!
I’m doing this on Raspian – but it should in theory work on any Linux-based OS you have on the Pi . If you haven’t already, make sure you set up SSH so we can remotely log in and perform console commands.
It’s a good idea to run updates first. Copy and paste the following commands one at a time – most will require confirmation.
sudo apt-get update sudo apt-get upgrade sudo apt-get install python-setuptools sudo easy_install pip sudo pip install twython
Registering a Twitter app
In order to use the Twitter API – that is, the REST interface that we’ll use to post new Tweets and generally interact with Twitter outside of the Twitter website – we’ll need to register a new app. Do that from this link – you needn’t specify a callback URL, and just make up a website if you want.
You’ll see something resembling this once you’re done – these keys are unique to you.
By default, the app is set to read-only, so we won’t be able to publish tweets without changing that to Read and Write. Go to the Settings tab and change the Application type.
Once saved, head back to the Details tab and click the button at the bottom to create an OAuth access token – this gives your application access to your own Twitter account. Refresh, and leave the page open for later – we’ll need to copy paste some of those keys in a minute.
Create Your Python Project
Begin by making a new directory to house your Tweet project, then create a new file.
mkdir SillyTweeter cd SillyTweeter sudo nano SillyTweeter.py
You can call it whatever you like, obviously.
In the text editor that appears, copy and paste the following, replacing the consumer key with the relevant key from the Twitter application page we left open earlier. Each key is surrounded by single quotes, so be sure not to miss those. Note that ACCESS_KEY is referred to as Access token on the Twitter app page.
#!/usr/bin/env python import sys from twython import Twython CONSUMER_KEY = '***************YOUR DATA*****************' CONSUMER_SECRET = '***************YOUR DATA*****************' ACCESS_KEY = '***************YOUR DATA*****************' ACCESS_SECRET = '***************YOUR DATA*****************' api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) api.update_status(status=sys.argv)
Hit Ctrl-X, and press Y to exit and save the file. Make it executable with the following command (replacing your Python file name if you chose something else)
sudo chmod +x SillyTweeter.py
You should now be able to test your ability to post tweets like so:
python SillyTweeter.py 'Hello Everyone, this is my Raspberry Pi tweeting you more nonsense'
Tweeting Your CPU Temp
Now that you can post any kind nonsense you want, let’s adjust the app to grab the current CPU temperature, because I’ll be damned if the world doesn’t need to know that every hour.
Start by adding another import for os library:
Then add the following lines, replacing the previous api.update_status from the example above.
cmd = '/opt/vc/bin/vcgencmd measure_temp' line = os.popen(cmd).readline().strip() temp = line.split('=').split("'") api.update_status(status='My current CPU temperature is '+temp+' C')
I won’t explain this code too much because it doesn’t really matter – it runs a command that grabs the temperature, then splits up the output to extract the number, and tweets that with a custom message. You can find the complete example code here.
Tweeting Webcam Pics
Now let’s make something really useful; we’re going tweet webcam pics. Thankfully, Twython supports the API function update_status_with_media, which makes things rather simple.
Plug a USB webcam into your device and check if it’s been recognised with the command:
if you see video0, you’re in luck. I used a Playstation 3 PSEye cam and it worked just fine without any additional legwork.
We’re also going to use the pygame libraries to take a picture; add the following lines just after the existing import statements:
import pygame import pygame.camera from pygame.locals import * pygame.init() pygame.camera.init() cam = pygame.camera.Camera("/dev/video0",(640,480)) cam.start() image = cam.get_image() pygame.image.save(image,'webcam.jpg')
In short, you’ve initialised the webcam at a specific resolution (you may need to adjust this is it’s a really old cam), snapped a picture, and saved it as a jpg. We’re just going to overwrite the same webcam.jpg each time the app is run.
Finally, adjust the update_status line to read:
photo = open('webcam.jpg','rb') api.update_status_with_media(media=photo, status='My RPi be tweeting images now => ')
Of course, you can change the status text to your current CPU temperature again, if you like. The complete code for this example is here.
Can You Repeat That?
A Twitter bot is only useful if it runs multiple times, automatically; you don’t want to be sitting there running the command every hour. To achieve this, let’s use the Pi’s CRON scheduling feature (What is a CRON job? )
sudo crontab -e
Paste in this line, to run every hour.
*/60 * * * * python /home/pi/SillyTweeter/SillyTweeter.py
Change that to * * * * * if you want it to run every minute, and be prepared to lose followers faster than a Twitter account that loses followers quickly.
That’s for today. I’m happy to have contributed more silliness to the vast wealth of useless bytes on the Internet, and I hope you do too! Show your appreciation for this tutorial by tweeting it, and then let us know what your own Twitter bot is going to tweet about in the comments.
Image credit: adafruit/flickr