Raspberry Pi Connect To Twitter Account Using Tweepy – Installation and Tweet CPU Temperature Example

After some inspiration from the pi bot on twitter I wanted to investigate how easy it is to connect my pi a spare account and tweet messages from the command line. The following tutorial will outline everything you need to get your first tweets sent. I have extended this to tweet the current cpu temperature on the pi board. There are a number of sensors and I will eventually be switching to also monitor the air temperature around the pi.

The raspberry pi will come with python pre-installed so it makes sense we use this language to do the work in this project. Before we begin it always useful to run an apt-get update to ensure all of your packages are running the best versions. We will start off by installing python-setuptools which essentially allows you to install, update, remove python packages nice and easy. We will be using a package called tweepy which has everything inside that we need to send our messages out to twitter.

To Install the setup tools and tweepy carry out the following commands:

pi@raspberrypi ~ $ sudo apt-get install python-setuptools
pi@raspberrypi ~ $ sudo easy_install pip
pi@raspberrypi ~ $ sudo pip install tweepy

Once these have all installed correctly we will need to head over to the twitter developer area to register an application against our twitter account. The link for this can be found here.

You will need to then carry out the following steps in order to get access keys and consumer keys which will allow us to authenticate the twitter account and application without having to keep entering in login data. This uses the OAuth protocol which you can find out more about using google!

  1. Select create a new application
  2. Enter name, description, website
  3. Select Yes I agree to the terms and conditions
  4. Enter captcha information and click submit

You will see that by default the access level is set to read only. We will need to change this to read/write to enable us to push tweets out to the world. To change this settings carry out the following steps.

  1. Select settings along top menu tabs
  2. Under application type select Read and Write
  3. Ensure that “Allow this application to be used to Sign in with Twitter” is checked
  4. Click the update this twitter applications settings button at the bottom of the page

If you now return to the Details tab you will see a number of special keys which include, consumer key/secret and access token/secret. Leave the webpage open as we will need all of this information in a minute to start tweeting.

As in my previous projects I have a directory set up already for my project files. It is housed under my /home/pi folder in a very original folder name called Projects.

I will now create a new folder called Twitter within this Projects folder but you can choose to save your files wherever you feel is relevant.

pi@raspberrypi ~ $ sudo mkdir /home/pi/Projects/Twitter
pi@raspberrypi ~ $ cd /home/pi/Projects/Twitter
pi@raspberrypi ~/Projects/Twitter $ 

Within this director I will create a file to house my python code that will do all of the work called Tweeter.

pi@raspberrypi ~/Projects/Twitter $ sudo nano Tweeter.py

This will open up a new blank file for us where we can paste the following python code.

#!/usr/bin/env python

import sys
import tweepy

CONSUMER_KEY = '***************YOUR DATA*****************'
CONSUMER_SECRET = '***************YOUR DATA*****************'
ACCESS_KEY = '***************YOUR DATA*****************'
ACCESS_SECRET = '***************YOUR DATA*****************'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)

What you now need to do is take all of the relevant key and secret information from the twitter application site we were using earlier and paste the relevant parts into the above file where I have marked “***************YOUR DATA*****************”.

Once you have done this use CTRL+X then Y to save your file.

The above code will allow us to stipulate exactly what we want to send to from the command line. I like to first though ensure my file is executable so run the following.

pi@raspberrypi ~/Projects/Twitter $ sudo chmod 755 Tweeter.py

We are now set! To send out your first tweet run the following command.

pi@raspberrypi ~/Projects/Twitter $ python Tweeter.py 'Hello World!'
pi@raspberrypi ~/Projects/Twitter $

As long as you get nothing returned by that call then everything has worked perfectly, head over to your twitter feed and you should see your Hello World tweet!

For now this is not all that useful however there is now the opportunity to expand on this initial example and make it in to something so much more awesome. At the start of the tutorial I said I wanted to tweet the current CPU temperature and eventually the temperature of the environment around the pi. I will show you the code required to get the current CPU temperature running.

We will first create a second python file so we do not destroy the hard work we have just carried out.

pi@raspberrypi ~/Projects/Twitter $ sudo nano Tweet_Status.py

You can then copy and paste the following code directly into the file.

#!/usr/bin/env python
import os
import sys
import tweepy

ACCESS_KEY = '*****YOUR DATA******'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)

cmd = '/opt/vc/bin/vcgencmd measure_temp'
line = os.popen(cmd).readline().strip()
temp = line.split('=')[1].split("'")[0]

