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

Our Raspberry Pi Twitter bot we will be showing you how to write and setup is made easy thanks to the Twython package. We will be exploring how to use the Twython package and it’s to 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 ever hour to monitor the growth of a plant or even tweeting out values from sensors connected to your Raspberry Pi.

Equipment List

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

Recommended:

Raspberry Pi 2 or 3

Micro SD Card

Ethernet Cord or Wifi dongle (The Pi 3 has WiFi inbuilt)

Optional:

Raspberry Pi Case

Registering a Twitter app

1. In order to use the Twitter API, we will first have to register our account as a Twitter app. This 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 Twitters 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 into 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 setup 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-get update
sudo apt-get upgrade

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

sudo apt-get 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, lets write in the following piece of code. This code is incredibly simple thanks to the Twython library, 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, 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, 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 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 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])

One 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 know make the script executable so we can send our text by passing it to the Python file as an argument.

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 ran, 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 succesfully 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, 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 grabbed.

One 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 checkout 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 also 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 setup 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 to first 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, 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, 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, it allows us to send a tweet with an image which is perfect for sending our just grabbed webcam photo.

One 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 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 wont 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 cron tab 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 Crontab Guru as 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

One 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 constantly 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 checkout our Twitch moderator bot tutorial as well. If you have any feedback or have ran into any issues with this tutorial feel free to drop a command below!

The Raspberry Pi Crash Course

The Raspberry Pi Crash Course

Enter your email address below to get the

Raspberry Pi crash course delivered straight to your inbox

Please check your inbox for a confirmation email!