Home

 › 

Articles

 › 

How to Make a Twitter Bot: A Step-By-Step Guide to Building a Twitter Bot in Python

tag someone on twitter

How to Make a Twitter Bot: A Step-By-Step Guide to Building a Twitter Bot in Python

You may have seen a tweet preceded by a little “automated” tag. This tag indicates that a robot made the tweet on behalf of a user who has determined what kind of posts this bot should make and when. While the idea of having a personal robot making tweets for you sounds like a tall order, it’s actually surprisingly easy! So, here’s how you can get your own Twitter bot up and running.

Prerequisites

First, you’ll need to complete a few prerequisite tasks that will set you up with Twitter’s API. For starters, you’ll need a developer account. These are easy to get; Twitter just hands them out for free. Follow this link to start your Twitter developer journey. (No, really. I got a Twitter developer account just for this article.)

Next, you’ll need to create a project within the developer portal. To do this, you’ll need to enter some information regarding your project. For example, you’ll need to provide the handle of the account you want to enroll in the project and the associated email address. You’ll also need to identify the country you’ll be operating your project from, your specific use case, and whether you’ll work with government entities. Finally, you’ll need to verify your email address once you complete the form below.

You’ll also need to create an app with the credentials you need to use the Twitter API V2.0. This is simply achieved; you’ll be greeted with a screen that asks you to name your app to get an API key as soon as you complete the email verification.

You will also need to download the Python dependencies, which you can find here. If you don’t, you won’t even be able to get started since you won’t be able to download the packages you need to make a Twitter bot.

Step 1: Tweet on Behalf of Your Bot

While it might sound oxymoronic to tweet on behalf of your bot, you need to try out your bot’s functionality before you can start building it. For example, you wouldn’t want to get halfway through your Python script only to find out that there’s a critical error in your API key and you need assistance from Twitter support.

Twitter has created a website that you can use to manually tweet on behalf of your bot using bot API functionality. This website will tweet a dog fact to the Twitter account you have logged in to if the account is attached to a functioning bot API key. The rest of this article will teach you how to essentially create your own version of this website that runs on your database and tweets automatically rather than you initiating a tweet manually.

Step 2: Handling Oauth 2.0 Tokens with a Database

The first thing you need to do is handle your app’s tokens. OAuth 2.0 tokens are only valid for two hours after their generation. Since bots are typically programmed to post one or more times a day on their own, without input from the creator, they need to be able to handle generating, storing, and refreshing keys on their own.

Since you’ll need somewhere to store the generated tokens, you’ll need to set up a database that your app can draw from to see if it has usable tokens and for more tokens to be stored as they’re generated. This is especially important if your bot is designed to tweet more than once every two hours.

If your bot is only tweeting once every two hours, the tokens will have already expired by the time your bot goes to tweet again. You’ll still need a place to store the tokens while your bot handles them and to store your refresh tokens, so you can’t get out of developing a database for your tokens by having your bot tweet less often.

You can use Render to create your database, which makes a Redis database compatible with Twitter. You can view their pricing and programs here. You’ll also need to create a program to connect to Redis from outside Render’s programs.

You can view all the information you need to configure and interface with your Redis instance in Render’s documentation.

Once you’ve created your database, you’ll need to use your external key to set the environment variable in your terminal to your Redis. You can do so by entering the following string into your terminal.

export
REDIS_URL=’external_connection_string’

You’ll want to replace ‘external_connection_string’ with the external variable that looks like this: rediss://username:password@host:port (i.e. rediss://example:password@example-2364872:4040).

Step 3: Install Prerequisite Packages

You’ll need to install some packages allowing you to interface with the Twitter API from outside of Twitter’s websites. Once you’ve set up your Redis environment with your terminal, you’ll want to enter the following into your terminal:

pip install requests redis requests_oauthlib flask

Step 4: Creating Your main.py File

We’ll be using Python as our coding language to create this robot. However, Python is not the only language you can use to make Twitter bots. Still, if you know another programming language, you wouldn’t be here… would you?

Now that you have your prerequisite packages, you’ll need to create a main.py file for your bot. You can do this by entering the following strings into your terminal:

mkdir bot-name-variable
cd bot-name-variable
touch main.py

Just replace “bot-name-variable” with something that describes your Twitter bot, like “dog-fact-twitter-bot” or “pandas-hourly-twitter.” The world is your oyster regarding names, but make sure you can remember them later.

Step 5: Editing Your Twitter Bot

Next, you’ll need to edit the main.py file in your code studio of choice. It’s up to you what code studio you use. Ensure you have all your Python databases downloaded and ready to use, as they’ll be necessary for your Twitter bot, even if you copy and paste our code into the studio.

First, you’ll need to import all the packages necessary for your Twitter bot to run. You can do so with the following code block.