api.update_status('My Current Processor Temperature: '+ temp + ' C')

Once again you will need to replace the YOUR DATA place holders with your keys/secrets etc from earlier. The above file now contains code that will ask the pi to output its current cpu temperature to the command line, read it and then format it in a nice way and push it out to twitter via the api.update_status call. There are many temperature sensors we can plug into on the pi and also even measure voltages so you can expand this script if you like to include a full system overview.

We can now save the file and close it with Ctrl + x and then Y.

Once again we need to ensure the file is executable.

pi@raspberrypi ~/Projects/Twitter $ sudo chmod 755 Tweet_Status.py

If you now run this file your twitter feed should show the current CPU temperature.

pi@raspberrypi ~/Projects/Twitter $ python Tweet_Status.py
pi@raspberrypi ~/Projects/Twitter $

We can now use a cron job (Scheduled Task) to run this script every hour so we get a constant update on twitter about our CPU temp.

To edit the root cron file you must run the following command.

pi@raspberrypi ~/Projects/Twitter $ sudo crontab -e

It is very important to ensure the sudo command is used!
Once you are in the file you can then add the following line, just change the directory to point to where your file is saved.

*/60 * * * * python /home/pi/Projects/Twitter/Tweet_Status.py

Thats it all done.. if you have any feedback please leave a comment!

You may also like...

