I Made a Twitter Bot Using Tweepy


First of all, what is Twitter? For people who might not know, Twitter is a micro-blogging site where its users can post short text messages sometimes also containing media such as photos, videos, and for the past few weeks, audio too. The information on Twitter moves fast, I mean really fast; which makes it a good source to get/disseminate information faster than other platforms. I am guessing this is why Twitter has its tag line as–

“Twitter. It’s what’s happening.”

Since Twitter has such a wide reach, it can be a good place to grow your presence quickly. One of the ways to grow quickly on Twitter is to maximize interactions and thus to generally be active. Sure, you can do all the heavy-lifting yourself and painstakingly like, retweet, reply, and follow but can you guess who does tedious and monotonous tasks better than you? Machines. Yup, Twitter bots can make your life easier and it doesn’t even take much experience to make one. So let’s do that!

The Twitter API

The Twitter API uses OAuth, a widely used open authorization protocol, to authenticate all the requests. Before making any call to the Twitter API, you need to create and configure your authentication credentials. Twitter also has rate limits imposed on its API to prevent spammers from overloading their servers. If all this sounds complicated right now, don’t worry we will take a look at all of it later in this article.

Technically, with the number of HTTP endpoints Twitter API exposes, the possibilities are truly endless. Although the logo of Twitter sort of inspires us to fly high with the sky being the limit, we are just going to build a basic bot so let’s stay grounded, shall we?

Let’s Get Started

  • Twitter Developer Account
  • Python 3 Installation
  • Tweepy Installation
  • PythonAnywhere Account
  • Basic programming skills

Step 1: Applying for the Twitter Developer Account

The Twitter Developers’ Website after the application gets approved

Step 2: Creating a Twitter App

To create an app, click on “Developer Portal” and navigate to “Projects & Apps” > “Overview”. You’ll see the following page:

The Twitter Developer Portal

Now, click on the “+ Create App” button. Twitter allows you to create a maximum of 10 Twitter apps which are more than enough for almost everyone trying to explore the API. Once you click the button, it will ask you to name the app. Name it something unique and continue to land on a page that'll look something like this–

The API Keys for your app. Don’t forget to note them down!

Here you can see three strings, namely:

  • API Key
  • API Key Secret
  • Bearer Token

Note down these strings and save them somewhere secure. It is crucial that you DO NOT share these with anyone other yourself. A person having your keys can perform actions on your behalf. In case you feel that someone might have gotten hold of your API keys, you can always regenerate them on your “App Settings” page. Note that this will require you to update your project with new keys as well.

On the “App Settings” page, you can see information about your app on the “Settings” tab and the set of keys on the “Keys and Tokens” tab. Scroll to the “App Permission” section and change the permission to “Read and Write”.

In the “Authentication Settings” section, enable “3-legged OAuth”. In the “Callback URLs” and “Website URL” fields type in the link to your website or if you don’t have a website you can simply put the link to your GitHub repository. In my case, I entered my website: mayurbhoi.com (please visit, thanks). Click on “Save” and go to the “Keys and Tokens” tab next.

Here, you’ll be generating the consumer keys for your app which, along with your API keys, will be used to authenticate your app and thus let you access the Twitter API. In the “Authentication Tokens” section, go to “Access Token and Secret” and click on “Generate”. The page will show you your tokens that were generated for you to note down. As is the case with API keys, these tokens are very sensitive and you can always regenerate them if you lose them or happen to accidentally share them with someone else.

Once all this is done, your step of creating a Twitter app is complete! On to the coding part (finally).

Step 3: Installing Python and Tweepy

python3 --version

and it should show you the version of Python installed.

Terminal showing Python v3.8.1 installed

After checking your Python installation, you need to install Tweepy.

“Tweepy is an easy-to-use Python library for accessing the Twitter API”

Installing Tweepy is extremely easy because of the Python Package Manager (also known as pip) and can be done via the Terminal by typing the following command–

pip3 install --user tweepy

Usually, the installation succeeds but if it doesn’t and you encounter any issues or errors, just run the above command again and it should install just fine.

Step 4: Coding the bot

