Raspberry Pi Twitter Bot

The ability to automatically tweet messages is handy when you’re trying to promote a service to a wide audience.

I run a few blogs and youtube channels and typically I only tweet when I have new content to share, however some of my older content is still very well received and gets lots of new hits each day I often think it would be good to remind people on twitter about the content I have to share.

One of the exciting things about twitter is the ability to tweet using a simple computer program written in Python script and a raspberry can be configured to do this automatically at regular intervals.

By using a few basic concepts I’ve put together just such a program:

Step by step:

First you need a twitter account, assuming you already have one you need to set it up so the raspberry pi python script can talk to it. You can do this in the developer hub: https://dev.twitter.com/

  • In the tools menu at the bottom click ‘Manage Your Apps’, then click ‘Create New App’
TwitterBot

Twitter Developer New App Form

  • Complete the form and agree to the terms and conditions
Note - You can use any website if you don't have one of your own and the call back URL can be left blank

In the next screen you’ll see the settings of your newly created app.

  • Navigate to the Keys and Access Tokens tab and copy the keys below into notepad
    • Consumer Key (API Key)
    • Consumer Secret (API Secret)

2016-09-14_14-04-24

  • Further down the page ‘click the Create my access’ token button

2016-09-14_14-04-49

  • Copy the keys below into notepad:
    • Access Token
    • Access Token Secret

2016-09-14_14-06-28

You’ll need these keys later when you’re creating your raspberry pi python script.

  • Boot up your raspberry pi (I use Raspian as the operating system)
  • In the command prompt window enter these commands one at a time
sudo apt-get update 
sudo apt-get upgrade 
sudo apt-get install python-setuptools
sudo easy_install pip
sudo pip install twython

What you’re doing here is running general updates (always a good idea) and installing Twython. This is a Python module for interfacing with twitter!

  • Next using your File Manager create a folder for the Python Code to reside and a sub folder for images to be stored
Raspberry Pi File Manager

Raspberry Pi File Manager

  • Right click in your new TwitterBot folder and select ‘Create New… / Empty File’
  • Name that new file ‘TwitterBot.py’

Open up the new file and enter this code replacing the Keys with the ones you’ve just got from your twitter app:

from twython import Twython
import random

APP_KEY='Zc9T13kRPPSsUdKI2XTAWSqKu'
APP_SECRET='Kj44EClrSoK9XZwKNXM7QVKjgGP98t8koI8LShAYPaH3sRHxfl'
OAUTH_TOKEN='755722195649847296-o4Yr1LL4loqcc3fTCFhIYVbPipOyFoA'
OAUTH_TOKEN_SECRET='Kb2v2WwehktTRk3BASNykAP5giCX2RSZ3oaF4NMnLpzDP'

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)


RandomNumber = random.randint(1,4)
print RandomNumber

if RandomNumber==1:
    TweetMessage = 'Random Message 11111'
    TweetPhoto = '/home/pi/PythonProjects/TwitterBot/Images/Image1.JPG'

elif RandomNumber==2:
    TweetMessage = 'Random Message 2'
    TweetPhoto = '/home/pi/PythonProjects/TwitterBot/Images/RichardPearce.jpg'

elif RandomNumber==3:
    TweetMessage = 'Random Message 3'
    TweetPhoto = '/home/pi/PythonProjects/TwitterBot/Images/Image1.JPG'

elif RandomNumber==4:
    TweetMessage = 'Random Message 4'
    TweetPhoto = '/home/pi/PythonProjects/TwitterBot/Images/RichardPearce.jpg'

print TweetMessage
print TweetPhoto

photo = open(TweetPhoto,'rb')
twitter.update_status_with_media(media=photo, status=TweetMessage)

 

You’ll need to ensure you have the images in place before you run the code (F5), copy them to your image folder and rename them in the script above as required.

Going through the above script in stages, firstly we import the libraries we need:

from twython import Twython
import random

We then set up twitter (remember to use your own keys!):

