How To Create A Twitter Retweet Bot Using Python

Liquet
Python in Plain English
11 min readApr 27, 2021

--

Photo by Chris J. Davis on Unsplash

If you’ve been tweeting about tech on Twitter and using hashtags such as “#100DaysOfCode”, “#30DaysOfCode”, “dotnet”, “csharp”, “python”, or any other tech related hashtag, you might have noticed that your tweets instantly get retweeted by some interesting looking accounts.

Upon closer inspection, they seem to be bots that retweet specific hashtags. Now you might be curious. How do I make my own retweet bot? Well first, let’s start off with an important question first. Why should you make your own retweet bot?

Why Should You Make A Twitter Retweet Bot?

  • They make a cool personal project that you can show off to employers without fear of some kind of NDA.
  • It’s an awesome way to make your name or brand more visible to other developers on Twitter in an automated way.
  • It’s a great learning opportunity.
  • You help platform your fellow developers as people will likely start to follow your bot on Twitter.

If any of these reasons appeal to you and you’re further interested in learning the basics of making a retweet bot using Python and a library named tweepy, then read on!

Step 1. Create a New Twitter Account For Your Retweet Bot and Sign Up For Twitter’s Developer Program

Photo by Fitore F on Unsplash

We will start by making a new Twitter account for your retweet bot. It helps to add a profile picture, a short bio with a link to your bot’s github repo, and a profile header to make it more personable.

After creating the new account, go to Twitter’s developer platform (while signed into your bot’s account) and sign up via the “Apply” button on the top right. It will ask you a variety of questions ranging from whether this is for business or personal use, and it will also ask you for your phone number.

After this, you should be able to access the dashboard.

Twitter Developer Dashboard

Step 2. Create a New Project

The next step is to click on that nice shiny button, “Create Project”. It will ask you to name the project, will ask you what you’re using this project for, ask you for a small description of the project, and then ask you to name your App (You can make many apps for each project, so name it accordingly.) After this, you should be redirected to this screen:

API Keys And API Secret Key

From this screen, take your API Key and API Secret Key and save it somewhere. Note: Do NOT publicly post your API Key and Secret Key or give it to any unauthorized individuals under any circumstances. If you do, you should quickly regenerate your keys and secret keys.

After this, you can now see your Project and App in the menu on the left side of your screen. Expand the button and click on your app. In my case, I named my app “LQ RT Bot”.

You should now be seeing this screen:

If the App permissions say: “Read Only” then click Edit and make sure it has Read and Write permissions. After that, head over to “Keys and tokens” and generate a new Access Token and Access Token Secret.

Put these aside with your API key and API key secret, you’ll be needing them later. Note: Do NOT publicly post your Access Token or Access Token Secret or give it to any unauthorized individuals. If you suspect your Token/Secret has been compromised, please regenerate them.

Step 3. Setting Up Virtual Environment

Photo by Florian Olivo on Unsplash

The next step in creating your retweet bot is to start setting things up. We will be using Python’s handy virtual environment module to make sure things remain consistent, in case you want to upload this onto a server someday. Open up your favorite command terminal (I’m doing this on Windows, so this will go according to Windows CMD terminal commands. Reference this page to find out what you need for Mac or Linux), navigate to where you want to start coding, and make sure you have venv by executing the command:

python -m pip install --user virtualenv
I already have it installed so your screen may vary

If you already have virtual environment installed, go ahead and execute this command:

python -m venv venv

This should create a folder named “venv” (I know it looked silly to write venv twice in the last command, the second one names the folder.) Inside this folder is three more folders and a configuration file. Now we just need to activate the virtual environment. If you’re using Windows Powershell, ignore this step, but if you’re using Windows CMD, execute:

powershell

This will let you have powershell capabilities while using the regular Windows command prompt. Now we can execute the command:

venv/Scripts/activate

If you’re successful, there should now be a “(venv)” at the beginning of every line.

Step 4. Installing Dependencies And Creating Dependency Files

The next step after activating venv is to finally install our dependencies. This is done by executing the command:

python -m pip install tweepy

This will install tweepy, a python library for easily accessing the Twitter API. We will also go ahead and install python-dotenv by executing the command:

python -m pip install python-dotenv

We will be using python-dotenv to store some environment variables. We could use the venv activate script to do it, but for the sake of simplicity, this will be the way used in this tutorial.

After installing your dependencies, we will now store them into a file named requirements.txt using the command:

pip freeze > requirements.txt

This will make it so that you will no longer have to manually download all of your dependencies one by one if you decide to deploy this somewhere else, on top of just being pretty good practice.

Step 5. Time To Code

Photo by Joshua Aragon on Unsplash

Now comes the time we’ve all been waiting for, time to actually write some code. Open up your favorite coding tool and open up the folder we made for this project. In my case, I will be using Visual Studio Code.

Create a file named .env in the base directory of the project. Remember those API keys and access tokens we set aside? This is where we will be putting them. Name them appropriately followed by an equals sign and then the value.

In .envtwitter_api_key=<YOUR API KEY HERE>
twitter_api_secret=<YOUR API SECRET HERE>
twitter_access_token=<YOUR ACCESS TOKEN HERE>
twitter_access_token_secret=<YOUR ACCESS TOKEN SECRET HERE>

After that, we’re going to make a file named bot.py and we will use this to write our code to authenticate/log in.

Start off by importing our dependencies and our environment variables. Importing the environment variables like this is optional but it makes the code a little bit easier to read and cleaner as a result.

in bot.py# import dependencies
import tweepy
import os
from dotenv import load_dotenv
# load our .env file to make use of the environment variables
load_dotenv()
# import and assign our environment variables
API_KEY = os.getenv('twitter_api_key')
API_SECRET = os.getenv('twitter_api_secret')
ACCESS_TOKEN = os.getenv('twitter_access_token')
TOKEN_SECRET = os.getenv('twitter_token_secret')

Next, we’re going to instantiate tweepy’s authentication handler using the api key and the api secret. Afterwards, we’ll set the access token on our authentication handler using our access token and token secret to finish up the authentication process. Once that is done, we can instantiate a new tweepy API object using the authentication handler object we created.

in bot.py# import dependencies
import tweepy
import os
from dotenv import load_dotenv
# load our .env file to make use of the environment variables
load_dotenv()
# import and assign our environment variables
API_KEY = os.getenv('twitter_api_key')
API_SECRET = os.getenv('twitter_api_secret')
ACCESS_TOKEN = os.getenv('twitter_access_token')
TOKEN_SECRET = os.getenv('twitter_token_secret')
# instantiate oauth handler and set access token
twitter_oauth = tweepy.OAuthHandler(API_KEY, API_SECRET)
twitter_oauth.set_access_token(ACCESS_TOKEN, TOKEN_SECRET)
# instantiate tweepy api object using the authentication handler object
twitter_api = tweepy.API(twitter_oauth)

You might be wondering now how you can see if you’ve done everything right so far. We can test by having our new tweepy API object tell us. The API object has a method named “verify_credentials” that will either return a bunch of data with info on which user is logged in, or will return an error. Put that into a try block with the except block catching a “tweepy.TweepError” followed by a final except block to catch anything else that might have gone wrong.

in bot.py# import dependencies
import tweepy
import os
from dotenv import load_dotenv
# load our .env file to make use of the environment variables
load_dotenv()
# import and assign our environment variables
API_KEY = os.getenv('twitter_api_key')
API_SECRET = os.getenv('twitter_api_secret')
ACCESS_TOKEN = os.getenv('twitter_access_token')
TOKEN_SECRET = os.getenv('twitter_token_secret')
# instantiate oauth handler and set access token
twitter_oauth = tweepy.OAuthHandler(API_KEY, API_SECRET)
twitter_oauth.set_access_token(ACCESS_TOKEN, TOKEN_SECRET)
# instantiate tweepy api object using the authentication handler object
twitter_api = tweepy.API(twitter_oauth)
# attempt credential verification. prints exception if something is wrong
try
:
print(twitter_api.verify_credentials())
print("Successfully logged in")
except tweepy.TweepError as e:
print(e)
except Exception as e:
print(e)

Now we can run bot.py and see what kind of results we get. If all is successful, you should get a huge message that tells you all kinds of things about the account that tweepy logged into. If something is wrong, the console should tell you what is going on (usually related to having the wrong api key, secret, token, etc).

The massive blacked out section is what would show up if it is successful, followed by the line “Successfully logged in”. The section after that shows what happens if something goes wrong with the authentication process (I removed a part of the authentication to make an example)

If your authentication is successful, we can now move on to the exciting part: pulling in tweets and retweeting them.

Create a new file named “streamlistener.py” and start by importing tweepy. This file is where we will hold all of our logic for handling each tweet. Afterwards, we will create a new class named “StreamListener” and it will take in a parameter of “tweepy.StreamListener”.

in streamlistener.py# import dependencies
import tweepy
# create new class "StreamListener"
# takes in tweepy.StreamListener as a parameter
class StreamListener(tweepy.StreamListener):
def __init__(self, api):
self.api = api
self.me = api.me()

Next, we’re going to definte two functions: on_status and on_error. The on_status function will contain the logic behind what we do with each tweet we receive from the stream listener. The on_error function will contain the logic behind what happens if something goes wrong.