import base64
import hashlib
import os
import re
import json
import requests
import redis
from requests.auth import AuthBase, HTTPBasicAuth
from requests_oauthlib import OAuth2Session, TokenUpdated
from flask import Flask, request, redirect, session, url_for, render_template

Since you’ll be using a Redis database, you’ll need to save it to its own variable, which Twitter politely recommends you name “r.” Setting the variable can be done with the following code block.

r = redis.from_url(os.environ["REDIS_URL"])

Now, you’ll need a variable that your code can use to initialize your Twitter App. Use the following code block to do that.

app = Flask(__name__)
app.secret_key = os.urandom(50)

You’ll need to authorize OAuth 2.0 to authorize tweets on behalf of another user. You can do that by following the steps outlined in the Developer Portal under “User Authentication Settings.”

The bot will need a Redirect URI, also called a Callback URL. To test the bot locally, enter the following:

http://127.0.0.1:5000/oauth/callback

Otherwise, you can set this to the website you’ll use to post tweets on your behalf. The site will display OAuth 2.0 Client ID and Secret ID under your keys and tokens menu. Open your terminal to create an environment for these by entering the following into your terminal:

export CLIENT_ID=’CLIENT_ID’
export CLIENT_SECRET=’CLIENT_SECRET_ID’
export REDIRECT_URI=’http://127.0.0.1:5000/oauth/callback’

You’ll need to enter it with the variables changed to your client and secret IDs.

Now, head back to your Python file and create variables for those environments. This will allow your bot to easily retrieve the environments you’ve created to run your program. You can use the following code to do so.

client_id = os.environ.get("CLIENT_ID")
client_secret = os.environ.get("CLIENT_SECRET_ID")
auth_url = "https://twitter.com/i/oauth2/authorize"
token_url = "https://api.twitter.com/2/oauth2/token"
redirect_uri = os.environ.get("REDIRECT_URI")

Remember to change all the environment information to the IDs and Redirect URI for your bot.

The next step is defining your scopes. Scopes determine when and where variables can be accessed. You can set your scopes using the following code:

scopes = [“tweet.read”, “users.read”, “tweet.write”, “offline.access”]

tweet.read allows the bot to read tweets, users.read enable the bot to obtain information about users, tweet.write allows the bot to write tweets, and offline.access allows the bot to stay connected to Twitter for more than two hours.

Twitter’s OAuth 2.0 is PCKE-compliant. So, you’ll need to set a code verifier to use it. You can do so with the following code:

code_verifier = base64.urlsafe_b64encode(os.urandom(30)).decode("utf-8")
code_verifier = re.sub("[^a-zA-Z0-9]+", "", code_verifier)

You’ll also need to pass a code challenge to verify with OAuth 2.0. You can do so with the following code:

code_challenge = hashlib.sha256(code_verifier.encode("utf-8")).digest()
code_challenge = base64.urlsafe_b64encode(code_challenge).decode("utf-8")
code_challenge = code_challenge.replace("=", "")

To make the bot manage and create Tweets, you’ll need to get the dang thing to create tokens. You can do that with this code:

def make_token():
return OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scopes)

This is where the code gets a little dicey for new people. You’ll need to figure out what your bot will post and where it will get that information from.

If you intend to draw your information from an existing API, you can create a variable that draws from the API and creates a .json file that it can post from. For instance, Twitter has a dog-fact API that it uses as its example. You can draw dog facts from this API using the following code:

def parse_dog_fact():
url = http://dog-api.kinduff.com/api/facts
dog_fact = requests.request("GET", url).json()
return dog_fact["facts"][0]

Now you’ll want the account to post the Tweet. If you continue with the Dog-Facts-Bot, you can use the following code. Otherwise, skip to step 6.

def post_tweet(payload, token):
print("Tweeting!")
return requests.request(
“POST”,
“https://api.twitter.com/2/tweets”,
json=payload,
headers={
"Authorization": "Bearer {}".format(token["access_token"]),
 “Content-Type”: “application/json”,
},
)

Now, you need a web page for your bot to land on that will allow the bot to authenticate with Twitter’s API. So you’ll need to build a website. It doesn’t have to be fancy, but it needs to have Twitter’s authentication API embedded so the bot can access it and authenticate on your behalf.

Then, you’ll need to create a string of code that allows the bot to log into the page. You can do so with the following code:

@app.route("/")
def demo():
global twitter
twitter = make_token()
authorization_url, state = twitter.authorization_url(
auth_url, code_challenge=code_challenge, code_challenge_method="S256"
)
session["oauth_state"] = state
return redirect(authorization_url)

Finally, you need the bot to turn the dog facts it scrapes into a JSON payload that the bot can post to Twitter. Code the following:

