Building a Twitter Bot in Python with Tweepy

Twitter is one of the world's largest social media companies. It's an excellent way to drive engagement for both organizations and individuals.

Twitter is somewhat unique in that it relies on periodically posting short snippets of text. Twitter accounts tend to post more frequently, with each post being shorter in nature.

Because of this, Twitter posting is a process that is easily automated. This tutorial will teach you how to biuld a Twitter bot in Python with Tweepy, a Python package that makes it easy to interact with the Twitter API.

Table of Contents

You can skip to a specific section of this Python Twitter bot tutorial using the table of contents below:

What is Tweepy?

In the simplest terms, Tweepy is a library for the Python language for accessing the application programming interface (API) provided by Twitter.

Tweepy allows easy integration of Twitter tools through the official API in your programs.

Tweepy can be used to create bots and tools to automate as well as prompt everything you manually do on Twitter.

Applications built using Tweepy can be used for both fun activities and very illegitimate activities such as spamming and harassing people. Since Twitter (like most social networks) has strict anti-spam policies, expect consequences if you use Tweepy for illigitimate purposes.

You should be thoughtful about what you do with the knowledge you gain today from this tutorial. It should solely be used for research and non-harmful purposes. I am not liable for any legal consequences or damages that might arise from any unlawful practices or applications.

Let's go ahead and install Tweepy using pip, the main package manager for Python.

pip install tweepy

Once it is installed, open up a new Jupyter Notebook (or a vanilla Python script) and see if Tweepy imports without any issues.

import tweepy

If it works fine, you are good to go.

Let's now look at the rest of the requirements you'll need before proceeding through this tutorial.

Requirements

In this Tweepy tutorial, it's not enough to have the Tweepy library installed to get a Twitter bot to run. You'll need access to an active Twitter account with developer mode enabled.

We will directly be working on this real-time without the use of any sandboxes. Because of this, we need the Twitter developer account to create the credentials for us.

More specifically, a Twitter developer account gives you access to four credentials:

  • Consumer API Key
  • Secret API Key
  • Access Token
  • Secret Access Token

A Twitter developer account gives access to the Twitter API. This opens up application layer and transport layer endpoints to perform various tasks such as tweeting, favoriting, retweeting, liking, direct messaging, and even more complex tasks like finding what is trending.

If you were to build a program from the scratch, you would have to go through all the trouble of writing code to deal with the low-level functionality like encoding and decoding your data, configuring requests, configuring authentication, and configuring timeouts.

To make matters worse, this would be table stakes just to use the endpoints Twitter provides. Tweepy does this for is and allows us to focus solely on the bot we are building instead.

Having a Twitter account does not necessarily give access to a developer account and we are required to explicitly apply for a developer account. Even when we apply, sometimes it takes days for our account to be approved. Therefore, the first thing you need to do in this tutorial is get the Twitter developer account set up.

I'll show you how to do that next.

Setting Up Twitter Developer Account

Let's first login to Twitter with your existing account (or if you do not have one, create a new one). Make sure that you verify it with a mobile number as well since this is essential in the next step.

Now, let's visit https://developer.twitter.com/ and apply for a developer account. The process is pretty intuitive. I do not imagine any readers will have trouble with this step.

Twitter developer homepage

You will be prompted with questions such as "why are you using this" and "what are you planning to do with it". It's important to share your genuine intentions. It's fine to say that you are intending to build a bot as a learning exercise and therefore, you need the developer account.

Twitter developer second screen

Twitter developer third screen

Once you have applied for the developer account, it will take one or two days for it to be approved. We urge you to keep reading this whether or not you have the account as it will allow you to get a better grip on everything that we do here.

The Twitter API exposes these endpoints after providing authentication with OAuth, the most popular open protocol for authentication. Once we have our Twitter developer account accepted, we need to configure our authentication details.

Let's navigate to the 'Apps' option from the top menu bar and then click 'Create An App'. Provide the details and then click 'Create'.

Once this is done, go to 'Permissions' and see whether your new app has both reading as well as writing permissions. If it seems like it does not, go ahead, edit it, and get permission for both reading and writing.

Next, navigate to 'Keys and Tokens' and get your credentials. Copy the consumer key, consumer secret, access token, and access token secret. Consumer key is also known as the API key and if your account says that instead, don't worry about it.

You should also keep in mind that certain rate limits have been imposed by the Twitter API. These rate limits dictate how often you are able to use those HTTPS endpoints within your app.

Before we do some coding, let us now use the credentials we stored earlier and see if we can connect to the Twitter endpoints.

Open your favorite Python IDE (even Notepad or Gedit would do) and test the connectivity.

import tweepy
API_KEY = 'Paste your api/consumer key here'
API_SECRET = 'Paste your api/consumer secret here'
ACCESS_TOKEN = 'paste your access token here'
ACCESS_TOKEN_SECRET = 'paste your access token secret here'
auth = tweepy.OAuthHandler(API_KEY, API_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_TOKEN_SECRET)
twitter_api = tweepy.API(auth)
print(twitter_api.verify_credentials())

In the above code, set the API_KEY, API_SECRET, ACCESS_TOKEN, and ACCESS_TOKEN_SECRET to the codes you generated and copied earlier from your Twitter account. If this executes well without any errors and prints true, you are good to go.

Let's now get ourselves familiar with the jargon of Tweepy and Twitter.

Tweepy: Jargon

What Tweepy really does is provide a medium to easily access Twitter API endpoints by encapsulating the low-level functions and adding high-level and relevant functionalities on top.

Tweepy has been evolving alongside Twitter's new updates. However, the vocabulary and the jargon has been carried forward from Tweepy's inception.

For instance, what we now call a Tweet on Twitter used to be called a Status. Tweepy still uses that term even today.

