How to Build a Raspberry Pi Twitter Bot

In this project, we will be exploring how to set up a basic low-cost Raspberry Pi Twitter Bot utilizing the Python programming language.

Raspberry PI Twitter Bot

In this Twitter bot tutorial, we will be showing you how to write the script while implementing the Twython package, and you will be amazed at how easy it is to set up. We will also be exploring how to use the Twython package and its major functions.

We will also be showing you how to make the Twitter Bot tweet your Raspberry Pi’s CPU Temperature or periodically take a photo and upload it as a tweet.

You can use your Raspberry Pi Twitter bot to automate a huge range of different tasks, these range from posting a picture to your Twitter account every hour to monitor the growth of a plant or even tweeting out values from sensors connected to your Raspberry Pi.

This tutorial is now archived and no longer actively maintained

Equipment List

Below are all the bits and pieces that I used for this Raspberry Pi Twitter Bot tutorial.

Recommended

Optional

Registering a Twitter App

1. This tutorial is now archived and no longer actively maintained. Please proceed cautiously; things are likely to no longer work.

To use the Twitter API, we will first have to register our account as a Twitter app. This API will allow us to use the REST interface and is what we will be utilizing to post new tweets to Twitter and generally interact with the website.

Once you are logged into the Twitter account you plan on using, go to Twitter’s New App page. You will be shown the screen below.

The three main things you need to focus on here is the Name, Description, and Website you can set these to whatever you like as this will not be a user-facing application. Callback URL can be left blank as we don’t need any callbacks. Once done you can click the “Create your Twitter Application” button.

Twitter Bot Create an application

2. After you have created your Twitter App, you will be taken to the page displayed below, on here click the “Keys and Access Tokens” tab.

Twitter Bot Application Manager

3. On this screen, you will want to copy down both the Consumer Key (API Key) and the Consumer Secret (API Secret). We will need both of these to connect to the Twitter API.

You can ignore both the Owner and Owner ID as we don’t require these to interact with the API.

After copying down these two different values click the “Create my access token” (2.) button.

Twitter Keys and Access Token

4. After you have created the access token, the page will refresh. Scroll down to the bottom of the page and copy down both the Access Token and the Access Token Secret. These are the final values we need to be able to set up our Raspberry Pi Twitter Bot.

Twitter Access Tokens

Setting up and writing the Twitter Bot for the Raspberry Pi

1. With our API tokens handy we can now start setting up and writing our Raspberry Pi Twitter bot. The first thing we should do is make sure our Raspberry Pi is up to date by running the following commands on it.

sudo apt update
sudo apt upgrade

2. With the Raspberry Pi now updated let’s install the tools we will need to set up our Raspberry Pi Twitter Bot. We will be utilizing the Python package twython to interact with Twitter’s API. Let’s begin installing the packages by running the next few commands in the terminal.

sudo apt install python-setuptools
sudo easy_install pip
sudo pip install twython

3. Finally, we can begin writing the Twitter bot on the Raspberry Pi. Thanks to the Twython package that we just installed this is incredibly easy to do.

First, let’s make a directory where we will keep our script and begin writing the script by running the following commands.

mkdir ~/twitterbot
cd ~/twitterbot
sudo nano TwitterBot.py

4. Now in this file, let’s write in the following piece of code. This code is incredibly simple thanks to the Twython library, and we will explain what each piece of the code does before we write it, so you get an idea of how it all works.

from twython import Twython – We use this to make API calls to Twitter, and it simplifies the Python script a lot.

import sys – Imports the sys library which we use to grab the system arguments that are passed to the script.

The next block of code defines the various keys that we wrote down earlier in the tutorial, and we pass these values into Twython. Make sure you replace the values of CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, and ACCESS_SECRET before proceeding.

We then define our variable API which stores the Twython object, we create this object with all our access and consumer keys. This object makes doing API calls to Twitter simple as all the data is there ready for it to use.

Finally, we issue a update_status API call to our api object. This call should tweet any text that is passed into the script to your Twitter account.

#!/usr/bin/env python
import sys
from twython import Twython