@app.route("/oauth/callback", methods=["GET"])
def callback():
code = request.args.get("code")
token = twitter.fetch_token(
token_url=token_url,
client_secret=client_secret,
code_verifier=code_verifier,
code=code,
)
st_token = '"{}"'.format(token)
j_token = json.loads(st_token)
r.set("token", j_token)
dog_fact = parse_dog_fact()
payload = {"text": "{}".format(dog_fact)}
response = post_tweet(payload, token).json()
return response
if __name__ == "__main__":
app.run()

With this, your bot is complete! You just need to automate it so that the script runs independently.

To test the file locally, enter the following into your terminal:

python main.py

If your code is successful, you’ll see JSON payload in your browser like the one below:

{“data” :{ “id”: “56258425364861”, “text”: “Dogs are not colorblind. They can see several shades of yellow and blue.” }}

Step 6: Posting a Tweet with the Tweepy API

You can also use the Tweepy API to make tweets without requesting anything from another source. You can do that by first installing Tweepy’s API by entering the following into your terminal:

pip install tweepy

That will install Tweepy’s API and get you ready to tweet. Then, you’ll need to authenticate your OAuth IDs in your Python file. Do that with the following code with all the Keys changed to the keys for your Twitter bot:

import tweepy
API_KEY: ‘API_KEY’
CONSUMER_SECRET = ‘API_SECRET_KEY’
ACCESS_KEY = ‘ACCESS_KEY’
ACCESS_SECRET = ‘ACCESS_SECRET_KEY’
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
api.update_status("Hello, World!" )

Step 7: Automating Your Bot

Now that you have a bot that will post to Twitter when it runs, you need to automate it so that it runs on its own every so often and posts a tweet without your input. To do so, you’ll need to make a new Python file.

touch twit_auto.py

You can name it whatever you want; we’ve gone with something that accurately describes what it does. You’ll need to enter this into your terminal to create a new Python file.

The first thing you want this script to do is to import your main.py. Then, you need it to import the other packages it needs to run.

import main
import redis
import json
import os

Now you want a variable named “twitter” that will “make_token.”

twitter = main.make_token()
client_id = os.environ.get("CLIENT_ID")
client_secret = os.environ.get("CLIENT_SECRET")
token_url = "https://api.twitter.com/2/oauth2/token"

Then, you need to access Redis and get the token, which we aptly named “token.”

t = main.r.get("token")
bb_t = t.decode("utf8").replace("'", '"')
data = json.loads(bb_t)

OAuth 2.0 tokens are only valid for two hours. So, you’ll need the program to refresh your token using Twitter’s Refresh Tokens.

refreshed_token = twitter.refresh_token(

client_id=client_id,
client_secret=client_secret,
token_url=token_url,
refresh_token=data["refresh_token"],
)

You’ll need it to load the token into a JSON object before you can save it back to Redis with the token value. You can do that with the following code:

st_refreshed_token = '"{}"'.format(refreshed_token)
j_refreshed_token = json.loads(st_refreshed_token)
main.r.set("token", j_refreshed_token)

Now, you’ll need to force the program to scrape a dog fact from your API and post it to Twitter. Code following:

dog_fact = main.parse_dog_fact()
payload = {"text": "{}".format(dog_fact)}
main.post_tweet(payload, refreshed_token)

To test the file locally, enter the following into your terminal:

python twit_auto.py

Then, you just need to set the code to run on its own every however long you want, and you’ve got yourself a Twitter bot!

In the following video, Vikas Jha explains how using a bot to auto tweet can increase your followers, likes, and retweets. Then he demonstrates how to create the bot using the Tweepy Python module.

Final Thoughts

There are hundreds of other kinds of Twitter bots you can make, and there are also many tutorials on how to code different types of Twitter bots. The more you learn about Python, the more you’ll be able to customize and change your Twitter bot. So, keep that in mind when researching Twitter bots. There’s more than one way to get the job done!

Frequently Asked Questions

Are bots against Twitter rules?

You may hear negative talk of “bots” on Twitter. But rest assured; there is no harm in creating a simple image bot or facts bot for Twitter. Twitter only bans bot activity considered harmful to the public or those that try to use Twitter’s platform to influence public events.

How often can Twitter bots repeat themselves?

Twitter bots cannot post the same Tweet more than once within a specific period. It’s not documented what this period is (to avoid abuse), but generally, posting the same tweet more than once every two hours will be flagged.

Are there rules for what Twitter bots can say?

Twitter bots are — or at least were — not allowed to spam the website and its users or disseminate hateful content.

What language is best for creating a Twitter bot?

Python is probably the most straightforward language to create a Twitter bot.

How do you create a Twitter bot?

You can create a Twitter bot using a Twitter Developer account and basic coding skills.

To top