Introduction: Raspberry Pi Twitterbot

I've written many "how-to" guides for the Raspberry Pi in my quest to learn this platform.

One of my art projects for 2014 has been Bot Collective— an ongoing project where I make Twitterbots that "live" on the Raspberry Pi and have physical bodies. I've defintely become familiar with how to make a Pi into a Twitter engine and want to share my knowledge.

I'd like to see many Bot Friends in the Twitterverse.

This Instructable will show you how to set up your Raspberry Pi to send Twitter messages. 

I learned most of this from this makeuseof guide, which was nearly complete. I wanted to cover the additional steps of setting up your application via Twitter. But the rest of this guide has been invaluable to me.

Before doing this Instructable, please make sure you have your Raspberry Pi up and running, which you can do with The Ultimate Raspberry Pi Configuration Guide Instructable.

I'm using the Mac OS for this guide, but you can extend the principles to other operating systems.

Step 1: Install Twython Packages

I'm using ssh to access to Raspberry Pi. My IP address for the SD card for this is 10.0.1.62. Your IP address may be different — just change the address accordingly.

Open the Terminal window and on the command line, type:
ssh pi@10.0.1.62
If you are running directly hooked into the monitor, you can skip this step.

Run the latest package updates and upgrades, just to make sure everything is current — you will have to have wifi access for this step. Type in the commands:
sudo apt-get update

sudo apt-get upgrade
There will be a lot of waiting and Linux garble, so take break and pet your cat. Now, install the Twython libraries, which will let you use Twitter from Python using these three commands:
sudo apt-get install python-setuptools
sudo easy_install pip
sudo pip install twython
You'll see more Linux stuff and then you should be good to go.

Step 2: Create Email for Account

Every Twitter account requires an email address, and your Twitterbot will need to have a unique one.

You can register for a free account with Yahoo, Gmail and many others.

I have by own ISP and about 10 Twitterbots, and so I create an email address for each one through my ISP. My Twitterbots also value their privacy, so the ISP option is a good one.

Step 3: Create Twitter Account

This is pretty straightforward, but login to Twitter and make a Twitterbot handle.

You'll have to go through their steps of following several people or organizations and verification via email.

Step 4: Add Your Mobile Phone to Account

You'll need this for a later step, but do it now. To activate a Twitter app, you'll need a mobile phone number tried to your account for verification. We can remove this later.

Go to Settings and check out the Mobile tab.

Add your phone number and verify the text with Twitter (GO 40404).

Turn off text notifications at the next dialog box and then leave this tab open in your browser.

Step 5: Create Twitter App

This may change if Twitter changes their application protocol, but here's the procedure for the time being:

Go to https://apps.twitter.com/ and click on Create New App

At the Create an Application dialog box, enter:
- Name of your application
- Description
- Link to valid URL (this can be changed later)

Leave the Callback URL field empty

Read the terms of agreement and agree to them and then OK the dialog


Step 6: Modify Permissions for Read/write

Twitter will take you to a page for Application Settings (I blacked out my API key for security reason).

The first thing you'll need to do is change the permission, click on modify permissions on the Access level tab

Choose either Read and Write or Read, Write and Access direct messages, the latter if your Twitterbot will parse DMs.
 
Click on Update Settings. If you get the error that you need to add your mobile phone to your account, then you probably skipped the "Add mobile phone to account" step of this Instructable.

Click on the Details tab and then you're back at the Application Settings dialog. Wait for a minute and click on Refresh until your Access level changes to Read/Write.


Step 7: Get Access Token and API Keys

Click on the API Keys Tab, and you will see a dialog with your API keys. What we want to do now is create your Access Token. Click on the Create Access Token button and you will be given an Access token + secret.

This may take a minute, so hit refresh on your browser after a few seconds until you get a dialog box like this (once again, I've blacked out my private information).

Copy the alphanumeric strings for the API key, API secret, Access token and Access token secret to a secure location like 1Password at least to a text file or to Evernote.

Step 8: Delete Your Mobile Phone Number From the Account

We don't need the mobile phone number on your Twitter account, so go back to this screen and choose Delete phone

Step 9: Create a Python Test Script

ssh into your Raspberry Pi, or else use the monitor. In this case, I prefer ssh, since I can copy-and-paste the application keys directly.
nano tweet_test.py
Try this script, only with your API key, API secret, Access token and Access token secret. Put a different string in than my RIP string — this is for testing JustDiedBot.

And substitute your own api key, api secret, access token and access token secret instead of using these.

--------

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

tweetStr = "RIP Peeraphan Palusuk, 68, Thai politician, Minister of Science and Technology (since 2013), MP for Yasothon (since 1985)"

# your twitter consumer and access information goes here
# note: these are garbage strings and won't work
apiKey = 'roasdkoqwkk8i10kwks09aka'
apiSecret = '4ghmkjal810kdla0wkkoasi'
accessToken = '1239821-dakos81koamow9918ma0sadsqq'
accessTokenSecret = 'saklasooqjdoajfj8f9981mska01mdka09'

api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)

