How to create a Twitter bot
by Molly White on
This is the second of a two-part series on Twitter bots. This post discusses how to create them. The previous post covers what they are and some examples.
I write all my Twitter bots in Python, so I’ll focus on that in this post. That being said, you can write a Twitter bot in just about any language you please, and there is no shortage of Twitter API wrappers; the general strategy remains the same.
This post uses a very basic bot framework that I’ve put together, and I’d encourage you to fork it for your own bots. You should also be able to create your own from scratch using my instructions here.
Register a Twitter account
Possibly the hardest part of creating a Twitter bot is coming up with a good username that isn’t already taken. I can’t help much with that, but once you’ve come up with something, register the account. You can futz with the avatar, description, cover photo, and all that now, or wait until later.
Create the Twitter app
In order to post to a Twitter account automatically, you have to get access keys for your account. To do this, you have to register a Twitter app. Head over to apps.twitter.com and click “Create New App”.
You should note that you need to have a unique phone number associated with the Twitter account in order to create an app; this is a damn pain. For those such as myself who have more Twitter bots than we have phone numbers, there’s only one real solution, and it’s not a good one:
- Choose an account to use as your developer account and associate your phone number with it.
- Create a new account for your bot.
- Register the Twitter app for the bot on the developer account.
- Head over to Twitter API support and select "I need to transfer an API key to another account".
- Fill out the form (make sure you're still signed into the developer account).
- Wait an arbitrary amount of time (it's usually been about a week for me, but sometimes much longer) for someone at Twitter Support to manually transfer the key.
- Grumble about how there's got to be a better way to do this.
Once you create the account, it’ll ask you to fill out a few fields:
- Name: Whatever you want to call your bot.
- Description: A short description of what the bot does.
- Website: I usually just put down my own website or my Github, or the link to the Github repo for the given bot.
- Callback URL: You can skip this.
Check the box to agree to the developer agreement, and click create!
Go to the “Permissions” tab and set the access level your application needs. This will probably be “Read and write”.
Go to the “Keys and Access Tokens” tab of the application and click the “Create my access token” button under the “Your access token” heading.
Write the bot!
I’ve created a very simple bot framework to go along with this tutorial. It will give you the general structure, as well as some simple logging functionality, which I find very useful for debugging purposes.
This tutorial assumes some knowledge of Python. It’s also going to assume that your project is structured like so:
twitter-bot/ |-- bot.py |-- secrets.py
bot.py will hold all the code for the bot.
secrets.py will store your access keys, and should be added to your
.gitignore if you’re going to be publishing the code. Anyone with access to your keys can read or write from this Twitter account, so you really don’t want to make these public.
Pick your library
If you like making things difficult for yourself, or if you’re using a language without a Twitter library, then I suppose you can communicate with the Twitter API directly. Otherwise, I’d highly recommend picking one of the many Twitter libraries. My personal favorite is tweepy, and that’s what this tutorial uses.
Install tweepy by running
pip install tweepy. Now you can just
import tweepy at the top of
In order to read or write from the Twitter account, you need to authenticate.
Go back into the “Keys and Access Tokens” tab of your Twitter app. In secrets.py, add:
C_KEY = "" C_SECRET = "" A_TOKEN = "" A_TOKEN_SECRET = ""
Add the following from the Keys and Access Tokens page inside the quotation marks:
C_KEY: Consumer Key (API Key)
C_SECRET: Consumer Secret (API Secret)
A_TOKEN: Access Token
A_TOKEN_SECRET: Access Token Secret
Again, if you’re going to be publishing this code, it’s important that you don’t publish the
bot.py, add the following:
from secrets import * auth = tweepy.OAuthHandler(C_KEY, C_SECRET) auth.set_access_token(A_TOKEN, A_TOKEN_SECRET) api = tweepy.API(auth)
This bit is somewhat up to you. Part I of this series explains some types of bots and gives some examples, which might provide some inspiration. You’ll need to create the content yourself, but I can give you some resources that I’ve found to be really useful:
- News headlines: Guardian API, Google News RSS (needs to be parsed)
- News headlines filter ("tact"): offensive.py
- HTML parsing: BeautifulSoup
- Parts-of-speech tagging: topia.termextract
- Word and dictionary magic: Wordnik
- Rhymes: RhymeBrain API
- Weather information: Forecast.io API
- Markov chaining: cobe
- Interesting corpora
- Other APIs: Mashape
Once you’ve got your tweet all together, post it!
This only posts a standalone tweet. If you want to reply to another tweet, direct message someone, or do other fun things, check out the tweepy documentation.
There are a ton of ways to repeatedly post tweets. You could write it into the program itself and run it in the background, but my favorite approach is using cron jobs on my VPS. You could probably also use them on your personal computer, but you would need to ensure the machine was both on and awake when you wanted it to execute. Cron jobs will work on Linux and OSX, but if you’re using a Windows machine, you’ll probably need to research alternative approaches.
You can edit your cron table by running
crontab -e. There are great resources available to help you schedule the task, such as this how-to and a crontab generator, but here are a few examples of lines that I’m currently using for my bots:
Tweet every hour, on the hour:
0 * * * * python /home/molly/twitter-bot/bot.py
Tweet every three hours:
0 */3 * * * python /home/molly/twitter-bot/bot.py
Tweet every fifteen minutes:
*/15 * * * * python /home/molly/twitter-bot/bot.py
Tweet at 12am, 6am, 12pm, and 6pm:
0 0,6,12,18 * * * python /home/molly/twitter-bot/bot.py
I would highly, highly recommend reading Darius Kazemi’s article, “Basic Twitter bot etiquette”. He lists four suggestions for “making a bot that isn’t an asshole”.
I see some of these rules as more bendable than others. For example, @yourevalued does @mention people, but I try to reduce its assholery by ensuring that it never tweets at the same person twice.
That said, I'm running the risk of this bot being banned by Twitter for @mentioning too many non-followers. That fateful day has come. RIP @yourevalued, November 12, 2014–May 4, 2016.