How to Build a Raspberry Pi Twitter Bot

Ads by Google

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!

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!

Getting Started

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.

Installing Twython

It’s a good idea to run updates first. Copy and paste the following commands one at a time – most will require confirmation.

Ads by Google

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 outisde 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.

new twitter app   How to Build a Raspberry Pi Twitter Bot

You’ll see something resembling this once you’re done – these keys are unique to you.

twitter app   How to Build a Raspberry Pi Twitter Bot

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.

readwrite access   How to Build a Raspberry Pi Twitter Bot

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.

access token   How to Build a Raspberry Pi Twitter Bot

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[1])

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:

import os

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('=')[1].split("'")[0]
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:

ls /dev/video*

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

Ads by Google

The comments were closed because the article is more than 180 days old.

If you have any questions related to what's mentioned in the article or need help with any computer issue, ask it on MakeUseOf Answers—We and our community will be more than happy to help.

49 Comments -

joel

I Reaaly don’t Understand that .. Can u please do it with video . ?

James B

You want me to write code, on a video?

Daniel E

Maybe not the code, but the process of registering the Twitter app.

On second thought, why not a video of you writing the code, and posting it on YouTube?

Patrick

Yes, could you video yourself writing the code on paper? ROFL!

Cool stuff with the Raspberry. i wish I could really find a use for one.

R Sail

is this like an automated spamming machine..

Chip

Not necessarily. For example it could be used to report the weather. Or it could be used to report data when triggered by an external trigger (i.e., too cold in the house). While this could be spamish, the big difference is that tweets are opt-in.

RasPi

Can you show how to get successful response after sending tweets and not exceeding 140 characters limit? Thank you.

James B

See Jim’s comment below!

John

you can limit the text of your status just like this:
twitter.update_status(status=twitter_status[:140])

Jim Easterbrook

To limit the tweet to 140 characters is very easy. Change
api.update_status(status=sys.argv[1])
to
api.update_status(status=sys.argv[1][:140])

James B

Awesome, thanks Jim!

James Nachaski

I realize that I might be labeled as a “hater” but really this is not that interesting.

You can do the same thing with any computer…

I don’t know why adding “raspberry pi” to the end of stuff makes it cool now.

There are too many projects involving the Pi doing stuff that is just normal computer use that try to sound fresh and cool.

Such as:
“Display stock prices on your television using Raspberry Pi” – Not a real problem or a cool project.
Use cnbc or, you know the Internet and an rss feed plus reader.

“Read your email on your Raspberry Pi” – Wow, it’s a computer with an email client! How innovative!

“Send tweets using the Twitter API and rPI” – Essentially this article.

Interesting uses:
Media center – The Pi media center is pretty darn cool.

Network attached home security and surveillance. Raspberry pi connected to a PIR array via
usb2serial to an arduino. If motion is detected, a signal is sent down the serial cable and the PI sends a text to my phone as well as emailing me 8 images from 4 cameras I have. Total cost – $73.

Let’s MakeUseOf technology to do something interesting. Using the twitter api can be done from any computer and OS’s are multitasking so you can have background processes. No need for a Pi when you can run the same job in the background from any Linux box.

Anyhow, this is just my opinion.

Bruce Bowman

Let me give you an example that shows why this is cool. I teach high school science. My environmental science class is building RPi units that connect to our (normally manually read) building power sub-meters and monitor both building instantaneous loads and total power consumption and then tweet the data every 10 minutes. We are also working up a web app that will receive the tweets and record and aggregate them for display and analysis on the school web site. Of course, anyone who wants to follow a building twitter account (think science classes,) can also monitor power consumption that way.

It’s cool because the submeter vendor wants about $10000 for hardware and software that does the same thing (with no Twitter). We are going to be able to monitor 6 buildings for around $500 and some sweat equity. My kids are EXCITED! It’s TWITTER! The rest of our school gets to use these tools to (hopefully) reduce energy consumption.

The Raspberry Pi makes this doable along with all the help from the RPi community, freely given. Just “any Linux box” falls short on cost, form factor and support. I rest my case.

Thanks for the help James.

Richard

Hi

I tried to google various terms from your paragraph

“Network attached home security and surveillance. Raspberry pi connected to a PIR array via
usb2serial to an arduino. If motion is detected, a signal is sent down the serial cable and the PI sends a text to my phone as well as emailing me 8 images from 4 cameras I have. Total cost – $73.”

