Blog by Sumana Harihareswara, Changeset founder
Fisher-Price's My First Twitter Bot
Hi, reader. I wrote this in 2013 and it's now more than five years old. So it may be very out of date; the world, and I, have changed a lot since I wrote it! I'm keeping this up for historical archive purposes, but the me of today may 100% disagree with what I said then. I rarely edit posts after publishing them, but if I do, I usually leave a note in italics to mark the edit and the reason. If this post is particularly offensive or breaches someone's privacy, please contact me.
On Sunday I wrote my first Twitter bot, with a bit of help from Leonard. (A Hacker School colleague inferred, understandably, that Leonard and I just write Twitter bots on the weekend, to relax.) Then yesterday I helped a peer get her first Twitter bot going, and decided to write it up for y'all/future Pythonistas.
Folks have already written other guides to writing good Twitter bots. Those more experienced people are better than I am at writing good, surprising bots, ones that respond to tiresome hashtags or argue with followers or what have you. My guide, in contrast, assumes that you already have some kind of code that spits out strings of 140 characters or fewer, and just want help interfacing with the Twitter API using Python so a Twitter account can say those tweets.
So!
pip install python-twitter
sudo pip install python-twitter
(The "consumer key/secret" pair identifies your "app" (the code you are writing) as something that is allowed to interact with the Twitter API; it's sort of a substitute for the User-Agent string in a browser. The "access token key/secret" pair authorizes the Twitter account whose tweets the "app" is gonna write. So conceivably you could write an app like Sycorax that lets your bot roleplay multiple accounts, and it would end up getting multiple access token key/secret pairs so that could work. This is all OAuth stuff that briefly turns you into an octopus when you understand it.)
Open up a new file in the same directory as your bot script, called something like "twitterapi.py". Also add "twitterapi.py" to your repository's .gitignore.
#!/wherever/you/put/python # ok, probably /usr/bin/python
import twitter
api = twitter.Api(consumer_key="KEY",
consumer_secret="SECRET",
access_token_key="KEY",
access_token_secret="SECRET")
from twitterapi import api
api.PostUpdate("wow\n so Program Assessment Rating Tool\nnice\n very budgetary")
import time
and stick a time.sleep(5*60)
line and an api.PostUpdate(awesomestring)
into a while True
loop.
* Is there a Snapchat desktop app? Maybe Snapchat is available for the iPad and in my hypothetical you're programming on your tablet? I don't know what people do these days.