How to Write a Twitter Bot in Python
For the purposes of this post, a Twitter bot is a program that automatically posts status updates to its account (we’re assuming the bot is associated with an account), perhaps also responding to @ messages sent to it.
I’ve wanted to write one for a while, just for the fun of it.
What we’ll build: I’m hooking up the Twitter API to an Eliza program, so that when you send it an @-message, it will reply with some silly psychoanalysis.
What you’ll need:
- Mike Verdone’s excellent Twitter Tools for Python, which presents an easy-to-use abstraction over the Twitter API.
- I’m also using a Python version of Eliza by Jez Higgins.
Before you get started install Twitter Tools using the accompanying setup.py. This will leave you with a command-line tool called “twitter”. Run “twitter authorize” to do the OAuth dance through the web-browser, give the resulting PIN back to the command-line tool, and have it cache your credentials locally. Future invocations of the API will need this.
The overall structure of the bot is to repeat the following in an infinite loop:
- Search for @-mentions to me.
- Reply to the authors of those @-mentions.
There is one remaining piece to the puzzle: you don’t want to reply more than once to a given @-mention, so you need some way to remember which ones you’re already replied to. Turns out, there’s a simple way to do that. The Twitter search API supports a parameter called “since_id”, which, when provided, only returns search results later than that ID. So all you have to do is remember the ID of the last message you replied to, and only request results from that point on.
The code is pretty simple, barely sixty-something lines, and you can see it on github.
The result of this is the_shrinkbot, a Twitter account which, if you sent it an @-message, will reply with some Eliza-like psychoanalysis. (The bot runs on my laptop, so will have periods of downtime.)
Go build your own!