because this sounds awesome but I can’t seem to find the article you’ve seen. Can you point me at it please?

All the best

Richard

Rob

Thanks for sharing this. I think posting stuff this is really useful. I am just an amateur t this, so I appreciate any instructions that you can provide. The Pi is a fun device to tinker with. The projects take a while, even the simple ones. Lots of time spent checking and double checking the commands…worth it. Keep posting your ideas!

Kris De Rocker

Dear,

I have my first Raspberry PI here and i have some questions about this script (for tweeting the temperature). Can you also give other temperatures such as motherboard temps? Or amount of RAM (and how much free), the amount of disk space (and how much free), CPU load etc?

Best regards,
Kris

Kris De Rocker

PS : i just tried to have my CPU temp twittered, and i get this error (my script is named iamrpi.py)

root@raspberrypi:/home/test/Tweeter# python iamrpi.py
File “iamrpi.py”, line 3
import sys
^

What did i do wrong?

Best regards,
Kris

James B

Is the example above working for you? It sounds like theres something more fundamental wrong there.

Atif Sheikh

Raspberry Pi tweets would be visible to all? mean can it be customized to send msgz only to me ?

James B

Sure. According to the Twython docs, you can use:

api.sendDirectMessage(user_id=””, text=””)

Luke

What happened to the link? It’s got a line through it..

James B

That can happen when then site goes offline and our dead link tracker catches it. You still see the strikethrough? I’m not sure which link you’re asking about precisely, so can’t offer an alternative…

Ajit

I like this! But does it not need some form of connectivity on the Pi(ex wifi) else how would it authenticate to twitter. many thanks

James B

Of course – it’s assumed you have ethernet connected, and power.

Ajit

many thanks! keep up your good work!

julian

Great tutorial very easy to follow had it up and tweatin in 5mins thanks .

ajit

Many thanks! this worked perfectly and is a great motivator for students. For the CPU temp – we got an error ‘incompatible VCHIQ library’ but needed a reboot and was fixed
Going to try webcam tomorrow. But great instructions. thanks!

ajit

All worked perfectly including the webcam. Thanks. You have a way to post to facebook also? Many thanks. Keep up the good work rgds ajit

ajit jaokar

@James – thanks! will try and see how far we get. keep up your good work :)

Dan

Great post, is it possible to read my tweets on the Pi too?

paul f

James, this is a e what you are doing to Meyer th buildings sounds really good – kids and headmaster both excited!

I got a little lost around what to do with pygame. Where does the code go ie import pygame …? In nano?

I really want to get this going to excite my kids at home.
Cheers

David Saul

Have tried setting it up the other way around – ie so the rpi can receive Tweets in to a Python app ?

Francois

Wonderfull tutorial! However it worked 3 times and now I have this error message that I abbreviate ” Twitter API returned a 403 (forbidden), User is over daily status update limit.”
I read a bit the API documentation and it seems that Twitter changed the permission rules and that one need now the read, write and direct message but I am not sure.
anyway I change to read, write and direct message but error message is still here and it does not tweet anymore. Any coding modifications?
best
Francois, Bordeaux, France

anonymous

very nice, thank you, my raspi is tweeting… :)

xsatria

thanks bro, greetings from Indonesia :)

Adrian

Good Tuturial. Everything worked fine. First stuff done with my RPI. Thanks

Aik

is it possible to make bot to retweet some other people tweets every 10 minutes (maybe random time every 10 – 15 minutes) and doing this by searching phrase I am interested in… For example every 10-15 min retweeting something about #raspberrypi… ?

James B

Sure, but I don’t see why you’d waste a raspberry pi on doing that.

Geo

Seems like authentication is always failing. Am I missing something?

James B

Probably – did you replace all of these lines with your access keys etc?

CONSUMER_KEY = ‘***************YOUR DATA*****************’

c3ntry

How do I register the Application now? Why is ” from this link” deactivated?

c3ntry

Cool, thank you.

gpem

Great tutorial worked first time, just wandering how do I add a #tag to the to the tweet
Many thanks for all your hard work

Paul

Great tutorial and the example works great. There are some small changes made to the Twitter dev page which can be a little confusing.

How would I go about using non-ANSI characters in a tweet? I cannot for the life of me figure it out.