Build and Deploy Twitter Bots with Python, Tweepy and PythonAnywhere

September 26, 2018
Written by
Ajao Iyanu
Contributor
Opinions expressed by Twilio contributors are their own

Twitter and Python logos

This article will guide beginner Python developers on creating Twitter bots. You will learn the Twitter API while building a your bot and then you will deploy the bot to a cloud platform. The Twitter bot tweets quotes randomly selected from a Random Quotes API service.

Development Environment

To build our Twitter bot, we first need to set up our Python development environment and install the required packages that are needed for us to follow along with this tutorial.

In addition to Python 3, we will be using:

  • virtualenv – a development environment
  • Requests library – a http library for humans
  • Tweepy – an API wrapper for Twitter
  • json – a built-in Python library for working with json
  • time module – a built-in Python library for working with time

First of all, it is highly recommended and best practice to create a virtual environment before you begin any Python project. We will create a virtual environment using a tool known as virtualenv. Virtualenv isolates your Python setup on a per-project basis. This means that changes made to one Python project won’t affect another Python project.

On Windows, Linux, or macOS:

mkdir twitter_bot                
cd twitter_bot

The next step is to make our virtual environment. This will be called environment. Make sure the name you choose for your virtualenv is in lower case with no special characters and spaces.

python3 -m venv environment        

Enter the twitter_bot directory:

cd twitter_bot

Activate the virtual environment:

environment\Scripts\activate

For Linux and macOS:

Enter the twitter_bot directory:

cd twitter_bot

Activate the virtual environment:

source environment/bin/activate

You will know that you have virtualenv started when you see that the prompt in your console is prefixed with (environment).

Next we’ll be installing dependencies. Create a requirements.txt file. This file contains a list of items to be installed using the Pip install command.

For our use case, we need to create a new file using the text editor of our choice in the twitter_bot directory, and save the file as requirements.txt. In our requirements.txt file, type the following:

tweepy
requests

On the command line use the following comand to install the dependencies:

pip install -r requirements.txt

On the command line, you will see the files installing one after the other. When the items listed in our requirements file are done installing, we can move on to the next phase of building our Twitter bot. This will install the updated versions of the following libraries: Tweepy and requests.

Creating our Twitter Bot

The code for our Twitter bot will be broken apart into two small functions, each with one task that it performs well. It is best practice to have functions that perform a single task. Our Twitter bot does two things that will be split into two functions. The first function connects to the API endpoint of a random quote generator to get the quotes.

To start with, let’s create a new file and call it twitter_bot.py. After that, we’ll import two libraries that will help with the writing of this function.

import requests    # an http library written for humans

The requests library makes it easy to use http in our Python programs. It is simpler than urllib, Python’s built-in http library.

Before moving on with our code, we need to create a RapidAPI account, in order to get our api_key and api_url.

Navigate to the Andrux API page and click connect GET Endpoint so we can use this service to grab random quotes.

According to RapidAPI’s documentation, we need to create a dictionary called headers. This contains our api_key and api_url.

To create a variable that will hold the api_key and api_url:

api_key = your unique api key in the X-Mashape-Key field (see diagram)
api_url = https:// the url in the X-Mashape-Host field (see diagram)

headers = {'X-Mashape-Key' : api_key, 'X-Mashape-Host' : api_url}

At this juncture, we will make use of the requests library to access the API endpoint.

# The get method is called when we 
# want to GET json data from an API endpoint
quotes = requests.get(api_url, headers=headers)
print(quotes.json())

You can run the file which contains your code from the terminal:

python twitter_bot.py

This is what a response in json looks like:

