Pinterest Stumbleupon Whatsapp
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 How To Use Twitter To Search For Mentors In Your Area Of Interest How To Use Twitter To Search For Mentors In Your Area Of Interest In the real world, a mentor is a wise teacher who supports and guides someone, and helps them maximize their potential. In the online world, you would be very lucky to find someone who will... Read More . 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 7 Operating Systems You Can Run With Raspberry Pi 7 Operating Systems You Can Run With Raspberry Pi Who can argue with a $40 computer? Especially one that also forms a good base for electronics projects! I certainly can't. But the hardware alone is only one side of the story: you still need... Read More . 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

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

twitter-app

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

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

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? Automate Your Wordpress Backup With Simple Shell Scripting & CRON Automate Your Wordpress Backup With Simple Shell Scripting & CRON Last time we talked about Wordpress backups, I showed you how incredibly easy it was to backup your entire database and files though SSH with only a few commands. This time, I'm going to show... Read More )

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

  1. Ishan
    July 22, 2016 at 8:11 pm

    I installed twython, then imported it into my code. I still have an ImportError saying no module named twython. Any ideas?

    • Ishan
      July 25, 2016 at 6:55 pm

      Never mind, I figured out the error: instead of using 'sudo python photobooth.py', I just needed to use 'sudo python3 photobooth.py'

  2. User123
    June 8, 2016 at 8:03 am

    Thanks... The code works for me... a little change which I did:

    from ---- api.update_status(status=sys.argv[1])
    to -----api.update_status(status=sys.argv)

    It works as smooth as a hot knife in a butter!

  3. jcmt_testing
    May 28, 2016 at 5:03 pm

    Great job !!!

    When using python 3 you can obtain this error:

    ImportError: No module named 'twython'

    Solve it with this command (to install sdk on python 3)

    sudo pip-3.2 install twython

  4. Josh Stevenson
    May 25, 2016 at 6:41 am

    I can execute the Twitter python script manually, but when run from crontab it doesn't send the Tweet - even when combined with other working crontab python scrips, which tells me that it's something on Twitter's end?

  5. ALI
    March 12, 2016 at 10:32 am

    thanks but it didn't work for me
    i did every step and when i want to send a tweet it says:
    Traceback (most recent call last) :
    File "Twitter.py", line 2, in (module)
    from twython import Twython
    ImportError: No module named twython

    PLEASE HELP!!!!!!

    • Brothah
      December 6, 2016 at 6:29 pm

      Having the same problem, did you solve it?

  6. Adam
    February 6, 2016 at 8:42 pm

    Great tutorial,

    Just wondering the first tweet my web cam sends is perfect however any it sends after this are distorted? if i disconnect the camera and reconnect it, it seems to work fine again? any ideas?

  7. phil
    January 23, 2016 at 5:23 pm

    Merci

  8. Jims Bryden
    September 1, 2015 at 8:14 am

    Hi, thanks for the great tutorial, got the tweeting going, including temperature tweets! Having a bit of trouble getting it to tweet a photo though as I am getting an error message

    Traceback (most recent call last):
    File "testingtweetsphoto.py", line 11, in
    cam.start()
    SystemError: ioctl(VIDIOC_S_FMT) failure: no supported formats

    Any help greatly appreciated, thanks in any case

  9. Russell
    April 30, 2015 at 12:54 am

    cool stuff

  10. widodolestari
    February 27, 2015 at 10:48 am

    Hi James, how the statement if use the camera on board ?

  11. Andy wood
    February 25, 2015 at 2:18 pm

    thanks....any pointers on how to do that? I'll search around google for it though

    ta

  12. andy wood
    February 24, 2015 at 10:47 pm

    hi, I've found that if a tweet is made then another tweet cannot be made if it contains the exact same text. An error is returned. This is especially noticeable with the temp as often this is the same. What have i done wrong? Thanks for the article though

    • James Bruce
      February 25, 2015 at 7:37 am

      Twitter spam protection: try putting the current date/time at the end of the tweet.

      • ethan dunzer
        August 13, 2016 at 8:36 pm

        sorry to bother you but i was wondering if you could show me what it would look like to add the date and time to the end of the tweet.

  13. widodolestari
    February 23, 2015 at 2:09 pm

    Great tutorial. Greeting from Jakarta 'Halo' !

  14. Paul
    March 5, 2014 at 3:24 pm

    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.

  15. gpem
    March 4, 2014 at 4:37 pm

    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

  16. c3ntry
    February 25, 2014 at 8:03 am

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

    • James B
      February 25, 2014 at 9:35 am

      Here: https://dev.twitter.com/apps/new

      It's deactivated because our broken link checker is pathetic. Sorry!

    • c3ntry
      February 25, 2014 at 9:37 am

      Cool, thank you.

  17. Geo
    February 20, 2014 at 4:58 am

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

    • James B
      February 20, 2014 at 8:57 am

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

      CONSUMER_KEY = '***************YOUR DATA*****************'

  18. Aik
    January 25, 2014 at 11:27 pm

    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
      January 26, 2014 at 9:28 am

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

  19. Adrian
    January 23, 2014 at 5:05 pm

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

  20. xsatria
    January 23, 2014 at 4:07 pm

    thanks bro, greetings from Indonesia :)

  21. anonymous
    January 13, 2014 at 6:05 pm

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

  22. Francois
    December 21, 2013 at 9:26 pm

    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

  23. David Saul
    December 8, 2013 at 12:34 pm

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

  24. paul f
    November 3, 2013 at 7:22 pm

    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

  25. Dan
    October 30, 2013 at 8:27 pm

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

  26. ajit jaokar
    October 25, 2013 at 7:59 am

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

  27. ajit
    October 20, 2013 at 7:37 pm

    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

  28. ajit
    October 19, 2013 at 7:20 pm

    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!

  29. julian
    October 16, 2013 at 8:43 pm

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

  30. Ajit
    October 12, 2013 at 7:35 am

    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
      October 12, 2013 at 8:25 am

      Of course - it's assumed you have ethernet connected, and power.

    • Ajit
      October 12, 2013 at 8:31 am

      many thanks! keep up your good work!

  31. Luke
    October 6, 2013 at 2:07 pm

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

    • James B
      October 7, 2013 at 8:35 am

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

  32. Atif Sheikh
    October 1, 2013 at 2:59 pm

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

    • James B
      October 1, 2013 at 3:27 pm

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

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

  33. Kris De Rocker
    September 26, 2013 at 12:12 am

    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
      September 27, 2013 at 10:54 am

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

  34. Kris De Rocker
    September 25, 2013 at 11:04 pm

    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

  35. Rob
    September 25, 2013 at 2:35 am

    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!

  36. James Nachaski
    September 12, 2013 at 6:09 pm

    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
      October 14, 2013 at 5:07 pm

      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
      February 10, 2014 at 11:20 am

      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

    • RMA
      February 9, 2015 at 12:34 am

      The Pi was designed to give children/people a way to learn computing and programming without risking the cost of a full blown computer. The fact that it's small makes it a nice media center, but mostly it's for creating little projects and enjoying the process of creating something.

      Unfortunately the Internet is full of trolls who will try to make everything that may be interesting to children lame, while they sit back and play with their PS4 and learn absolutely nothing.

  37. Jim Easterbrook
    September 12, 2013 at 4:57 pm

    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
      September 12, 2013 at 5:58 pm

      Awesome, thanks Jim!

  38. John
    September 12, 2013 at 3:47 pm

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

  39. RasPi
    September 11, 2013 at 6:10 pm

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

    • James B
      September 12, 2013 at 5:58 pm

      See Jim's comment below!

  40. R Sail
    September 7, 2013 at 8:12 am

    is this like an automated spamming machine..

    • Chip
      September 10, 2013 at 10:18 am

      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.

  41. Patrick
    September 6, 2013 at 5:01 pm

    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.

  42. joel
    September 6, 2013 at 3:54 pm

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

    • James B
      September 6, 2013 at 3:59 pm

      You want me to write code, on a video?

    • Daniel E
      September 7, 2013 at 4:53 am

      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?

    • Almark
      December 24, 2014 at 6:39 am

      I don't own a Pi 'though I want one' Instead I'm using an old P3 in my closest and your tutorial is the 'only' one of the net that made any sense, thank you. The confusion has ended!

Leave a Reply

Your email address will not be published. Required fields are marked *