Aditya Bose

Software developer and part-time memelord

Covid-19 Stats Tweeter

So I finally got developer account access from Twitter which I had applied for last month to post automated coronavirus updates. In this part, we will look at the process of creating an app, and developing the code to post tweets programmatically.

We are going to use Python3 as our programming language and use the tweepy python library to access Twitter’s APIs along with lxml package to parse the Worldometers site for data. We need to install these dependencies in a new python virtual environment, and activate it to start developing.

First, we go to the apps page and create an app. We give an app name, add a description and a website url. dd description and a website url. At the bottom, we need to describe briefly how we are going to use the app, and press create.

Once created, go to the Keys and Tokens tab, and generate Access Token and Access Token Secret, and copy them along with the consumer API keys in a python file called config.py as below:

CONSUMER_KEY = '<API key>'
CONSUMER_SECRET = '<API secret key>'
ACCESS_TOKEN = '<Access token>'
ACCESS_TOKEN_SECRET = '<Access token secret>'

In the same folder as config.py, create another python file called app.py and import the tweepy module, the keys from config and authenticate the app as below:

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

Then, create an API object and verify the access credentials as below:

api = tweepy.API(auth)
api.verify_credentials()

We are now ready to compose our tweet and post it to Twitter.

We use the requests library to fetch the data for our tweet from Worldometers, parse it using xpath and save it in a variable called tweet. We can then post our tweet using a single line of code as below:

api.update_status(tweet)

To post the tweet, simply run the app.py from the console with the command

$ python app.py

We now have a basic Twitter bot ready, and can post tweets whenever we run our script. Feel free to checkout the code on Github and send PRs to improve this bot.

Also, follow the bot @covidtrackerbot on Twitter, and press the bell icon to get notified whenever there is a new tweet.

Our next steps would be to host it online and add more functionality like tweeting periodically from an infinite loop, or tweeting country-wise stats as they are updated on Worldometer.

Stay tuned for further updates!