28 Responses

  1. Hello
    Thank you for your article. It is working on my RPi and i can send tweets. A question i have is HOW TO RECIEVE TWEETS AND HOW TO READ THE TWEET? We are doing a project where we are trying to connect the RPi to the Traffic light and we are change the signal by sending a tweet i.e RED/GREEN/YELLOW. I need the coding to read make RPi read the tweet and put hi/low voltage signal to the output pin, resulting in the signal changing. I will look forword for your reply.

    Thank You for your help.

  2. Moe says:

    Its a great tutorial, i tried tweeting but I keep getting errors & i have tried everything before posting this here, any idea why it’s throwing this error back?

    raise TweepError(error_msg, resp)
    tweepy.error.TweepError: [{u’message’: u’Invalid or expired token’, u’code’: 89}

    • MrMobberley says:

      If this is a new twitter account give it a few hours to setup correctly I have seen this happen a couple of times when working with new accounts. Also check your authorisation keys for blank spaces which can cause issues and also in your code. If still no luck I would try stackoverflow.com the guys there can help with specific issues like this quite quickly.

      • Moe says:

        Thank you for the reply,I I will check with Stackoverflow peeps however I am now getting this:

        raise TweepError(error_msg, resp)
        tweepy.error.TweepError: [{u’message’: u’Timestamp out of bounds’, u’code’: 135}

        any idea?

        • Moe says:

          My bad, the time and date on the pi were all wrong, therefor throwing the last error.

          and you were right about it taking time for new accounts.

          Thank you for the tut & the support, keep the good posts coming :)

  3. Garrettishere says:

    Thanks a bunch for this. I need a command line tool in order for my flare detection service, @RealtimeFlares, to function. I use one account to tweet the flares and another to send regularly scheduled updates. It was ugly; I was using multiple command line tools because non-OAuth tools only allow one account to be authenticated at a time. Twitter just updated their API so both tools are down until the code is updated. I had looked at OAuth before briefly but it looked messy so I abandoned that route pretty quickly.

    This guide has totally changed that and has saved me a lot of time. Thanks and really looking forward to this added flexibility of having multiple accounts authenticated.

  4. rpiph1 says:

    Excellent tutorial. Worked perfectly the first time I tried it! Thank you. Gave you props on my newly minted blog

  5. jose pablo says:


    yo ejecuto el script y la primera vez funciona correctamente. Despues aparece el siguiente error:
    python tweet.py
    Traceback (most recent call last):
    File “tweet.py”, line 19, in
    api.update_status(‘Asi de caliente estoy: ‘+ temp + ‘ C’)
    File “/usr/local/lib/python2.7/dist-packages/tweepy/binder.py”, line 197, in _call
    return method.execute()
    File “/usr/local/lib/python2.7/dist-packages/tweepy/binder.py”, line 173, in execute
    raise TweepError(error_msg, resp)
    tweepy.error.TweepError: [{u'message': u'Status is a duplicate', u'code': 187}]

    Lo pongo en cron y funciona cada hora pero de vez en cuando no envia y los logs me muestran este errror.

    ¿alguna sugerencia?


    • David says:

      Hola que tal amigo si pudiste solucionar tu problema yo no he podido ni enviar el Tweet como le hiciste?? Saludos

  6. Enzo says:

    Can you please tell me how can i add Uptime to this script? I wanna Twitt Temp and Uptime in the same twitt.TNX

  7. Ryan says:

    Great tutorial, thanks! I’m having trouble with single quotes within the tweets I’m trying to send. For example, the command, “$ Tweeter.py ‘I’m using @Raspberry_Pi’s command line to send tweets!’ ” is published as “Im”.

    It seems as though the second single quote tells the API that the tweet is over, but why is the ‘m’ still included?

    Also, sometimes after typing the command as above will call the > on the next line. I then have to enter the tweet without the single quotes and hit enter for it to go through.

    Any thoughts? Thanks again for a great walkthrough.

  8. Jon says:

    I have followed the instructions above but I am recieving the following error. Anyone have any ideas?

    pi@raspberrypi ~/projects $ sudo python tweeter.py
    Traceback (most recent call last):
    File “tweeter.py”, line 15, in
    File “/usr/local/lib/python2.7/dist-packages/tweepy-2.1-py2.7.egg/tweepy/binder.py”, line 197, in _call
    return method.execute()
    File “/usr/local/lib/python2.7/dist-packages/tweepy-2.1-py2.7.egg/tweepy/binder.py”, line 154, in execute
    raise TweepError(‘Failed to send request: %s’ % e)
    tweepy.error.TweepError: Failed to send request: [Errno -5] No address associated with hostname

  9. David says:

    pi@raspberrypi ~/Projects/Twitter $ python Tweeter.py ‘Hello World!’
    Traceback (most recent call last):
    File “Tweeter.py”, line 15, in
    File “/usr/local/lib/python2.7/dist-packages/tweepy/binder.py”, line 197, in _call
    return method.execute()
    File “/usr/local/lib/python2.7/dist-packages/tweepy/binder.py”, line 173, in execute
    raise TweepError(error_msg, resp)
    tweepy.error.TweepError: Read-only application cannot POST

  10. Earl says:

    I’ve set everything up and double-checked the code, but I still keep getting a syntax error for line 9 (the ACCESS_SECRET).

    It reads as:

    pi@raspbmc:~/Twitter$ python Tweeter.py ‘Hello World!’
    File “Tweeter.py”, line 9
    ACCESS_SECRET = (My info here, obvs)

    SyntaxError: invalid syntax

    Any suggestions? Otherwise it seems fine, but it just says this over and over.

    • MrMobberley says:

      Hi earl, give it a few hours I know a few issues can happen because the access key does not seem to work straight away. Weird but it happened to a few in previous comments. Otherwise if its still stuck paste your file and I’ll take a look

  11. dineshauti says:

    Thanks. Helped me a lot :-)

  1. June 9, 2013

    [...] I used to write this Raspberry twitter tutorial, DS1820B [...]

  2. June 12, 2013

    [...] made a Twitter account for my Pi, @welbegone. I set it up using a super-simple Pi + Twitter tutorial featuring the Python library [...]

  3. August 21, 2013

    […] Una vez tenemos instalado el sistema vamos a necesitar instalar tweepy para que se puedan enviar tweets a través de Python, además necesitaremos tener una cuenta de Twitter con una aplicación registrada a dicha cuenta. Un ejemplo muy interesante para realizar estas acciones es este tutorial. […]

  4. October 7, 2013

    […] After some inspiration from the pi bot on twitter I wanted to investigate how easy it is to connect my pi a spare account and tweet messages from the command line. The following tutorial will outli…  […]

  5. October 29, 2013

    … [Trackback]

    [...] Read More here: c-mobberley.com/wordpress/index.php/2013/04/26/raspberry-pi-connect-to-twitter-account-using-tweepy-installation-and-tweet-cpu-temperature-example/ [...]

  6. November 7, 2013

    […] Tweepy – example to show R-Pi tweeting its CPU […]

  7. November 17, 2013

    […] Once had done this, the next step was to install tweepy to post tweets through Python. A Twitter account with a registered application is required. A very interesting example to perform these actions is this tutorial. […]

  8. February 6, 2014

    […] got the ‘tweet the cpu temperature’ idea from Chris Mobberly’s blog. Here’s a condensed code snippet we’re going to borrow from […]

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>