COVID19 stats to Telegram (Python version)

Continuing my previous post about Covid19 stats.

I understand, that using Shell script to parse text table information from the site is not the most reliable method, although it is very quick and dirty to make.

Thankfully, the Coronavirus Tracker CLI project also provides statistics in JSON format. Which is more reliable and more predictable in its data structure.

Python script for pulling data

As before, I created the file in the target directory.

1
touch /opt/corona-updade/corona-info.py

And then I made the Python script, which produces the same output, as a Shell script from the previous post

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/python3
import json
import requests
from datetime import date
from datetime import time
from datetime import datetime

# I pull data for Germany. You shall use your country.
url = "https://corona-stats.online/Germany?format=json"

response = requests.get(url)
r_dict = response.json()

time_now = datetime.now()

print("_Covid19 stats:_")
print(time_now.strftime("_%R %Y-%m-%d_"))
print()
print("*Germany*") # Put your country name instead.
print("Total cases:", "{:,}".format(int(r_dict['data'][0]['cases'])).replace(',',' '))
print("Recovered:", "{:,}".format(int(r_dict['data'][0]['recovered'])).replace(',',' '))
print("Critical:", "{:,}".format(int(r_dict['data'][0]['critical'])).replace(',',' '))
print("Total deaths:", "{:,}".format(int(r_dict['data'][0]['deaths'])).replace(',',' '))
print("Cases per 1 million:", "{:_.2f}".format(float(r_dict['data'][0]['casesPerOneMillion'])).replace('_',' '))

print()
print("*World stats*")
print("Total cases:", "{:,}".format(int(r_dict['worldStats']['cases'])).replace(',',' '))
print("Recovered:", "{:,}".format(int(r_dict['worldStats']['recovered'])).replace(',',' '))
print("Critical:", "{:,}".format(int(r_dict['worldStats']['critical'])).replace(',',' '))
print("Total deaths:", "{:,}".format(int(r_dict['worldStats']['deaths'])).replace(',',' '))
print("Cases per 1 million:", "{:_.2f}".format(float(r_dict['worldStats']['casesPerOneMillion'])).replace('_',' '))
print()

Then make file executable and change ownership to openhab user, otherwise OpenHab rules engine will not be able to process the file.

1
2
chmod 750 /opt/corona-update/corona-info.py
sudo chown openhab:openhab /opt/corona-update/corona-info.py

OpenHab rule

It is almost the same as the rule here.

1
2
3
4
5
6
7
8
rule "corona update"
when Time cron "0 30 8,19 * * ?" // updates are sent at 8:30 and at 19:30 every day
then
    var String corona = executeCommandLine("/opt/corona-update/corona-info.py", 5000)

    // Use name of your Telegram bot instead of <bot_name>. 
    sendTelegram("<bot_name>", corona)
end