{quote:"As God is my witness

Now, let’s create our first function and call it get_quote(). This function will look like this:

def get_quote():
    headers = {'X-Mashape-Key': api_key, 'X-Mashape-Host': api_url}
    response = requests.get(api_url, headers=headers)
    json = response.json()[0]
    tweet = json['quote']+ '-' + json['author']
    return tweet

The response from our requests.get method should be passed to a variable that will be called response:

response = requests.get(api_url, headers=headers)

This json response has to be decoded:

response.json()

The response for this method will then be passed to a variable that will be called json.

One of the characteristics of the Rest API is that it returns a large amount of data, including data that is not needed, but its advantage lies in the fact that it queries our endpoint just once. Since our data is now formatted as a Python dictionary, we can use the method for accessing the values of dictionary keys.

tweet = json[‘quotes’] + json[‘author’]

return tweet
def get_quotes():
    headers = {'X-Mashape-Key': api_key, 'X-Mashape-Host': api_url}
    response = requests.get(api_url, headers=headers)
    json = response.json()[0]
    tweet = json['quote']+ ' -' + json['author']
    return tweet

At this juncture, we just completed half of the code for our Twitter bot. Now we will write the second function that POSTs the quotes to Twitter.

Next, we need to register for a Twitter API key.

Visit apps.twitter.com and sign in. Then click on the Create New App button.

Fill out the Create New App form as required.

You can put a placeholder in the Website field. The Callback URL field is not required, so leave it empty.

Click the link to 'Manage Keys and Access Tokens'. Then click on either Regenerate Consumer Key and Secret or Regenerate My Access Token and Token Secret for any information that is not yet available on the page.

In the code, create the following variables:

consumer_key = YOUR CONSUMER KEY
consumer_secret = YOUR CONSUMER SECRET
access_token = YOUR ACCESS TOKEN
access_token_secret = YOUR ACCESS TOKEN SECRET

Please note: it's okay to hardcode your credentials when getting started, but you should use environment variables to keep them secret before deploying to production. Check out how to set environment variables for more information.

The next step is to import Tweepy that was installed earlier:

import tweepy


# Twitter requires oAuth2 to access its API:
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

To POST a tweet on Twitter, we’ll make use of the update_status method of Tweepy. Tweepy is a popular Twitter API wrapper. It provides methods for accessing the different Twitter API endpoints. This library makes life easy for developers writing code to use Twitter’s API.

api.update_status('Hello world') # This will update our timeline with "Hello world"

For our use case, the update_status argument will be the value returned in our get_quote function. Hence, we type the following:

tweet = get_quote()
api.update_status(tweet) 
print(‘Done’)    # This prints ‘Done’ whenever the update is successful

The above lines of code will be put in a function called tweet_quote. This function receives tweet as an argument.

def tweet_quote():
     tweet = get_quote()
     status = api.update_status(tweet)
     print(status.id)

Finally, call the tweet_quote function when you run the file by adding this at the bottom:

tweet_quote()

Testing and Deploying the Twitter Bot

To test that our bot is working properly, we can run the script from the command line. We should make sure that our computer is connected to the internet. The bot is working when we see Done showing on the command line.

cd twitter_bot

Then activate the virtual environment. You should see the prompt that was explained earlier in this article.

python twitter_bot.py  

twitter_bot.py is the name of our Python script. The above command will run in the script and display the Tweet status ID on our terminal screen.

To deploy our Twitter bot, first we are going to create a free account with PythonAnywhere, a service that makes it easy to deploy Python applications to the cloud. On the login page, type in your email address and password and click on "Log in".

After you log in to your PythonAnywhere account, you will be presented with the Dashboard page.

Click on files.

The next page will present something that looks like the above page. You can then click on Upload a file, locate your newly created Twitter bot script, and upload.

To create a scheduler for when our script will run, click on Tasks and then create a task.

Set the time the script should run and add the path to your uploaded file. It will probably be in /home/<your username>/twitter_bot.py

What’s Next

Voilà! We now have a functioning Twitter bot. We can improve our Twitter bot by making it tweet more than once at a time. We can also develop another bot that uses a News API on RapidAPI. I encourage you to play around with RapidAPI and the Tweepy library to find out more interesting things that we can do.

You can reach me on Twitter @IyanuAshiri or check out my GitHub profile @IyanuAshiri