#Define our constant variables, this is all the data we wrote down in the first part of the tutorial.
CONSUMER_KEY = '***************YOUR DATA*****************'
CONSUMER_SECRET = '***************YOUR DATA*****************'
ACCESS_KEY = '***************YOUR DATA*****************'
ACCESS_SECRET = '***************YOUR DATA*****************'

#Create a copy of the Twython object with all our keys and secrets to allow easy commands.
api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) 

#Using our newly created object, utilize the update_status to send in the text passed in through CMD
api.update_status(status=sys.argv[1])

Once you have finished writing in the code, save the file by pressing CTRL + X then Y and then hitting ENTER.

5. With the Twitter Bot script now written, we need to make the script executable, so we can send our text by passing it to the Python file as an argument. To make the script executable we use the chmod command.

sudo chmod +x TwitterBot.py

6. Now let’s test out the Twitter Bot script by running the following command, this will make sure that we are making a valid connection with the Twitter API and ensure we have written. After the command has run, check your Twitter account to see the new tweet.

sudo python TwitterBot.py "This is a test tweet from PiMyLifeUps Twitter bot"

7. Once you have confirmed that the tweet was successfully sent we can start doing a few more interesting things with the Twitter Bot, just sending a simple message is kind of boring after all.

Our next two sections will explore both making the Twitter bot send out an image taken from a webcam and also show you how to get the Twitter bot to tweet out the Raspberry Pi’s CPU temperatures.

First, off we are going to explore grabbing the CPU temperature and tweeting that out if you are more interested in the webcam picture sending then you can skip on further down the page.

Tweeting the Raspberry Pi’s CPU Temperature

1. Let’s begin by editing the Twitter Bot script by running the following command on our Raspberry Pi.

sudo nano TwitterBot.py

2. Now that we have opened up the fire we can make the following changes.

Find

import sys

Replace With

import os

Since we no longer need to worry about arguments being passed in, we can replace the sys library with our new os library. The OS library allows us to interact with the operating system itself, and in our case, we will be using it to issue a command on the OS and get the result. You will see this in our next lot of code changes.

Find

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

Replace With

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')

Basically, what this bit of code does is issue a command into Raspbian’s terminal, this command calls a binary file that returns the Raspberry Pi’s temperature. We then process this file to grab the correct value that we are after and then simply send out a Tweet with the update_status command that has the value we caught.

Once you have finished writing in the code, save the file by pressing CTRL + X then Y and then hitting ENTER.

3. We can test out this new piece of code by running the following command on our Raspberry Pi.

python TwitterBot.py

If you check out your Twitter account, you will notice that you will have a new tweet that displays your Raspberry Pi’s CPU temperature.

With that done, you can now skip down to our automating your Raspberry Pi Twitter Bot section unless you want to learn how to send webcam photos from your Raspberry Pi to Twitter.

Tweeting Webcam Photos via your Raspberry Pi Twitter Bot

1. Let’s begin by editing the Twitter Bot script by running the following command on our Raspberry Pi.

sudo nano TwitterBot.py

2. Now we can make the following changes to our bot to make it send an image from an attached video interface.

Find

import sys

Replace With

import pygame
import pygame.camera
from pygame.locals import *

We replace the sys library with pygame as we no longer need to grab any variables passed into the script. Pygame is a library that contains a large range of Python modules designed for writing games. Of course, we aren’t writing a game, but pygame has an excellent and easy to use module for utilizing cameras so we will be making use of that module to set up our Raspberry Pi Twitter Bot.

Find

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

Replace With

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')

photo = open('webcam.jpg','rb')
api.update_status_with_media(media=photo, status='Test Raspberry Pi Image Bot => ')

We need first to replace the original update_status call with several other calls. The first function that we add sets up and initializes the pygame library. We then proceed to initiate pygame’s camera module, and this sets itself up so we can get it to read from one of our interfaces.

We then store a copy of the camera object in our cam variable, setting it up to use our /dev/video0 interface and use the resolution of 640×480 for pictures we capture from the device.