The bot we are creating will reply to tweets that mention it and have a particular hashtag (in this case #pat) with a GIF. If the tweet doesn’t have the ✨special✨ hashtag, it’ll simply like the tweet and not reply with anything. The code is split into three sections so that it is easy to understand as it can be very easy to get lost while following a written coding tutorial.

4.1 — The Setup

Create a new file named bot.py. In the file, start by writing the following statement:

import tweepy

This will import the Tweepy library for you so that you can use it for the project. After doing that, declare your keys by initializing respective variables as follows:

consumer_key = '<REPLACE-WITH-YOUR-OWN>'
consumer_secret = '<REPLACE-WITH-YOUR-OWN>'
access_token = '<REPLACE-WITH-YOUR-OWN>'
access_token_secret = '<REPLACE-WITH-YOUR-OWN>'

consumer_key and consumer_secretare your API keys saved in Step 1 while access_token and access_token_secret are the access tokens generated in the “Keys and Tokens” section of your Twitter app.

Now, add these three lines which enable your program to take your keys and connect them to the Twitter API.

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

At this point your file should be looking like this:

4.2— Remembering the last tweet replied to

At a glance, you might be wondering why this section is even necessary. It turns out that it is actually one of the most important things to do while coding a Twitter bot. Think about it this way, if you are a bot replying to tweets using tweet IDs, how will you know what tweet was the last one you replied to? Clearly, you need to store the ID somewhere and reference it when you are ready to reply to new tweets, right? So, how do we implement that?

A very simple way to do this is to maintain a plain text file that holds the tweet ID of the last tweet the bot replied to. Every time the code is executed and a tweet is replied to, the ID will be overwritten with the ID of the tweet our bot just replied to. To do this we write two functions, namely read_last_seen() and store_last_seen(). The code is explained below for these functions:

For these functions to work, you need to make a file named last.txt in the same directory as your Python file. In your Python file declare a variable for the text file and GIF names as follows:

FILE_NAME = 'last.txt'
GIF = 'pat-pat.gif'

4.3— The reply() Function

The code for the function, the actual good stuff in the program, is as follows:

The points to note here are:

  • api.mentions_timeline() returns an array of tweets that were tweeted after the one that has its ID stored in the text file.
  • We check the array for the hashtag and if found, we call the api.update_with_media() function that takes the media file’s path you want to include in the reply and the ID of the tweet you want the bot to reply followed by updating the latest replied ID by calling store_last_seen().
  • If the hashtag isn’t found, it simply stores the last seen ID and continues to the next tweet.
  • The original tweet is liked in both the cases using api.create_favorite()

We are almost done with the bot! At this point, you can run the file and check if it runs. Call the reply() function at the end of the file. Log in to Twitter with a different account (duh) and Tweet at the bot with & without the hashtag you chose so that you can test both the cases. The bot should like and reply to the tweet containing the hashtag and just like the tweet that doesn’t have the specified hashtag.

But wait, we want our bot to check for the tweets continuously right? Yes. Yes, we do. For this, we can simply wrap reply() with while(True) and call it a day, right? No. Here’s why:

We’ll be hosting our code on a server, so we should try minimizing the resources used (space and CPU processing time) as much as possible, and should be our top priority. In addition to this, we also need to take care of the rate limits of the Twitter API as discussed previously as making too many requests continuously will exhaust your quota pretty quickly. To do this, just add a delay in the execution of the function. Import the Python library time and add the line time.sleep(30). This will pause the program for 30 seconds, which is a pretty reasonable compromise between performance and limiting resource usage.

At the end of this section your bot.py file should be looking like this:

and your files should be structured this way in your root folder (remember disco-octopus?):

|____ bot.py
|____ pat-pat.gif
|____ last.txt

Sweet! The coding part is over. Now we can deploy our bot to a server so it can run all the time.

Step 5: Deploying the bot

Go to pythonanywhere.com and create a free account. You’ll see a screen like this one:

Dashboard of PythonAnywhere.com
  • In the “Files” tab, upload all three files in the root directory.
  • Go to the “Consoles” tab and open a new bash console.
  • Type pip3 install --user tweepy to install Tweepy on your server.
  • Type python3 bot.py to start your bot.

Some points to note here are that our free server allows 100 seconds of CPU computation time and 512MB of space for our files. Remember when I said optimizing code for minimum CPU usage is always a good idea?

And… that’s it! Congratulations, you’ve successfully created and deployed your own Twitter bot!

Wrapping Up

I made this bot because I was bored one day and also so that I could explore the Twitter API. The tools Twitter provides are extremely powerful in terms of what you can do with them, so take a deep dive and keep learning.

My bot, called The Pat Pat Bot, is currently active and goes by the Twitter handle @patPatBot_ so come say hi! Also, consider following me (Mayur Bhoi — @mayurtheboi) on Twitter.

Code to my bot is hosted here: https://github.com/Mayur57/patbot-twitter

❤️ If you liked this article, consider buying me a coffee here:

I like coding and numbers.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store