APP_KEY='Zc9T13kRPPSsUdKI2XTAWSqKu'
APP_SECRET='Kj44EClrSoK9XZwKNXM7QVKjgGP98t8koI8LShAYPaH3sRHxfl'
OAUTH_TOKEN='755722195649847296-o4Yr1LL4loqcc3fTCFhIYVbPipOyFoA'
OAUTH_TOKEN_SECRET='Kb2v2WwehktTRk3BASNykAP5giCX2RSZ3oaF4NMnLpzDP'

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

We pick a random number between 1 and 4 (you will need to increase this if you have more messages):

RandomNumber = random.randint(1,4)
print RandomNumber

We then use a list of conditional if statements which check to see what number has been picked and for each one a different message and image can be used (we only have four at the moment), we use the full file path for the photo because we’re going to schedule it late:

if RandomNumber==1:
    TweetMessage = 'Random Message 11111'
    TweetPhoto = '/home/pi/PythonProjects/TwitterBot/Images/Image1.JPG'

elif RandomNumber==2:
    TweetMessage = 'Random Message 2'
    TweetPhoto = '/home/pi/PythonProjects/TwitterBot/Images/RichardPearce.jpg'

Finally we tweet the message:

print TweetMessage
print TweetPhoto

photo = open(TweetPhoto,'rb')
twitter.update_status_with_media(media=photo, status=TweetMessage)

You should be able to test this works by pressing F5 and checking your twitter account.

This is great so far but we need to improve a couple of things! I want to tweet something every day and I also want to make adding new tweets to the list a lot more simpler.

 

Scheduling the TwitterBot using Cron

To set up a schedule for when this program runs go back to your command promt and type

  • sudo crontab -e

Add the following line at the end of the file (its all on one line!!):


0 14 * * * python /home/pi/PythonProjects/TwitterBot/TwitterBot.py >> /home/pi/PythonProjects/TwitterBot/Script.log

You can use the first five operators in crom to specify the frequency:

 # ┌───────────── min (0 - 59)
 # │ ┌────────────── hour (0 - 23)
 # │ │ ┌─────────────── day of month (1 - 31)
 # │ │ │ ┌──────────────── month (1 - 12)
 # │ │ │ │ ┌───────────────── day of week (0 - 6) (0 to 6 are Sunday to
 # │ │ │ │ │                  Saturday, or use names; 7 is also Sunday)
 # │ │ │ │ │
 # │ │ │ │ │
 # * * * * *  command to execute

So in the example above the script will run at 2pm every day (https://en.wikipedia.org/wiki/Cron). I then specify it’s a python script with the full path to the file. The >> and the following path/file name is where the log will be written to.

  • Save the file and exit editor.
  • Now type Sudo Reboot

Your tweets will be flying out every day at 2pm…..

If you can’t wait that long change the schedule to every 10 mins in the crontab:
* /10 * * * python /home/pi/PythonProjects/TwitterBot/TwitterBot.py >> /home/pi/PythonProjects/TwitterBot/Script.log

 

Creating loads of new tweets

Of course you can just update the code adding more and more conditional if statements…. I would rather use excel to do this and I’ve created a simple excel document to help me:

Excel TwitterBot

  • Columns A – D I type in the message details, notice there’s 3 lines per message used
  • Columns F and G hold the code, if you look at the formula bar you can see it’s building up the required text so I can just copy and past it directly into my python script.

A good reason for doing this is you could add additional columns in excel and filter the data before you import it. For instance you may be focusing on a particular area of marketing and therefor you only want to use certain tweets. Or maybe you have a finish date column so once it’s out-of-date it will no longer be tweeted.

 

Next steps

Where do we go from here? well we could add some more functionality into the random aspect of the tweeting. For instance you may want to check special dates first such as Christmas Day. If it is you may want to pick just from those types of tweets. It would also be good if once a tweet has gone out you don’t re-tweet it for a while (if you have 100’s that may not be a problem). There’s plenty of improvements here although for a first attempt with limited knowledge it seems to work well so far!

I hope this has been useful, if you have any further ideas on how this can be improved I’d love to hear your comments below.

Richard

Advertisements

2 comments

  1. does not seem to work. Keep getting errors when I try to use the code: from twython Import Twython

    Like

    1. Did you install twython in the command window first?

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: