The world is slowly recovering from the pandemic. The borders are opening. You start thinking about traveling to another country. However, you don’t want to rush into the country where COVID cases are still growing and contribute to spreading the virus.

The solution is to use Python to monitor the country’s COVID recovery status and book your travel when it’s relatively safe. We’re going to automate this process using Python in under 50 lines of code.

In this tutorial, we will write a Python script that uses COVID API and sends messages to WhatsApp. Notifications will be sent using the Twilio service. We will upload our code into Seamless Cloud that will execute our script daily. All services we’re using have free-tier accounts. Let’s get into it.

Disclaimer

This post has purely educational purposes. Please always check traveling recommendations from official sources in your country and the country you’re traveling to.


We will need to accomplish the following steps:

  1. Set up Twilio account and connect it to WhatsApp.
  2. Write the Python script that processes COVID data.
  3. Upload the Python code into the Seamless Cloud to run it daily.

If you’re here just for the code, here it is.

Step 1: Set up a Twilio account and connect it to WhatsApp

Twilio – Communication APIs for SMS, Voice, Video and Authentication
Sign up and start building Talk to an expert Marks & Spencer Blue Apron Zendesk American Red Cross ING Dr. On-Demand…www.twilio.com

We’re going to use Twilio to send messages to WhatsApp. It is much more difficult to send messages directly from Python.

Please go to the https://www.twilio.com/ and sign up.

There will be a series of questions to customize your experience. Chose options that you code, your preferred language is Python and that you want to use Twilio in a project, specifically, send WhatsApp messages.

After that, Twillio asks you if you want to activate the Sandbox. Agree and click “Confirm”. Then follow the instructions to connect to your WhatsApp account.

Next, pick the option “Send a One-Way WhatsApp Message”. On this screen, you will find your account ID and AuthToken. That is all we need in our Python script to send a message to WhatsApp. In the last line in the “Request” section you can find your Account Id and Auth Token. They are written in the form account_id:auth_token . We will insert those values into our Python script in the next section.

Step 2: Write the Python script that processes COVID data

First, let’s create a file and call it function.py . Let’s add all Python requirements at the top of the file.

from datetime import datetime, timedelta

import requests

from twilio.rest import Client
from dateutil.parser import parse

We also need to create requirements.txt file and put requirements there so we can later install them using the Pip package installer.

requests
twilio
python-dateutil

Now, let’s get the actual code done. We need one main function and 2 helper functions. In the function.py let’s add this function to the bottom of the file:

def get_country_confirmed_infected(country, start_date, end_date):
    resp = requests.get(f"https://api.covid19api.com/country/{country}/status/confirmed", params={"from": start_date, "to": end_date})
    return resp.json()

What this Python code does is it makes a request to the open COVID API and returns confirmed cases for a specific country for dates between start_date and end_date .

Let’s add the second helper function under the first one.

def send_whatsapp_message(msg):
    account_sid = '<your Twilio account id>'
    auth_token = '<your Twilio auth token>'
    Client(account_sid, auth_token).messages.create(
        from_='whatsapp:+14155238886',
        to='whatsapp:<your phone number>',
        body=msg
    )

It sends WhatsApp messages, pretty self-explanatory. Please put your real account credentials from Twilio that you’ve received in the previous section. Also, you need to insert your real phone number instead of the placeholder.

Now, the main function:

def main():
    country = "Japan"
    today = datetime.now().date()
    week_ago = today - timedelta(days=7)
    print("Getting COVID data")
    cases = get_country_confirmed_infected(country, week_ago, today)
    latest_day = cases[-1]
    earliest_day = cases[0]
    percentage_increase = (latest_day['Cases'] - earliest_day['Cases']) / (earliest_day['Cases'] / 100)
    msg = f"There were {latest_day['Cases']} confirmed COVID cases in {country} " \
          f"on {parse(latest_day['Date']).date()}\n"
    if percentage_increase > 0:
        msg += f"This is {round(abs(percentage_increase), 4)}% increase over the last week. " \
               f"Travel is not recommended."
    else:
        msg += f"This is {round(abs(percentage_increase), 4)}% decrease over the last week. " \
               f"Travel may be OK."
    print("Sending Whatsapp message")
    send_whatsapp_message(msg)
    print("Job finished successfully")

Also, let’s make the file executable by adding this to the bottom:

if __name__ == '__main__':
main()

Let’s say we want to travel to Japan. By using calling the function get_country_confirmed_infected(country, week_ago, today) we’re going to get the data with COVID confirmed cases for the last week in Japan. Then we can calculate the percentage increase in cases for the last week by using the number of cases in the first element of response array and the last element.

Next, we create the message text. If the percentage_increase is greater than 0, then cases are growing and our message will contain the recommendation not to travel. However, if it is less than 0, the message is different, it says that it may be OK to travel.

Again, this post has purely educational purposes. Please check travel guidelines from official sources before deciding to travel.

The last thing we need to do is to send a message to WhatsApp. That is accomplished in the line send_whatsapp_message(msg).

That’s it! Less than 50 lines of code. Let’s get this thing actually working.

Step 3: Upload the Python code into the Seamless Cloud to run it daily

Seamless Cloud
Seamless Cloud is a cloud solution for running python code on schedule. Status monitoring and real-time logs included.www.seamlesscloud.io

Seamless Cloud is a service for running Python code on schedule. It is perfect for our use case because you don’t need to set up any cloud resources or infrastructure yourself.

First, create a free account at http://seamlesscloud.io.

Follow the instructions to create your first example job.

If you follow instructions one by one you should be familiar with the platform in under 5 minutes. If you get lost at any step, you can use this Quick Start Guide as a reference. Please note that you need Pip package installer to install the package that we will use to deploy your code.

By the end of the previous section, you should have 2 files: function.py and requirements.txt. Just in case, this is the full code. Make sure those files are in a separate folder (name does not matter). Open the terminal and cd into the folder.

Hopefully, you’ve successfully installed smls package from Pip and authorized in Seamless Cloud by running smls auth <your api key>. Now while in the folder, please run smls run. This command is going to execute the code in function.py on the Seamless Cloud server, you don’t need to worry about a local development environment. If everything is right, you should see a message in your WhatsApp app.

The last step is to run our code every day. It’s trivial to do with Seamless Cloud. You just need to execute smls publish --name "Monitor COVID Status" -- schedule "0 9 * * *". That’s it. Your code will now run every day at 9 AM every day (UTC). The schedule is in the cron format.

Congratulations! As a next step, you can make the script more complicated by monitoring multiple countries. You can also add a condition to the Python code to only send you notifications when the percentage decrease in confirmed COVID cases bypasses a certain threshold.

Stay safe and good luck!

You can read more of our blog here.