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.

1touch /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#!/usr/bin/python3
 2import json
 3import requests
 4from datetime import date
 5from datetime import time
 6from datetime import datetime
 7
 8# I pull data for Germany. You shall use your country.
 9url = "https://corona-stats.online/Germany?format=json"
10
11response = requests.get(url)
12r_dict = response.json()
13
14time_now = datetime.now()
15
16print("_Covid19 stats:_")
17print(time_now.strftime("_%R %Y-%m-%d_"))
18print()
19print("*Germany*") # Put your country name instead.
20print("Total cases:", "{:,}".format(int(r_dict['data'][0]['cases'])).replace(',',' '))
21print("Recovered:", "{:,}".format(int(r_dict['data'][0]['recovered'])).replace(',',' '))
22print("Critical:", "{:,}".format(int(r_dict['data'][0]['critical'])).replace(',',' '))
23print("Total deaths:", "{:,}".format(int(r_dict['data'][0]['deaths'])).replace(',',' '))
24print("Cases per 1 million:", "{:_.2f}".format(float(r_dict['data'][0]['casesPerOneMillion'])).replace('_',' '))
25
26print()
27print("*World stats*")
28print("Total cases:", "{:,}".format(int(r_dict['worldStats']['cases'])).replace(',',' '))
29print("Recovered:", "{:,}".format(int(r_dict['worldStats']['recovered'])).replace(',',' '))
30print("Critical:", "{:,}".format(int(r_dict['worldStats']['critical'])).replace(',',' '))
31print("Total deaths:", "{:,}".format(int(r_dict['worldStats']['deaths'])).replace(',',' '))
32print("Cases per 1 million:", "{:_.2f}".format(float(r_dict['worldStats']['casesPerOneMillion'])).replace('_',' '))
33print()

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

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

OpenHab rule

It is almost the same as the rule here.

1rule "corona update"
2when Time cron "0 30 8,19 * * ?" // updates are sent at 8:30 and at 19:30 every day
3then
4    var String corona = executeCommandLine("/opt/corona-update/corona-info.py", 5000)
5
6    // Use name of your Telegram bot instead of <bot_name>. 
7    sendTelegram("<bot_name>", corona)
8end