DEV Community

Robertino
Robertino

Posted on

🐍 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

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

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 so make sure you are signed up on AWS.

Twitter API authentication credentials

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

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.

Installed these external Python libraries on your local environment

  1. Tweepy — To interact with Twitter API
  2. Pillow — To create an image and to add texts over it
  3. Requests — To make HTTP requests to the random quote generator API
  4. APScheduler — To schedule your job periodically
  5. 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.

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

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

Portal

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

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

Category

  • 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

  • Name of app: Finally, enter the name of your app

App Name

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

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"
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

If everything is correct, you should be able to see a response saying "Authentication Successful".

Understanding Tweepy

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
Enter fullscreen mode Exit fullscreen mode

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

pip install git+https://github.com/tweepy/tweepy.git
Enter fullscreen mode Exit fullscreen mode

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

user = api.get_user('apoorv__tyagi')
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Read more...

Top comments (0)