Yee-ello, there! Let’s take a quick (and possibly dirty) look at how to write your very own Twitter bot in Python.

But… why?

For countless reasons. You could write your own watcher bot for Twitter that crawls stuff you’re interested of, or you could automate some routines like posting to Twitter every time you publish a new YouTube video or write a blog post. Maybe there’s a celebrity you want to bombard by retweeting or starring every single one of their tweets.

Why Python?

It’s just a really, really easy way of doing it. If you don’t fancy Python, you can find just as simple Twitter libraries for almost any language there is. Code snippets aside, the same steps are necessary to acquire the API access.

Okay, let’s do it!

Great! First off, create a new virtual environment for the project. Once you’re done, you need to install python-twitter library. You can do it with pip like this:

pip install python-twitter

Oh, by the way, this library is open-source, licensed under Apache 2.0, so you can do just about anything with it, including selling your ready-made bot.

Okay, now you’re ready to write your bot. So let’s not! Instead, either create a new Twitter account for your bot to manage, or log in to your current one. Be sure to set your phone number on your account, as the account needs to be verified. You’ll receive a PIN code later on in the app creation process.

Next, head over to the Twitter Apps and click “Create a new app”.

Create a new Twitter App

Next, fill out the “Name”, “Description” and “Website” fields. For now, if you don’t have a web site, you can leave a placeholder. You can leave the callback URL field empty. Finally, check the developer agreement and click “Create your Twitter application”. Note that the name must be unique (Sorry, I already took “Manabreak’s awesome bot”).

Fill out the form

Now you should have your app created and see something like this:

Application Settings

And if you scroll down, there should be this part called “Your Access Token”. Go ahead and click the “Create my access token” button to, well, unsurprisingly create your access token.

Access Token

Finally! We are done with the app management thingy! You should see your newly created access token here. The four things you will need from this page are:

  • The consumer key (API Key)

  • The consumer secret (API Secret)

  • The access token

  • The access token secret

Either leave the page open or copy-paste these four things as you will need them to write your bot.

Coding we shall do, mm?

Okay, enough with the awful browser-based setups. Let’s whip out our beloved Python! First off, import the Twitter library:

import twitter

Not so difficult, is it? Next, remember how we just saw the four keys-slash-secrets? Now is the time we need them. Write the following piece of code:

api = twitter.Api(consumer_key = 'CONSUMER KEY HERE',
                  consumer_secret = 'CONSUMER SECRET HERE',
                  access_token_key = 'ACCESS TOKEN HERE',
                  access_token_secret = 'ACCESS TOKEN SECRET HERE')

Err, actually, don’t write literally just that. Instead, replace the portions between the quotes with your actual keys and secrets. Also, what did we just do? We initialized the Twitter library. To make sure you got the keys and secrets right, we can verify the credentials:

if api.VerifyCredentials():
    print('Credentials ok! You may start your shindigs!')

If the credentials were indeed OK, we can go and troll the hell out of Twitter. Now is as good time as any to think about what you want to do with your bot. In the meantime, I’ll show you something neat.

You know the little “Trending” column on Twitter? There’s ten trending hashtags or topics there. If you want to fetch those topics, here’s what you do:

# Get the Top 10 trending things
trends = api.GetTrendsCurrent()

for trend in trends:
    print("Currently trending: %s" % (

Well! That wasn’t so difficult. Actually, the Twitter library we’re using is simple as heck. Let’s see some other examples.

Automatically mark posts as favorite when someone mentions you

Suppose you are overly confident of your virtual presence in the somesphere and you are absolutely certain all mentions about you are always positive. In that case, you could automate the process of starring the posts with this:

# Get the 20 latest mentions of you
mentions = api.GetMentions()
for mention in mentions:

Enjoy your ever-growing list of favorite posts! Now only if someone would mention me…

Re-tweet posts that are not yet retweeted by other users

I have no idea why you would like to do this other than to boost some poor soul’s self-confidence. In any case, let’s say you’d like to go through the latest curling-related posts and re-tweet them if they haven’t re-tweeted yet.

# Search for curling-related posts
search_results = api.GetSearch(term = 'curling', result_type = 'recent', count = 10)
for post in search_results:
    if post.retweet_count < 1:

Really shows the power of the API, huh? In just four lines, we searched for curling- themed tweets and retweeted if they didn’t have any retweets yet. Nice! Now all those lonely curling tweeters can enjoy at least a single retweet! Go Canada!

Follow another poor soul if they don’t have any followers

Continuing with the poor curling player theme, let’s see if any of those bastards are all alone in Twitter. If they are, let’s give them a pity-follow:

# Search for curling-related posts (just like last time)
search_results = api.GetSearch(term = 'curling', result_type = 'recent', count = 10)
for post in search_results:
    if post.user.followers_count < 1:
        api.CreateFriendship(, follow = True)

Neato burrito. One thing that boggles me, though: Twitter uses “follow” and “friendship” pretty much interchangeably, and I have never understood the difference between the two. Well, this piece of code does the trick. No more lonely curling enthusiasts on Twitter, and we are yet another step closer to world peace.

BONUS ROUND: Get your bot’s write permissions revoked by this one neat little trick!

So, you’re already fed up with your bot being all nice to canadians? You’d like it to stop doing things, but are too lazy to just… turn off the bot? Well then, you’re in luck! If you go absolutely bonkers with your bot, I can guarantee it will get its write permissions revoked in no time!

For starters, you can loop through the newest trends forever, retweeting every single tweet you find and, as a bonus, follow the users who tweeted them. Ah, what the hell, let’s star the posts too! You can never have too many favorites!

# Search for curling-related posts
while True:
    trends = api.GetTrendsCurrent()
    for trend in trends:
        search_results = api.GetSearch(term =
        for post in search_results:
            api.CreateFriendship(, follow = True)

There we go! Now the bot will fetch the current trends, search for posts using each of the trend and retweet and favorite all those posts and follow the users. When all the trends are handled, it all starts from the beginning, fetching new trends (if they’ve changed) and doing it all over again.

Oh, one more thing: don’t do this.

Throw in some fault tolerance

When you write a bot, chances are you don’t want to be looking after it all day long in case it catches on fire or goes berserk over neighborhood kids. Instead, I bet you want relax, slowly sip through your cappuccino while browsing /r/funny and be sure that your bot is doing all the things you told it to without crashing.

First off, let’s suppose you’d like the bot to tell you what it’s retweeting. You’d do something like this:

# Get some posts somehow
posts = ...
for post in posts:
    print('Handling post: %s' % (post.text))

This is fine so far, but Python might flip its shit if the tweet is written in, say, mandarin chinese. This would cause the print command to fail. In order to prevent this, let’s use a codec for stdout. To the beginning of your code, add this code:

import twitter
import codecs
import sys

sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, "xmlcharrefreplace")

Great! Now the program shouldn’t crash for character encoding reasons. Another problem may arise if the API doesn’t behave correctly. This may be if you do a wonky API call or if Twitter responds with something unsuspected. To ensure your bot won’t crash, you should surround your API calls with try-except:

    search_results = api.GetSearch(term = '#cobacabana')
except twitter.TwitterError as e:
    # Handle the exception, or just 'pass' if you don't want to

That’s it!


Writing a Twitter bot with Python is a piece of cake, and the available API is absolutely brilliant and fool-proof in its simplicity. Now if we only had something meaninful for a bot to do… Until then, why don’t you fiddle around with your bot?

If you found this post useful, you can support my caffeine-induced journey by buying me a cup of coffee!