api.update_status(status=tweetStr)

print "Tweeted: " + tweetStr

---------

cntl-X, Return will save the script

(I know, I know, the variable names are different in the screenshot than the script I wrote. Busted).

Step 10: Run the Python Script and Check Out the Tweet

execute the Python script
python tweet_test.py
and you'll see the tweetStr output. In the case of JustDiedBot, it is this:
Tweeted: RIP Peeraphan Palusuk, 68, Thai politician, Minister of Science and Technology (since 2013), MP for Yasothon (since 1985)
Now go to Twitter and you should see your Tweet!

Step 11: Improve on the Technique

Now you should have sent single tweet.

You'll have to decide what kind of Twitterbot you'll want to do. Quotebots are an easy way to start and the first 6 bots for The Bot Collective were quotebots.

One thing you'll want to check out is using the crontab, which will let you do timed operations such as send a Tweet out every hour or once a day.

Word of warning: You'll want to be cautious about over-tweeting or spamming people with replies. This behavior might get your account suspended.

 Step 7 of my Launch Python script on Startup for Raspberry Pi covers timed events with crontab, as well as directing any crontab errors to an appropriate logfile.

This is another comprehensive crontab guide.

Step 12: Done!

We are done with the basic tutorial.

In the meantime, do check out JustDiedBot — it is up and running as of today!

Soon, I will be publishing the code and an Instructable on Twitter-scraping

I hope this was helpful!
Scott Kildall

For more on Raspberry Pi code and other projects, you can find me here:
@kildall or www.kildall.com/blog

Comments

author
mohndsmhmd (author)2017-01-20

question please,

I tried as you wrote but some error appear :

File "tweet_test.py", line 2, in <module>
from twython import Twython
File "/usr/lib/python2.7/dist-packages/twython/__init__.py", line 23, in <module>
from .api import Twython
File "/usr/lib/python2.7/dist-packages/twython/api.py", line 14, in <module>
from requests_oauthlib import OAuth1, OAuth2
ImportError: No module named requests_oauthlib

Can you help please.

thanks

author
SQLCodeMonkey (author)mohndsmhmd2017-05-21

I had the same issues with this. To correct it I ran: sudo pip install twython --upgrade

Once I did that it took care of the issue and my script started working.

author
mohndsmhmd (author)mohndsmhmd2017-01-21

I found the solution

it's should to do this :

sudo apt-get install -y python3-oauth python3-oauth2client python3-oauthlib python3-requests-oauthlib
author
shramik4954 (author)2017-04-19

can some 1 help me out with this error:

Exception in Tkinter callback

Traceback (most recent call last):

File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__

return self.func(*args)

File "/home/pi/mirror2.py", line 27, in callback

api.update_status(status=message)

File "/usr/local/lib/python3.4/dist-packages/twython/endpoints.py", line 112, in update_status

return self.post('statuses/update', params=params)

File "/usr/local/lib/python3.4/dist-packages/twython/api.py", line 268, in post

return self.request(endpoint, 'POST', params=params, version=version)

File "/usr/local/lib/python3.4/dist-packages/twython/api.py", line 258, in request

api_call=url)

File "/usr/local/lib/python3.4/dist-packages/twython/api.py", line 194, in _request

retry_after=response.headers.get('X-Rate-Limit-Reset'))

twython.exceptions.TwythonError: Twitter API returned a 403 (Forbidden), Status is a duplicate.

author
shramik4954 (author)shramik49542017-04-19

i have added a gpio push button to upload tweet from a choice of random messages .

for 1st button press the tweet is uploaded succesfully but for the second time onwards i get this errror

author
KanishkaV (author)2017-02-27

I would like to say thanks for providing this valuable stuff and this one is perfect post which told me the perfect way to control Raspberry Pi Twiiterbot.

https://www.promoocodes.com/

author
NixtestTest made it! (author)2017-02-26