Once we have done that, we can use the new object and start the camera up, and this allows us to grab images off the camera which we do in the following line of code.

With the image now saved to the Raspberry Pi, all we need to do is read back in that image using the open function, and then making use of another handy Twython function.

This function is update_status_with_media, and it allows us to send a tweet with an image which is perfect for sending our just grabbed webcam photo.

Once you have finished writing in the code, save the file by pressing Ctrl + X then Y and then hitting Enter.

3. Please note if you are using your Raspberry Pi camera as your webcam, make sure you run the command below before running this script. This command allows it to appear as a /dev/video* interface.

sudo modprobe bcm2835-v4l2

4. We can test out this new piece of code by running the following command.

python TwitterBot.py

With that done, you can now skip down to our automating your Twitter Bot section.

Automating your Twitter Bot

1. There isn’t much use in your Twitter Bot if you must manually run it all the time, one of the best ways to get your bot to be continually triggered is to use Cron Jobs.

You may be wondering why we just don’t run the script in a continuous loop, well two reasons for this is that there is no guarantee that the script won’t hang at some point, the other is that it burns up precious processing cycles having to continually loop and check whether we should be tweeting out.

So now let’s begin by editing the crontab by running the following command.

sudo crontab -e

2. To this file you want to add the line of text below to the bottom of the file, basically what this will do is automatically trigger the script every hour.

If you want to work out your own times for when you want the script to trigger but are not used to dealing with Cron Jobs, you can try using an online tool such as our Crontab generator. It will give a human-readable version of the cron schedule. Just replace */60 * * * * with your generated value.

*/60 * * * * python /home/pi/twitterbot/TwitterBot.py

Once you have finished writing in the code, save the file by pressing Ctrl + X then Y and then hitting Enter.

You should now hopefully have a fully operational basic Twitter Bot that will continuously tweet out every time the cron job goes off. We hope we have explained the code enough and kept it basic enough that you can easily extend the bot to do more complicated tasks.

If you enjoyed this Raspberry Pi Twitter bot tutorial, you can also check out our Twitch moderator bot tutorial as well. If you have any feedback or have run into any issues with this tutorial, then feel free to leave a comment below.

11 Comments

  1. Avatar for Eric
    Eric on

    How do you rotate the image with pygame? I rotate it 270 degrees (or -90)

    1. Avatar for Eric
      Eric on

      I got it to work with the code below. Also the update_status_with_media has been deprecated and replaced with upload_media.

      image=cam.get_image()
      rot_image = pygame.transform.rotate(image,90)
      pygame.image.save(rot_image, ‘webcam.jpg’)

  2. Avatar for Pauli Isoaho
    Pauli Isoaho on

    How to see the tweets?
    After this command “sudo python TwitterBot.py “This is a test tweet from PiMyLifeUps Twitter bot”

    1. Avatar for Emmet
      Emmet on
      Editor

      Hi Pauli,

      The tweets will appear on the twitter account that you connected during this tutorial.

      Cheers,
      Emmet

  3. Avatar for ARS
    ARS on

    How do you make Celsius show as Fahrenheit?

    1. Avatar for Emmet
      Emmet on
      Editor

      Hi ARS,

      You simply need to convert the number from celsius to farenheit using some basic math.

      Add this below the existing temp = line to convert it from Celsius to farenheit.
      temp = 9.0/5.0 * temp + 32

      Cheers,
      Emmet

  4. Avatar for Muhammad Izzuan Bin Ariffin
    Muhammad Izzuan Bin Ariffin on

    Is there a possible way to mention other users by using the twython?

  5. Avatar for megan_xls
    megan_xls on

    I get an ImportError: No module named requests_oauthlib

  6. Avatar for unveiled
    unveiled on

    I get an ImportError: No module named requests_oauthlib

    1. Avatar for megan_xls
      megan_xls on

      I’ve solved it,
      use
      sudo pip install requests_oauthlib

  7. Avatar for Mike
    Mike on

    Great write ups.. I have made more than a few things by following your tutorials.

    Thanks for the resources.

Comments are closed.