Automate Retweeting and Liking using Python and Heroku

Wordy Woman
5 min readJan 10, 2021

--

This article broadly narrates the steps taken to automate and deploy a social network bot using Tweepy , a Python library created to serve requests to the Twitter API and Heroku , a platform-as-a-service(PAAS) provider that allows developers to deploy applications to the cloud and has a free tier.

The code used can be found here.

Step 1: Get the Keys

Since you will be accessing tweets using the API , it is imperative to get access to the API. This is done using two pairs of string credentials: the API keys (access keys) and the consumer keys that are generated from an application created on the Twitter Developer site.

Step 2: Setup the Environment

The commands used for setup will vary across operating systems and the author here uses a Windows (x64 bit) system. Reader discretion is therefore advised.

Tweepy can be added to python libraries available locally using pip. For this ,you can start off by creating a virtual environment that you will use for the rest of this mini-project to keep track of the required libraries and will be useful when it comes to deploying.

To create a virtual environment named “virtualenv” within the project directory, navigate to the folder path in the command line and run python3 -m venv virtualenv . To activate the created virtual environment , run <path to virtual environment>\Scripts\activate.bat and the name of the virtual environment appears in brackets on the terminal line.

From here you can then run pip install tweepy to install the package.

Step 3: Authenticate

To set up a connection to Twitter, you need to send the keys for authentication using an OAuthHandler object. As a rule of thumb, never hard code your API keys, choosing instead to use environment variables.

#set the keys  consumer_key = environ["CONSUMER_KEY"]
consumer_secret = environ["CONSUMER_SECRET"]
access_token = environ["ACCESS_TOKEN"]
access_token_secret = environ["ACCESS_TOKEN_SECRET"]
#send the keys for authentication
auth = tweepy.OAuthHandler(consumer_key , consumer_secret)
auth.set_access_token(access_token , access_token_secret)
api = tweepy.API(auth , wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
try:
api.verify_credentials()
except Exception as e:
logger.error("Error creating API" , exc_info=True)
raise e
logger.info('API Created')

Step 4: Create the Bot

For retweeting and liking , the bot first checks that the tweet is not from the same account as the one on which the bot runs. If the tweet has not been liked, the bot likes it else it returns an error using a logging object and the same goes for retweeting.

if tweet.in_reply_to_status_id is not None or \
tweet.user.id == self.me.id:
return
if not tweet.favorited:
#mark it as liked since it is not yet liked
try:
tweet.favorite()
except Exception as e:
logger.error("error on fav and retweet" , exc_info=True)
if not tweet.retweeted:
#retweet
try:
tweet.retweet()
except Exception as e:
logger.error("Error on fav and retweet" , exc_info=True)

To fetch the tweets, you can use a Stream object that takes a StreamListener and authentication as arguments and provides a filter method on the returned object.

 tweets_listener = FavRetweetListener(api)
stream = tweepy.Stream(api.auth , tweets_listener)
stream.filter(track=keywords , languages=['en'])

I followed a blog post on RealPython for this part and the link is at the bottom of this article.

Step 5: Deploy

Now that you have your bot ready, it is time to let the chick leave the nest.

For this we will use Heroku which requires that you already have installed Git. Login to Heroku and create a new app.

This leads to the following page :

` int Deploy Tab in Heroku

For this project, we will deploy by connecting to GitHub therefore, navigate to GitHub and create a new repository. Do not forget to initialize it with a Read-Me. Clone the created repository locally.

At this point , revive the command line and navigate to the project virtual environment. Start by generating a requirement text file by running pip freeze > requirements.txt .This adds a requirements file to the project directory . Using type nul > runtime.txt add an empty text file which you will edit to indicate the version of python being used. You can find this out by running python --version in the command line. At the time of this writing, the version in use is python-3.9.1.

Copy the bot and its authentication modules as well as the requirement and runtime files into the cloned directory and add a file called Procfile with no extensions.The latter indicates what kind of a service is to be run , whether web or worker and the command to run.

Stage the changes , commit and then push the changes to the git repository.

Back on the Heroku application dashboard,since the authentication needs the API keys, under the Settings tab, reveal the config vars and add the keys and the values. In this case for example, the key is CONSUMER_KEY and the value is the string value generated from the Twitter Developer application. Return to Deploy and select the connect to GitHub option and search for the repository and connect. Proceed to enable builds from changes and watch the log of the build.

Things to look out for:

In case the build completes successfully and there are no workers, try navigating to the cloned directory and running the following command in the CLI:

heroku ps:scale worker=1 -a <name_of_heroku_application>

In case the build completes successfully, make sure that the workers are on.

To check the run results of the bot , you can see this under the More option on the right hand side of the Heroku dashboard.

Heroku Navigation

Referenced Materials

I made use of the following sources to prepare and serve the bot:

Adriaan Van Niekerk’s YouTube video: Python Tutorial | How to deploy your Python Twitter bot to Heroku so that it runs in the cloud

Miguel Garcia’s blog post on Real Python:How to Make a Twitter Bot in Python With Tweepy

--

--