Codementor Events

Let’s build a Python Twitter bot (Part 1)

Published Feb 21, 2018Last updated Aug 20, 2018
Let’s build a Python Twitter bot (Part 1)

If you are a heavy Twitter user, you might have noticed that to become popular you need to be constantly active on the website for long hours.

Not everyone has the time to do so on a daily basis. So what is the solution? What if I tell you that it is possible to be active on your favorite website even when you are not even near your computer or your phone and you can write the code for it yourselves?

Here is where Twitter API comes to our rescue. This is part one of a three part blog.

Here I will try to explain what we are trying to achieve and how to set up the development environment. The second part will deal with increasing the features of the bot (making it smarter).

If you have some experience in development, then you will probably enjoy parts two and three more.

The third part will be deploying it and linking it to a database. We can make a dataset out of this and run some analyses. The possibilities are endless.

But, let’s start from the beginning. I hope all of my readers are familiar with basic Python 3. Even if you are not, don’t worry. I will explain my code and help you understand it as we proceed.

First things first. Make sure you have Python 3 installed. If it is not installed, download it from here. If you are a Linux/Unix user, you don’t need to do so. Windows users also need to set path to Python directory in environment variables.

So let us set up our development environment. Open terminal and install virtualenv for Python by writing:

pip3 install virtualenv

After installation, move to the directory where you want to set up the bot. You should use cd to move to that directory from terminal. Now in terminal, write:

virtualenv venv

This code will create a virtual environment for our bot, named venv. Let’s activate this virtual environment. If you are a Linux/Unix user, write:

source venv/bin/activate

In Windows, you’ll need to write:

venv/bin/activate.bat

Now you should see (venv) written at the leftmost position. This means we are in the virtual environment. Creating virtual environments is advised by all developers as it allows you to install different versions of the same package when the need arises.

In this virtual environment, you’ll observe nothing is installed. For this part we are just going to need Tweepy. You can install Tweepy by typing the following code in terminal:-

pip3 install tweepy

After you are done with that, let’s do the easy parts first and create a Twitter app. Go to https://apps.twitter.com and sign up with your Twitter account.

Once you are done with that, just create a new app. Fill in the details and copy-paste your consumer key, consumer secret, access token, access token secret in a file and call it credentials.py.

#Paste inside the quotation marks
consumer_key=''
consumer_secret=''
access_token=''
access_token_secret=''

After you are done with that, save and close this file. We won’t be opening that from text editor anymore. Make sure you don’t reveal these codes to anyone because they can use them to impersonate you. Therefore, we will use these values in our main code from credentials.py.

Now we will write a simple code to search Twitter for a keyword and retweet that tweet. This will be based on the REST API of the Twitter API.

Wondering what’s REST API? Well, REST stands for REpresentational State Transfer. It is an approach to communications in Web Services. And API is Application Program Interface. What you need to understand is that we do not need to install libraries or software to take advantage of a REST API design.

You might ask why did we install Tweepy then? The answer to that question is very simple. Tweepy is framework which has a lot of built-in functions that take advantage of Twitter API very efficiently.

We would have written the code for those functions anyway. But since they already have done it for us, why waste time and effort on that. Also Tweepy has a very respectable arsenal of features.

Now the main code of our bot:-

import os
import tweepy
from credentials import *
from time import sleep

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)

for tweet in tweepy.Cursor(api.search, 'blockchains').items(50):
    try:
        tweet.retweet()
        sleep(5)
    except Exception as e:
        print('Could not retweet because',e)
    sleep(5)
    try:
        tweet.favorite()
    except Exception as e:
        print('Could not favorite because',e)
    sleep(5)
    try:
        api.create_friendship(tweet.author.screen_name)
        print(tweet.author.screen_name)
    except Exception as e:
        print('Could not favorite because',e)

This is the code for a basic Twitter bot that gets tweets by searching for a user provided keyword. In the above code, we have used a cursor of Tweepy which is very handy, as it paginates the searches.

Lines 6 and 7 are for authenticating our bot, basically telling Twitter that it is the code for the app that we created before. Line 8 is the initialization of the API, which is what we will use from now on.

wait on rate limit simply means that the code will not crash even when it has reached the rate limit for that time duration, which is quite handy.

Line 10 for loop is a cursor which searches for word “blockchains” in tweets. 50 represents the number of tweets to be collected. So this loop will run 50 times.

Now the three functions. Retweet, like and follow, are at 12,18 and 23 lines. They are inside a try-except block to catch errors, if any. We don’t want to stop our bot due to an error do we?

You might have wondered why are we using sleep(). It is because we are deliberately trying to slow down our code so that we don’t cross the rate limit of the Twitter API.

If we do cross the rate limit, our code won’t be able to do anything until the rate limit resets, usually 15 minutes. And if you cross the rate limit multiple times, your app might get banned and your tokens will get revoked. So tread carefully. Read this to learn more about rates.

As I mentioned beforehand, it is incomplete. We have tons of features that we need to add to it before deployment. I tried to keep it as simple as possible, and this bot is nothing compared to what our final bot will be.

In the next part, I will write more code and we will run the bot on a server so it truly becomes an automated task.

I will try to finish this series as soon as possible. Please be patient. If you liked this post, press the like button. If you did not love it, tell me about it in the comments section. If you have any doubts or issues, ask in the comments section. I will try to help you all out.

Hope to see all of you in part two😄

Happy coding!

Discover and read more posts from Vedarth Sharma
get started
post commentsBe the first to share your opinion
Saurabh Chaturvedi
6 years ago

Good jump start for developing bots with Python in general! Great post!

Vedarth Sharma
6 years ago

I am really glad that you enjoyed it :) stay tuned in for part 2.

Show more replies