Making a Twitter Bot Using Tweepy

It's easier than you think

April 18, 2021 (3y ago) • 13 minute read
⚠️

Note: Due to changes of March 30, 2023 to the Twitter API pricing, making Twitter apps and obtaining API keys is now behind a paid subscription. Hence, to follow this tutorial you’d need to spend a minimum of USD 100. I strongly condemn these changes as it hinders beginners and developers from wanting to experiment and build with the Twitter API. This article will be left up for reference also serving as a symbol of disagreement.

Introduction

As the title says, this article is about making a simple Twitter bot that likes, retweets, and even replies to other tweets using Twitter APIs and Tweepy. We'll also see how to deploy the bot to a server so that it can run continuously without any monitoring required. Sounds cool right? Let's see how you can do it too.

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 is a set of tools and endpoints that give you access to the functionalities of Twitter and the ability to (in some sense) play with the data. A developer can use the API to execute most of the actions you can normally take on Twitter, programmatically. You can like, retweet, and delete a tweet. You can also reply to tweets that include a specific hashtag, have a specific phrase, or even those that mention your Twitter handle.

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?

Getting Started

To make a Twitter bot there are a few requirements--

  • Twitter Developer Account
  • Python 3 Installation
  • Tweepy Installation
  • PythonAnywhere Account
  • Basic understanding of programming

Step 1: Applying for the Twitter Developer Account

To access the tools and the API by Twitter you obviously need a Twitter account but having just that isn't enough. You will need to apply for being a Twitter Developer by filling out an application here and clicking on "Apply". It's fairly simple to apply and generally takes at maximum about a day or two for the application to get approved. In my case though, the application was approved instantly. Once your account is approved, you can access the developer documentation and tools.

Step 2: Creating a Twitter App

Twitter doesn't allow developers to access their API and database using traditional password/key authentication for all projects. Instead, for every use-case/project, the developer needs to create a new Twitter app. Every app has its own set of authentication keys and that's how your bot (or any other type of implementation) will get itself authenticated so that it can communicate with the API.

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

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--

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. 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

Get the latest Python v3 SDK from their official website and install it on your machine. To check if your installation is correct run the following command--

python3 --version

and it should show you the version of Python 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: Code for the bot

Since everything we need to start coding is already installed and set up, we can now open a code editor of our choice (I personally am a very big fan of VS Code but let's not get into that debate). Create a folder and name it something fancy. (disco-octopus?)

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>'
consumer_secret = '<REPLACE-WITH-YOUR-OWN>'
access_token = '<REPLACE-WITH-YOUR-OWN>'
access_token_secret = '<REPLACE-WITH-YOUR-OWN>'

consumer_key and consumer_secret are 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 = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

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:

# This function will open the text file and return the ID of
# This function will open the text file and return the ID of
# the latest tweet the bot has successfully replied to
def read_last_seen(FILE_NAME):
    file_read = open(FILE_NAME, 'r') #open the file in read mode
    last_seen_id = int(file_read.read().strip()) #read the Tweet ID as an integer
    file_read.close() #close file reader
    return last_seen_id #return the result

# Overwrite the previous Tweet ID with latest
def store_last_seen(FILE_NAME, last_seen_id):
    file_write = open(FILE_NAME, 'w') #open the file in write mode
    file_write.write(str(last_seen_id)) #write the ID as a string
    file_write.close() #close file writer
    return #return void

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:

def reply():
    # The API will only send a response containing tweets with IDs that come after the ID
    # stored in the text file
    tweets = api.mentions_timeline(read_last_seen(FILE_NAME), tweet_mode='extended')
    for tweet in reversed(tweets):
        if '#pat' in tweet.full_text.lower():
            print("Patted!: " + str(tweet.id) + " - " + tweet.full_text.lower())
            api.update_with_media(GIF, "@"+ tweet.user.screen_name + " pat pat" + "\nPS: " + random_appreciation(), in_reply_to_status_id=tweet.id)

        elif '#pat' not in tweet.full_text.lower():
            print("Liked!: " + str(tweet.id) + " - " + tweet.full_text.lower())

        store_last_seen(FILE_NAME, tweet.id)
        api.create_favorite(tweet.id) # Like the tweet with mentions

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 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.

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

In order to deploy your bot, you need to host and execute it on a live server. You have tons of options here like creating a Docker container and deploying it on an AWS EC2 server or using Heroku but for the sake of simplicity, we'll use a website that is built solely to host Python scripts.

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

  • 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?

That's it! Congratulations, you've successfully created and deployed your own Twitter bot!

Wrapping Up

Note that this was just the tip of the iceberg and there's a heck of a lot more to explore in Twitter API than we have managed to cover today in this article. I suggest you read through the official documentation of Twitter API and Tweepy to come up with more complex and innovative ideas for a Twitter bot because as I said possibilities are endless with the number of tools Twitter provides us.

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.

Code to my bot is hosted here.

Mayur Bhoi @ mayurbhoi.com