🐍 How to make a Twitter Bot in Python using Tweepy
Tags: python, twitter, api
Published: 2021-07-23 12:27:53

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

### <br>

**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](https://github.com/ApoorvTyagi/Pytweet)


## Introduction

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:

![Example_Tweet](https://images.ctfassets.net/23aumh6u8s0i/1H8pndxhyHEAv9R8sJJBHZ/ee383447a77972633902ea912a4c1b2b/01_example_tweet.png)

## Prerequisites

To follow along with this tutorial, make sure you have:

### An AWS account
You are going to deploy the final application to [AWS Elastic Beanstalk](https://aws.amazon.com/elasticbeanstalk/) so make sure you are [signed up](https://aws.amazon.com/free/) on AWS.

### Twitter API authentication credentials
To enable your bot to interact with Twitter, you first have to [sign up](https://developer.twitter.com/en) 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).

### Python 3
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](https://www.python.org/downloads/).

### Installed these external Python libraries on your local environment

1. [Tweepy](https://pypi.org/project/tweepy/) &mdash; To interact with Twitter API
2. [Pillow](https://pypi.org/project/Pillow/) &mdash; To create an image and to add texts over it
3. [Requests](https://pypi.org/project/requests/) &mdash; To make HTTP requests to the random quote generator API
4. [APScheduler](https://pypi.org/project/APScheduler/) &mdash; To schedule your job periodically
5. [Flask](https://pypi.org/project/Flask/) &mdash; 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.

## Twitter API Authentication Credentials

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:

1. A consumer key
2. A consumer secret
3. An access token
4. An access secret

You need to follow the steps below to create your credentials once you have signed up to Twitter:

### Step 1: Apply for a Twitter Developer Account

Go to the [Twitter developer platform](https://developer.twitter.com/) 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 :

![Application_Recieved.jpg](https://images.ctfassets.net/23aumh6u8s0i/6AFx7FwF96gj3qh0GayzxA/1fa1b1d3f76faaae8e3b5e34fda48c54/02_application_recieved.jpg)

### Step 2: Create an Application

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](https://developer.twitter.com/en/portal/dashboard) dashboard.

![Portal](https://images.ctfassets.net/23aumh6u8s0i/3LV4PNWOa8ebJ5vv3MXV0x/f71d438b9f9dd3bb3aa9c40988c4b0b7/03_app_Portal.png)

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)

![Name of the project](https://images.ctfassets.net/23aumh6u8s0i/7liNwiFetOdzKL7EqgbozZ/4c9b22c3848621ebd2bc886a41cda478/04_project_name.png)

- **Category**: Select the category to which your project belongs. In this case, choose "Making a bot."

![Category](https://images.ctfassets.net/23aumh6u8s0i/1oYQpGFpbZ5xZTszneXuun/203eb3f1e2090fdaeece59791d496793/05_app_category.png)

- **Description**: The purpose of your project or how users will use your app (such as this app is used to automatically respond to tweets)

![Description](https://images.ctfassets.net/23aumh6u8s0i/m1oBaTFnLWIw3edFgNyB6/6723cb083f4ce6bd03845809bd6d93df/06_app_description.png)

- **Name of app**: Finally, enter the name of your app 

![App Name](https://images.ctfassets.net/23aumh6u8s0i/XMXJZ1KOV3k8Z0kR24HaZ/a5ebd280c7edd68c79685d6c1033bacc/07_app_name.png)

### Step 3: Create the Authentication Credentials

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.

![KEYS.png](https://images.ctfassets.net/23aumh6u8s0i/G05lyhIz0SArEDnE4vVIs/656a2c9b6f57fbad9717718e57aa5d45/08_app_keys.png)

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:

```python
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".

## Understanding Tweepy

> [Tweepy](https://www.tweepy.org/) 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:

```bash
pip install tweepy
```

Alternatively, you can also install it from the GitHub repository.

```bash
pip install git+https://github.com/tweepy/tweepy.git
```

Let's now understand some of its basic functionalities:

### OAuth

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.

### Twitter API wrapper

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](https://docs.tweepy.org/en/stable/api.html) and the most commonly used are listed below:

- Methods for tweets
- Methods for users
- Methods for user timelines
- Methods for trends
- Methods for likes

### Models
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:

```python
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:
```python
print(user.screen_name) #User Name
print(user.followers_count) #User Follower Count
```



[Read more...](https://auth0.com/blog/how-to-make-a-twitter-bot-in-python-using-tweepy/?utm_source=content_synd&utm_medium=sc&utm_campaign=python)