19
π How to make a Twitter Bot in Python using Tweepy
π£ A reply-to-mention Twitter bot that can reply to every tweet where it got mentioned with a specific keyword with an auto-generated image.
TL;DR: This blog post is aimed to demonstrate how to make a custom Twitter bot in Python using the official Twitter API. The bot will reply to every tweet in which it got mentioned with a specific keyword. The reply will be in the form of an image with a quote written on it.
Source code of this application is available in this GitHub repository
In this article, you'll learn how to make your own Twitter bot in Python using Tweepy, a Python library for accessing the official Twitter API.
You will be creating a Reply to mentions bot, which will send a reply to everyone's tweet who has mentioned it with a specific keyword.
The reply will be in the form of an image that you will generate and put some text over it. This text will be a quote that you will fetch from a third-party API.
Here's how it will look like:
To follow along with this tutorial, make sure you have:
You are going to deploy the final application to AWS Elastic Beanstalk so make sure you are signed up on AWS.
To enable your bot to interact with Twitter, you first have to sign up to a Twitter developer account and create an application for which Twitter will grant you access (There is a detailed explanation of this step in the next section).
At the time of writing this article, the latest version is Python 3.9, but it is always recommended to choose a version that is one point revision behind the latest one so that you do not face any compatibility issues with third-party modules.
For this tutorial, you can go with Python 3.8.
- Tweepy β To interact with Twitter API
- Pillow β To create an image and to add texts over it
- Requests β To make HTTP requests to the random quote generator API
- APScheduler β To schedule your job periodically
- Flask β To create a web app for deploying your application on Elastic Beanstalk
Rest all other libraries that you'll see in this project are part of Python's standard library, so you do not need to install them.
Any request that is accessing the official Twitter API requires OAuth for authenticating. That's why you need to create those required credentials to be able to use the API. These credentials include:
- A consumer key
- A consumer secret
- An access token
- An access secret
You need to follow the steps below to create your credentials once you have signed up to Twitter:
Go to the Twitter developer platform to apply for a developer account.
Twitter will ask for some information about how you're planning to use the developer account. So, you have to specify the use case for your application.
Try to be as specific as possible about your intended use for faster and better chances of getting approval.
Once you submit your application, you'll land on this screen :
You'll receive the confirmation back within a week. Once your Twitter developer account access gets approved, create a project on the Twitter developer portal dashboard.
You have to do this process because Twitter permits authentication credentials only for apps. An app can be defined as any tool that uses the Twitter API. You need to provide the following information about your project:
- Project name: a name to identify your project (such as Reply-To-Mention-Bot)
- Category: Select the category to which your project belongs. In this case, choose "Making a bot."
- Description: The purpose of your project or how users will use your app (such as this app is used to automatically respond to tweets)
- Name of app: Finally, enter the name of your app
To create your authentication credentials, firstly, go to your Twitter apps section. Here you'll find the "Keys and Tokens" tab; clicking this will take you to another page where you can generate the credentials.
After generating the credentials, save them to your local machine to later use in your code. Inside your project folder, create a new file called credentials.py
and store these four keys in the key-value format as shown below:
access_token="XXXXXXX"
access_token_secret="XXXXXXXX"
API_key="XXXXXXX"
API_secret_key="XXXXXXXX"
You can even test the credentials to check if everything is working as expected using the following code snippet:
import tweepy
# Authenticate to Twitter
auth = tweepy.OAuthHandler("CONSUMER_KEY", "CONSUMER_SECRET")
auth.set_access_token("ACCESS_TOKEN", "ACCESS_SECRET")
api = tweepy.API(auth)
try:
api.verify_credentials()
print("Authentication Successful")
except:
print("Authentication Error")
If everything is correct, you should be able to see a response saying "Authentication Successful".
Tweepy is an open-sourced, easy-to-use Python library for accessing the Twitter API. It gives you an interface to access the API from your Python application.
To install the latest version of Tweepy, type the following command in your console:
pip install tweepy
Alternatively, you can also install it from the GitHub repository.
pip install git+https://github.com/tweepy/tweepy.git
Let's now understand some of its basic functionalities:
Tweepy provides an OAuthHandler
class that takes care of the OAuth required by Twitter to authenticate API calls.
The code you just saw above depicts the OAuth functionality by Tweepy.
Tweepy also provides an API class for accessing the Twitter RESTful API methods, which you can use to access various Twitter functionalities.
You can find those methods here and the most commonly used are listed below:
- Methods for tweets
- Methods for users
- Methods for user timelines
- Methods for trends
- Methods for likes
When you call any of the API methods that you just saw above, you'll get a Tweepy model class instance in response.
This will contain the response returned from Twitter. For example:
user = api.get_user('apoorv__tyagi')
This returns a User model which contains the data which you can further use in your application. For example:
print(user.screen_name) #User Name
print(user.followers_count) #User Follower Count
19