in streamlistener.py# import dependencies
import tweepy
# create new class "StreamListener"
# takes in tweepy.StreamListener as a parameter
class StreamListener(tweepy.StreamListener):
def __init__(self, api):
self.api = api
self.me = api.me()

# the function containing the logic on what to do for each tweet
def on_status(self, tweet):
# We only want the bot to retweet original tweets, not replies.
# We also don't want the bot to retweet itself
if tweet.in_reply_to_status_id is not None or \
tweet.use.id == self.me.id:
return
# If we haven't retweeted this tweet yet, retweet it
if not tweet.retweeted:
try:
tweet.retweet()
print("Tweet retweeted successfully")
except Exception as e:
print(e)
# the function containing the logic in case there is an error
def on_error(self, status):
print(f"Error while retweeting: {status}")

In the on_status function, we want to ignore any tweets that are replies to other tweets, and we want the bot to ignore it’s own retweets. To do this, we just check for those conditions and simply “return” if they are true. After this, we check if we have already retweeted that tweet and if not, we use the retweet() method that is available to the tweet object to retweet that tweet.

As a side note, some bots also favorite the tweet when they retweet it. If you also want this functionality, you just check to see if you have favorited the tweet already in the same way you check for retweets, and then you use the favorite() method available to the tweet object.

  # the function containing the logic on what to do for each tweet
def on_status(self, tweet):
# We only want the bot to retweet original tweets, not replies.
# We also don't want the bot to retweet itself
if tweet.in_reply_to_status_id is not None or \
tweet.use.id == self.me.id:
return
# If we haven't retweeted this tweet yet, retweet it
if not tweet.retweeted:
try:
tweet.retweet()
print("Tweet retweeted successfully")
except Exception as e:
print(e)
# If we haven't favorited this tweet yet, favorite it
if not tweet.favorited:
try:
tweet.favorite()
print("Tweet favorited successfully")
except Exception as e:
print(e)

Now that we’ve completed this file, we can now use it in our bot.py file. Import the StreamListener class and instantiate a new StreamListener object. Pass in the Twitter API object as a parameter. After this, we’re going to instantiate a tweepy.Stream object, passing in our Twitter API’s auth parameter and the new StreamListener object.

After this, we use the filter() method available to the tweepy.Stream class, passing in ‘track=[“#100DaysOfCode”, “#AnotherHashtagWeMightWannaTrack”]’ to signal that we want to track these specific hashtags/search results and ‘languages=[“en”, “MaybeSomeOtherLanguage”]’ to signal that we only want tweets in English and maybe another specific language. Your bot.py should now look something like:

in bot.py# import dependencies
import tweepy
import os
from dotenv import load_dotenv
from streamlistener import StreamListener <-- Make sure to have this
# load our .env file to make use of the environment variables
load_dotenv()
# import and assign our environment variables
API_KEY = os.getenv('twitter_api_key')
API_SECRET = os.getenv('twitter_api_secret')
ACCESS_TOKEN = os.getenv('twitter_access_token')
TOKEN_SECRET = os.getenv('twitter_token_secret')
# instantiate oauth handler and set access token
twitter_oauth = tweepy.OAuthHandler(API_KEY, API_SECRET)
twitter_oauth.set_access_token(ACCESS_TOKEN, TOKEN_SECRET)
# instantiate tweepy api object using the authentication handler object
twitter_api = tweepy.API(twitter_oauth)
# attempt credential verification. prints exception if something is wrong
try
:
print(twitter_api.verify_credentials())
print("Successfully logged in")
except tweepy.TweepError as e:
print(e)
except Exception as e:
print(e)
# instantiate a StreamListener object
tweets_listener = StreamListener(twitter_api)
# instantiate a tweepy.Stream object
tweet_stream = tweepy.Stream(twitter_api.auth, tweets_listener)
# Use the filter method
tweet_stream.filter(track=["#100DaysOfCode", "#30DaysOfCode"], languages=["en"])

At this point, you should be able to run “python bot.py” in your terminal and it will log in and start retweeting and favoriting.

Success!

Conclusion

This is just the tip of the iceberg when it comes to what you can do with this bot. You can add additional logic to StreamListener’s on_status method to do things like filter out other bot users or determine based on someone’s profile whether or not you want to retweet their tweet (trying to implement a filter that tries to identify descriptions that belong to malicious users).

If you found this guide particularly helpful, please feel free to check out @LiquetBot on Twitter, Liquet Bot’s Github Repo, my Ko-Fi, or follow me on medium for more articles like this one. For more information on tweepy, feel free to check out the tutorial I used to make my own bot, or check out tweepy’s official site! Thank you for giving my article a read!

Further Reading

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Interested in scaling your software startup? Check out Circuit.

--

--

I'm a software engineer that enjoys mixing my passions into my code. When I'm working you can usually find me coding Discord Bots.