In Tweepy, there are also friendships. This is the equivalent term for followers on Twitter. Moreover, what we call likes on Twitter are called favorites on Tweepy.

There are a few more vocabulary differences but for now, it's enough to understand these main points.

Tweepy: Functionalities

There are five main functionalities Tweepy facilitates. Let's talk about them one by one.

  • OAuth Handling

You already have an idea about what OAuth is - it's the authentification system used by Twitter (and other large applications).

Tweepy has a class named OAuthHandler to deal with the underlying mechanics of the OAuth. We can create OAuthHandler objects and use it for API calls.

For instance, in a previous section, we created an OAuthHandler object called auth with the API key and API secret we generated to see whether our Tweepy installation had been performed correctly.

  • API

Tweepy comes with an API class that facilitates accessing the available HTTPS endpoints in the Twitter API.

In the code we saw earlier, we created a twitter_api object using the OAuthHandler we created and verified the credentials we generated.

Tweepy's API class also contains functions to perform tasks such related to user timelines, followers, tweets, accounts, blocking users, trends, and streaming (to name a few).

We will go over these functions one-by-one when we are actually writing code later in this tutorial.

  • Models

There are model classes in Tweepy to conveniently use the responses from the https endpoints to our benefit.

These responses are inherently encapsulated by the Tweepy model classes so we only have to worry about the functionality of the intended task instead of the low-level functions it contains.

Examples of model classes include user, friendship, status, and searchresults.

  • Cursors

Almost every time, the Twitter API's https endpoints return results by a sequence of assigned numbers of pages. This is where the Tweepy cursor comes in.

The Tweepy cursor makes the process of traversing and fetching items easy. More specifically, there is a cursor class in Tweepy to facilitate this task.

  • Streams

Streams in Tweepy are used for the task of acquiring much larger volumes of data such as tweets. Streams handle session creation, authentication, connection, and the closing. We can also use streaming to watch for tweets in real-time matching specific guidelines or criteria.

Now that we know about both the jargon and the functionalities of Tweepy, we are ready to write our first code using the Tweepy library.

Tweepy: The Twitter Bot

There is no proper and methodical way to learn Tweepy. You just have to build with it.

In this section, I'll demonstrate how to build all of the major functionality from Twitter using the Tweepy library.

  • Say Hi to all your followers

my_followers = twitter_api.followers()
for user in my_followers:
	twitter_api.update_status('Hi @' + user.screen_name)
	time.sleep(5000)

Let's go over this code line by line.

What we're doing here is acquiring the followers of my account using the twitter_api object's followers() method.

We are saving it to a my_followers object and in the next line, we are iterating through it and updating our status (which means we are tweeting) with a five second time interval.

The time.sleep(5000) function is very important. It is required to avoid getting banned due to breaking the Twitter API's rate limits.

Congratulations! You just made your first bot.

  • Get Tweets on Your Timeline

my_timeline = twitter_api.home_timeline(count = 10)
for tweet in my_timeline:
	print(tweet.user.name + 'tweeted' + tweet.text)

What we are doing here is getting the timeline from my account and storing it in a variable named my_timeline.

Once the data has been stored, the script loops through it and prints our 10 most recent tweets.

  • Get User Details

some_user = twitter_api.get_user("elonmusk")
print(some_user.name)
print(some_user.description)
print(some_user.location)

If we know the username, we can use the get_user function from the API class to fetch their details. In the example above, we fetched their name, description, and location using some_user's name, description, and location attributes.

You can also get a list of their followers. Here's how you'd print the name of each of their followers:

for follower in some_user.followers():
	print(follower.name)
  • Update Profile Description

twitter_api.update_profile(description="I am a bot")

Tweepy's API class also provides functions to update your personal details. In this example, we updated our description to I am a bot.

  • Liking Tweets

my_timeline = twitter_api.home_timeline()
tweet = my_timeline[0]
twitter_api.create_favorite(tweet.id)

In this example, we fetch the first tweet of our timeline and then like it.

We first pulled tweets from our timeline using twitter_api.home_timeline(). Then we parsed that Python list using square bracket notation to get the first tweet from our timeline. Finally, we used the create_favorite method to like this tweet.

  • Blocking Users

twitter_api.create_block(twitterusername)

Tweepy can also be used to block other Twitter users. To do this, call the create_block method on our twitter_api object and pass in the username of the account you'd like to block.

  • Get Blocked List

for blocked_user in twitter_api.blocks():
	print(blocked_user.name)

Calling the blocks method on our twitter_api object fetches a list of all the Twitter users that we have blocked. In the code above, we combined this function with a for loop to print the names of all the users our account has blocked.

  • Search for Tweets

for tweet in twitter_api.search(q="Space", lang="en", rpp=5):
	print(tweet.user.name + 'said' + tweet.text)

The Tweepy library can also be used to search for tweets. In the search method outlined above, the q parameter is what we're searching for and the rpp parameter specifies how many tweets we'd like to fetch.

Note that this search method goes beyond the people that our account follows. It also searches the universe of public tweets.

  • Get Name Mentions on Tweets

mentioned_tweets = twitter_api.mentions_timeline()
for tweet in mentioned_tweets:
	print(tweet.user.name + 'said' + tweet.text)

Lastly, the code above fetches all tweets in which our username has been mentioned. The mentioned_timeline method is the key to this.

Final Thoughts

In this tutorial, you learned how to build a Twitter bot in Python with Tweepy. This can be used for a range of things like automated tweeting or advanced Twitter analytics.

We used the Tweepy library to make this bot much easier to build. While you saw a few examples to get ourselves familiar with Tweepy, you've only scratched the surface. More Tweepy functionality can be found on the official documentation. Feel free to play around and keep practicing!


Written on August 11th, 2020