Huge thanks for this article, it formed the foundation for what became @NixieBot on Twitter. Coming up on 50k tweets any day now! More details here: https://hackaday.io/project/9155-nixiebot
Source here: https://github.com/Zedsquared/NixieBot
Command list etc here: http://nixiebot.tumblr.com/ref

IMG_5699.JPGIMG_5700.JPG
author
T0BY (author)2016-11-28

Great idea, great Instructable!

author
RachelA67 (author)2016-07-12

Hey guys, great article! What are your thoughts on tools like https://www.tweetfavy.com and similar sites? I've been using their service to get more followers on my Twitter account, great stuff!

author

i wonder how can i tweet the picture by using this method ?

and if i can what is the thin that i need to do?

author

Yes, you can. It's been awhile since I've done this, so I can't remember off the top of my head.

But, my SelfiesBot project does this and here is the code on my GitHub repo, which you are welcome to adapt and try out.

https://github.com/scottkildall/SelfiesBot

Good luck!
Scott

author
Zer0h0 (author)2016-05-28

So i want to make the bot tweet random quotes i set up, How may i do that? Im a beginner in coding and i cant find this anywhere!

author
XxsonicxX (author)2016-04-19

Still kinda curious, how can I get what someone said on a website, and tweet that?

author
XxsonicxX (author)XxsonicxX2016-04-19

Also, can I tweet images?

author
scottkildall (author)XxsonicxX2016-04-19

yes indeed, check out these examples (both mine)

JustDiedBot - a Twitterbot that scrapes Wikipedia and tweets RIPs for recent deaths:
https://github.com/scottkildall/justdiedbot

SelfiesBot - a Twitterbot that tweets images of itself
https://github.com/scottkildall/SelfiesBot

have fun!

author
CarLeeToes made it! (author)2016-04-17

This is awesome! I made a bot to tweet whether my apartment complex got electricity or not! :) Thank you!

Capture.PNG
author
beavis2k (author)2016-04-13

Thanks for the instructable, got it running quick. I do get warnings "InsecurePlatformWarning" and "SNIMissingWarning" but the tweets get posted. installed various libraries/updates but still warns, but its working.

Modified the script to accept message from argument. I'll use it on my startup script to send me when it powers up, might also set it up for the ncid server, motion and temperature tweets :)

author
JeffHoover (author)2016-01-14

Great tutorial! I have a question though. Do you have any thoughts on how to address what twitter says:

Keep the "Consumer Secret" a secret. This key should never be human-readable in your application.

author
collinsarthur (author)2015-11-21

This is awesome

author
MartinG38 (author)2015-10-31

Hi Scott,

I made this, but I want to add a times tamp to the tweet it sends . What would be the best way to incorporate this in to the script?

Thanks

M

author
scottkildall (author)MartinG382015-10-31

Hi, the various threads on Stack Overflow will be help answer this question:

This one is pretty good:
http://stackoverflow.com/questions/13890935/timestamp-python

Best,
Scott

author
whataslacker (author)2015-09-09

So have to try this. Have you gotten a chance to "publish[ing] the code and an Instructable on Twitter-scraping"

author
marlin.vonkuenheim (author)2015-04-26

Hey. Awesome tut. But is there a way to let him favorite every tweet from the people he follows?

author
NilayK (author)2015-02-21

awesome tutorial

author
kantona80 made it! (author)2015-01-26

wow, great tutorial! I'm going to use it for my ipcam notifications!

raspberryPI.png
author
sakko303 (author)2014-09-12

Hello! I love your twitterbot idea. I came across your post looking for info on a project of my own. I am trying to create a Pi that will perform GPIO activity (blink LED, turn on sprinklers, whatever) when a twitter account receives a certain direct message.

My ultimate goal is to use Google Calendar, through IFTTT, to tweet my sprinklers on.

I hate my stupid commercial sprinkler controller this much.

author
lucazen (author)2014-07-11

Hi!

thank you for the great HOWTO, i made i small BOT that scrape the wikiquote of the day from the wikiquote atom feed service and tweet it every day! By now it is only for Italian, but well if you want follow me @RaspzenBOT.

Thank you!

Luca

About This Instructable

107,186views

246favorites

License:

Bio: Scott Kildall is an new media artist and researcher. He works at Autodesk, Pier 9 and is an artist-in-residence with the SETI Institute
More by scottkildall:Pier 9 Guide: Fusion 360 to OMAX WaterjetStrewn Fields: Waterjet Etching Into StonePier 9 Resource: Setting up 2D profiles for CNC in Fusion 360
Add instructable to: