Corona: rewrite plugin, more stats, top10 command

This commit is contained in:
oddluck 2020-03-31 23:16:30 +00:00
parent 3ae22932c1
commit 3a441bc07f

View File

@ -37,7 +37,8 @@ from supybot.commands import *
try: try:
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('Corona')
_ = PluginInternationalization("Corona")
except ImportError: except ImportError:
# Placeholder that allows to run the plugin on a bot # Placeholder that allows to run the plugin on a bot
# without the i18n module # without the i18n module
@ -293,79 +294,88 @@ countries = {
"EH": "WESTERN SAHARA", "EH": "WESTERN SAHARA",
"YE": "YEMEN", "YE": "YEMEN",
"ZM": "ZAMBIA", "ZM": "ZAMBIA",
"ZW": "ZIMBABWE" "ZW": "ZIMBABWE",
} }
states = { states = {
'AK': 'ALASKA', "AK": "ALASKA",
'AL': 'ALABAMA', "AL": "ALABAMA",
'AR': 'ARKANSAS', "AR": "ARKANSAS",
'AS': 'AMERICAN SAMOA', "AS": "AMERICAN SAMOA",
'AZ': 'ARIZONA', "AZ": "ARIZONA",
'CA': 'CALIFORNIA', "CA": "CALIFORNIA",
'CO': 'COLORADO', "CO": "COLORADO",
'CT': 'CONNECTICUT', "CT": "CONNECTICUT",
'DC': 'DISTRICT OF COLUMBIA', "DC": "DISTRICT OF COLUMBIA",
'DE': 'DELAWARE', "DE": "DELAWARE",
'FL': 'FLORIDA', "FL": "FLORIDA",
'GA': 'GEORGIA', "GA": "GEORGIA",
'GU': 'GUAM', "GU": "GUAM",
'HI': 'HAWAII', "HI": "HAWAII",
'IA': 'IOWA', "IA": "IOWA",
'ID': 'IDAHO', "ID": "IDAHO",
'IL': 'ILLINOIS', "IL": "ILLINOIS",
'IN': 'INDIANA', "IN": "INDIANA",
'KS': 'KANSAS', "KS": "KANSAS",
'KY': 'KENTUCKY', "KY": "KENTUCKY",
'LA': 'LOUISIANA', "LA": "LOUISIANA",
'MA': 'MASSACHUSETTS', "MA": "MASSACHUSETTS",
'MD': 'MARYLAND', "MD": "MARYLAND",
'ME': 'MAINE', "ME": "MAINE",
'MI': 'MICHIGAN', "MI": "MICHIGAN",
'MN': 'MINNESOTA', "MN": "MINNESOTA",
'MO': 'MISSOURI', "MO": "MISSOURI",
'MP': 'NORTHERN MARIANA ISLANDS', "MP": "NORTHERN MARIANA ISLANDS",
'MS': 'MISSISSIPPI', "MS": "MISSISSIPPI",
'MT': 'MONTANA', "MT": "MONTANA",
'NA': 'NATIONAL', "NA": "NATIONAL",
'NC': 'NORTH CAROLINA', "NC": "NORTH CAROLINA",
'ND': 'NORTH DAKOTA', "ND": "NORTH DAKOTA",
'NE': 'NEBRASKA', "NE": "NEBRASKA",
'NH': 'NEW HAMPSHIRE', "NH": "NEW HAMPSHIRE",
'NJ': 'NEW JERSEY', "NJ": "NEW JERSEY",
'NM': 'NEW MEXICO', "NM": "NEW MEXICO",
'NV': 'NEVADA', "NV": "NEVADA",
'NY': 'NEW YORK', "NY": "NEW YORK",
'OH': 'OHIO', "OH": "OHIO",
'OK': 'OKLAHOMA', "OK": "OKLAHOMA",
'OR': 'OREGON', "OR": "OREGON",
'PA': 'PENNSYLVANIA', "PA": "PENNSYLVANIA",
'PR': 'PUERTO RICO', "PR": "PUERTO RICO",
'RI': 'RHODE ISLAND', "RI": "RHODE ISLAND",
'SC': 'SOUTH CAROLINA', "SC": "SOUTH CAROLINA",
'SD': 'SOUTH DAKOTA', "SD": "SOUTH DAKOTA",
'TN': 'TENNESSEE', "TN": "TENNESSEE",
'TX': 'TEXAS', "TX": "TEXAS",
'UT': 'UTAH', "UT": "UTAH",
'VA': 'VIRGINIA', "VA": "VIRGINIA",
'VI': 'VIRGIN ISLANDS', "VI": "VIRGIN ISLANDS",
'VT': 'VERMONT', "VT": "VERMONT",
'WA': 'WASHINGTON', "WA": "WASHINGTON",
'WI': 'WISCONSIN', "WI": "WISCONSIN",
'WV': 'WEST VIRGINIA', "WV": "WEST VIRGINIA",
'WY': 'WYOMING' "WY": "WYOMING",
} }
class Corona(callbacks.Plugin): class Corona(callbacks.Plugin):
"""Displays current stats of the Coronavirus outbreak""" """Displays current stats of the Coronavirus outbreak"""
threaded = True threaded = True
def __init__(self, irc): def __init__(self, irc):
self.__parent = super(Corona, self) self.__parent = super(Corona, self)
self.__parent.__init__(irc) self.__parent.__init__(irc)
self.data = requests.structures.CaseInsensitiveDict() self.countries = requests.structures.CaseInsensitiveDict()
self.states = requests.structures.CaseInsensitiveDict()
today = datetime.datetime.utcnow() today = datetime.datetime.utcnow()
self.updated = today - datetime.timedelta(days=1) self.updated = today - datetime.timedelta(days=1)
self.headers = {}
self.top = {}
self.headers["countries"] = []
self.headers["states"] = []
self.top["countries"] = []
self.top["states"] = []
def time_created(self, time): def time_created(self, time):
""" """
@ -375,137 +385,264 @@ class Corona(callbacks.Plugin):
if d.days: if d.days:
rel_time = "{:1d}d ago".format(abs(d.days)) rel_time = "{:1d}d ago".format(abs(d.days))
elif d.seconds > 3600: elif d.seconds > 3600:
rel_time = "{:.1f}h ago".format(round((abs(d.seconds) / 3600),1)) rel_time = "{:.1f}h ago".format(round((abs(d.seconds) / 3600), 1))
elif 60 <= d.seconds < 3600: elif 60 <= d.seconds < 3600:
rel_time = "{:.1f}m ago".format(round((abs(d.seconds) / 60),1)) rel_time = "{:.1f}m ago".format(round((abs(d.seconds) / 60), 1))
else: else:
rel_time = "%ss ago" % (abs(d.seconds)) rel_time = "%ss ago" % (abs(d.seconds))
return rel_time return rel_time
@wrap([getopts({'top10':''}), optional('text')]) def get_data(self):
def corona(self, irc, msg, args, optlist, search):
"""[--top10] [region]
Displays Coronavirus statistics. Add a region name to search for country/state
specific results. Accepts full country/state names or ISO 3166-1 alpha-2 (two
character) country abbreviations and US Postal (two character) state abbreviations.
Invalid region names or search terms without data return global results.
"""
optlist = dict(optlist)
if 'top10' in optlist:
top10 = True
else:
top10 = False
OK = False OK = False
try: try:
r = requests.get('https://www.worldometers.info/coronavirus/', timeout=10) r = requests.get("https://www.worldometers.info/coronavirus/", timeout=10)
r.raise_for_status() r.raise_for_status()
OK = True OK = True
except (requests.exceptions.RequestException, requests.exceptions.HTTPError) as e: except (
log.debug('Corona: error retrieving World data from API: {0}'.format(e)) requests.exceptions.RequestException,
requests.exceptions.HTTPError,
) as e:
log.error("Corona: error retrieving World data from API: {0}".format(e))
OK = False OK = False
return
soup = BeautifulSoup(r.content) soup = BeautifulSoup(r.content)
updated = soup.find("div", text = re.compile('Last updated:')) updated = soup.find("div", text=re.compile("Last updated:"))
updated = updated.text.split(':', 1)[1].replace('GMT', '').strip() updated = updated.text.split(":", 1)[1].replace("GMT", "").strip()
updated = datetime.datetime.strptime(updated, "%B %d, %Y, %H:%M") updated = datetime.datetime.strptime(updated, "%B %d, %Y, %H:%M")
if OK and updated > self.updated: if OK and updated > self.updated:
self.updated = updated self.updated = updated
table = soup.find("table", { "id" : "main_table_countries_today" }) table = soup.find("table", {"id": "main_table_countries_today"})
data = {} self.headers["countries"] = [header.text for header in table.find_all("th")]
for row in table.findAll("tr"): results = [
cells = row.findAll("td") {
if len(cells) >= 9: self.headers["countries"][i]: cell.text.strip()
country = cells[0].text.strip() for i, cell in enumerate(row.find_all("td"))
data[country] = {} }
data[country]['name'] = country for row in table.find_all("tr")
data[country]['country'] = True ]
if cells[1].text.strip(): results = sorted(
data[country]['total_cases'] = int(cells[1].text.strip().replace(',', '')) results,
else: key=lambda k_v: int(
data[country]['total_cases'] = 0 re.sub("[^\d]", "", k_v[self.headers["countries"][1]])
if cells[2].text.strip(): )
data[country]['new_cases'] = cells[2].text.strip() if len(k_v) == len(self.headers["countries"])
else: else 0,
data[country]['new_cases'] = '+0' reverse=True,
if cells[3].text.strip(): )
data[country]['total_deaths'] = cells[3].text.strip() top = []
else: for item in results:
data[country]['total_deaths'] = '0' if len(item) == len(self.headers["countries"]):
if cells[4].text.strip(): i = 0
data[country]['new_deaths'] = cells[4].text.strip() while i < len(self.headers["countries"]):
else: if i < 7 and not item[self.headers["countries"][i]]:
data[country]['new_deaths'] = '+0' item[self.headers["countries"][i]] = "0"
if cells[5].text.strip(): elif not item[self.headers["countries"][i]]:
data[country]['total_recovered'] = cells[5].text.strip() item[self.headers["countries"][i]] = "N/A"
else: if re.sub(
data[country]['total_recovered'] = '0' "[^\w ]", "", item[self.headers["countries"][i]]
if cells[6].text.strip(): ).isdigit():
data[country]['active'] = cells[6].text.strip() item[self.headers["countries"][i]] = int(
else: re.sub("[^\d]", "", item[self.headers["countries"][i]])
data[country]['active'] = 'N/A' )
if cells[7].text.strip(): i += 1
data[country]['serious'] = cells[7].text.strip() self.countries[item[self.headers["countries"][0]]] = item
else: rank = results.index(item)
data[country]['serious'] = 'N/A' self.countries[item[self.headers["countries"][0]]]["rank"] = rank
if cells[8].text.strip(): if rank > 0 and rank <= 10:
data[country]['cases_million'] = cells[8].text.strip() top.append(
else: "#{0}: \x1F{1}\x1F (\x0307{2}\x03/\x0304{3}\x03)".format(
data[country]['cases_million'] = 'N/A' rank,
if cells[9].text.strip(): item[self.headers["countries"][0]],
data[country]['deaths_million'] = cells[9].text.strip() "{:,}".format(item[self.headers["countries"][1]]),
else: "{:,}".format(item[self.headers["countries"][2]]),
data[country]['deaths_million'] = 'N/A' )
data = requests.structures.CaseInsensitiveDict(sorted(data.items(), key=lambda k_v: k_v[1]['total_cases'], reverse = True)) )
for country in data: self.top["countries"] = top
data[country]['rank'] = "#{0}".format(list(data).index(country)) for item in self.countries:
self.data.update(data)
try: try:
r = requests.get('https://www.worldometers.info/coronavirus/country/us/', timeout=10) self.countries[item]["ratio_new_cases"] = "{0:.1%}".format(
self.countries[item][self.headers["countries"][2]]
/ (
self.countries[item][self.headers["countries"][1]]
- self.countries[item][self.headers["countries"][2]]
)
)
except:
self.countries[item]["ratio_new_cases"] = "0%"
try:
self.countries[item]["ratio_new_dead"] = "{0:.1%}".format(
self.countries[item][self.headers["countries"][4]]
/ (
self.countries[item][self.headers["countries"][3]]
- self.countries[item][self.headers["countries"][4]]
)
)
except:
self.countries[item]["ratio_new_dead"] = "0%"
try:
self.countries[item]["ratio_dead"] = "{0:.1%}".format(
self.countries[item][self.headers["countries"][3]]
/ self.countries[item][self.headers["countries"][1]]
)
except:
self.countries[item]["ratio_dead"] = "N/A"
try:
self.countries[item]["ratio_recovered"] = "{0:.1%}".format(
self.countries[item][self.headers["countries"][5]]
/ self.countries[item][self.headers["countries"][1]]
)
except:
self.countries[item]["ratio_recovered"] = "N/A"
try:
self.countries[item]["mild"] = (
self.countries[item][self.headers["countries"][6]]
- self.countries[item][self.headers["countries"][7]]
)
except:
self.countries[item]["mild"] = "N/A"
try:
self.countries[item]["ratio_mild"] = "{0:.1%}".format(
self.countries[item]["mild"]
/ self.countries[item][self.headers["countries"][6]]
)
except:
self.countries[item]["ratio_mild"] = "N/A"
try:
self.countries[item]["ratio_serious"] = "{0:.1%}".format(
self.countries[item][self.headers["countries"][7]]
/ self.countries[item][self.headers["countries"][6]]
)
except:
self.countries[item]["ratio_serious"] = "N/A"
for value in self.countries[item]:
if isinstance(self.countries[item][value], int):
self.countries[item][value] = "{:,}".format(
self.countries[item][value]
)
try:
r = requests.get(
"https://www.worldometers.info/coronavirus/country/us/", timeout=10
)
r.raise_for_status() r.raise_for_status()
OK = True OK = True
except (requests.exceptions.RequestException, requests.exceptions.HTTPError) as e: except (
log.debug('Corona: error retrieving USA data from API: {0}'.format(e)) requests.exceptions.RequestException,
requests.exceptions.HTTPError,
) as e:
log.error("Corona: error retrieving USA data from API: {0}".format(e))
OK = False OK = False
return
if OK: if OK:
soup = BeautifulSoup(r.content) soup = BeautifulSoup(r.content)
table = soup.find("table", { "id" : "usa_table_countries_today" }) table = soup.find("table", {"id": "usa_table_countries_today"})
data = {} self.headers["states"] = [
for row in table.findAll("tr")[:-1]: header.text for header in table.find_all("th")
cells = row.findAll("td") ]
if len(cells) >= 7: results = [
state = cells[0].text.strip() {
data[state] = {} self.headers["states"][i]: cell.text.strip()
data[state]['country'] = False for i, cell in enumerate(row.find_all("td"))
data[state]['name'] = state }
if cells[1].text.strip(): for row in table.find_all("tr")
data[state]['total_cases'] = int(cells[1].text.strip().replace(',', '')) ]
results = sorted(
results,
key=lambda k_v: int(
re.sub("[^\d]", "", k_v[self.headers["states"][1]])
)
if len(k_v) == len(self.headers["states"])
else 0,
reverse=True,
)
top = []
for item in results:
if len(item) == len(self.headers["states"]):
i = 0
while i < len(self.headers["states"]):
if not item[self.headers["states"][i]]:
item[self.headers["states"][i]] = "0"
if re.sub(
"[^\w ]", "", item[self.headers["states"][i]]
).isdigit():
item[self.headers["states"][i]] = int(
re.sub("[^\d]", "", item[self.headers["states"][i]])
)
i += 1
self.states[item[self.headers["states"][0]]] = item
rank = results.index(item)
self.states[item[self.headers["states"][0]]]["rank"] = rank
if rank > 0 and rank <= 10:
top.append(
"#{0}: \x1F{1}\x1F (\x0307{2}\x03/\x0304{3}\x03)".format(
rank,
item[self.headers["states"][0]],
item[self.headers["states"][1]],
item[self.headers["states"][2]],
)
)
self.top["states"] = top
for item in self.states:
try:
self.states[item]["ratio_new_cases"] = "{0:.1%}".format(
self.states[item][self.headers["states"][2]]
/ (
self.states[item][self.headers["states"][1]]
- self.states[item][self.headers["states"][2]]
)
)
except:
self.states[item]["ratio_new_cases"] = "0%"
try:
self.states[item]["ratio_new_dead"] = "{0:.1%}".format(
self.states[item][self.headers["states"][4]]
/ (
self.states[item][self.headers["states"][3]]
- self.states[item][self.headers["states"][4]]
)
)
except:
self.states[item]["ratio_new_dead"] = "0%"
try:
self.states[item]["ratio_dead"] = "{0:.1%}".format(
self.states[item][self.headers["states"][3]]
/ self.states[item][self.headers["states"][1]]
)
except:
self.states[item]["ratio_dead"] = "N/A"
for value in self.states[item]:
if isinstance(self.states[item][value], int):
self.states[item][value] = "{:,}".format(
self.states[item][value]
)
return True
else: else:
data[state]['total_cases'] = '0' log.error("Corona: unable to retrieve latest USA data")
if cells[2].text.strip(): return
data[state]['new_cases'] = cells[2].text.strip() elif len(self.countries) > 0 and len(self.states) > 0:
log.info("Corona: data not yet updated, using cache")
return True
else: else:
data[state]['new_cases'] = '+0' log.error("Corona: Error. Unable to retrieve data.")
if cells[3].text.strip(): return
data[state]['total_deaths'] = cells[3].text.strip()
else: @wrap([getopts({"top10": ""}), optional("text")])
data[state]['total_deaths'] = '0' def corona(self, irc, msg, args, optlist, search):
if cells[4].text.strip(): """[region]
data[state]['new_deaths'] = cells[4].text.strip() Return Coronavirus statistics from https://www.worldometers.info/coronavirus/.
else: Search accepts full country/state names or ISO 3166-1 alpha-2 (two character)
data[state]['new_deaths'] = '+0' country abbreviations and US Postal (two character) state abbreviations.
if cells[5].text.strip(): Invalid region names or search terms without data return global results.
data[state]['active'] = cells[5].text.strip() """
else: optlist = dict(optlist)
data[state]['active'] = 'N/A' if "top10" in optlist:
data = requests.structures.CaseInsensitiveDict(sorted(data.items(), key=lambda k_v: k_v[1]['total_cases'], reverse = True)) self.top10(irc, msg, args, None)
for state in data: return
data[state]['rank'] = "#{0}".format(list(data).index(state)+1) if search:
self.data.update(data) search = search.strip()
else: if not self.get_data():
log.debug("Corona: unable to retrieve latest USA data") irc.reply(
elif len(self.data) > 0: "Error retrieving data from https://www.worldometers.info/coronavirus/"
log.debug("Corona: data not yet updated, using cache") )
else:
log.debug("Corona: Error. Unable to retrieve data.")
return return
if search and len(search) == 2: if search and len(search) == 2:
if self.registryValue("countryFirst", msg.channel): if self.registryValue("countryFirst", msg.channel):
@ -524,78 +661,134 @@ class Corona(callbacks.Plugin):
search = countries[search.upper()] search = countries[search.upper()]
except KeyError: except KeyError:
pass pass
if not top10 and search and self.data.get(search): if search and self.countries.get(search):
if self.data[search]['country']: irc.reply(
ratio_dead = "{0:.1%}".format(int(self.data[search]['total_deaths'].replace(',', ''))/self.data[search]['total_cases']) "\x02\x1F{0}\x1F: World Rank: #{1} | Cases: \x0307{2}\x03 "
ratio_recovered = "{0:.1%}".format(int(self.data[search]['total_recovered'].replace(',', ''))/self.data[search]['total_cases']) "(\x0307+{3}\x03) (\x0307+{4}\x03) | Deaths: \x0304{5}\x03 "
if self.data[search]['serious'].replace(',', '').isdigit(): "(\x0304+{6}\x03) (\x0304+{7}\x03) (\x0304{8}\x03) | Recovered: "
mild = '{:,}'.format(int(self.data[search]['active'].replace(',', '')) - int(self.data[search]['serious'].replace(',', ''))) "\x0309{9}\x03 (\x0309{10}\x03) | Active: \x0307{11}\x03 "
"(\x0310{12}\x03 Mild) (\x0313{13}\x03 Serious) (\x0310{14}\x03/"
"\x0313{15}\x03) | Cases/1M: \x0307{16}\x03 | Deaths/1M: \x0304{17}"
"\x03 | 1st Case: {18} | Updated: {19}".format(
self.countries[search][self.headers["countries"][0]],
self.countries[search]["rank"],
self.countries[search][self.headers["countries"][1]],
self.countries[search][self.headers["countries"][2]],
self.countries[search]["ratio_new_cases"],
self.countries[search][self.headers["countries"][3]],
self.countries[search][self.headers["countries"][4]],
self.countries[search]["ratio_new_dead"],
self.countries[search]["ratio_dead"],
self.countries[search][self.headers["countries"][5]],
self.countries[search]["ratio_recovered"],
self.countries[search][self.headers["countries"][6]],
self.countries[search]["mild"],
self.countries[search][self.headers["countries"][7]],
self.countries[search]["ratio_mild"],
self.countries[search]["ratio_serious"],
self.countries[search][self.headers["countries"][8]],
self.countries[search][self.headers["countries"][9]],
self.countries[search][self.headers["countries"][10]],
self.time_created(self.updated),
)
)
elif search and self.states.get(search):
irc.reply(
"\x02\x1F{0}\x1F: USA Rank: #{1} | Cases: \x0307{2}\x03 "
"(\x0307+{3}\x03) (\x0307+{4}\x03) | Deaths: \x0304{5}\x03 "
"(\x0304+{6}\x03) (\x0304+{7}\x03) (\x0304{8}\x03) | Active: "
"\x0307{9}\x03 | Updated: {10}".format(
self.states[search][self.headers["states"][0]],
self.states[search]["rank"],
self.states[search][self.headers["states"][1]],
self.states[search][self.headers["states"][2]],
self.states[search]["ratio_new_cases"],
self.states[search][self.headers["states"][3]],
self.states[search][self.headers["states"][4]],
self.states[search]["ratio_new_dead"],
self.states[search]["ratio_dead"],
self.states[search][self.headers["states"][5]],
self.time_created(self.updated),
)
)
else: else:
mild = 'N/A' irc.reply(
irc.reply("\x02\x1F{0}\x1F: World Rank: {1} | Cases: \x0307{2}\x03 (\x0307{3}\x03) | Deaths: \x0304{4}\x03 (\x0304{5}\x03) (\x0304{6}\x03) | Recovered: \x0309{7}\x03 (\x0309{8}\x03) | Active: \x0307{9}\x03 (\x0310{10}\x03 Mild) (\x0313{11}\x03 Serious) | Cases/1M: \x0307{12}\x03 | Deaths/1M: \x0304{13}\x03 | Updated: {14}".format( "\x02\x1F{0}\x1F: Cases: \x0307{1}\x03 (\x0307+{2}\x03) "
self.data[search]['name'], "(\x0307+{3}\x03) | Deaths: \x0304{4}\x03 (\x0304+{5}\x03) "
self.data[search]['rank'], "(\x0304+{6}\x03) (\x0304{7}\x03) | Recovered: \x0309{8}\x03 "
'{:,}'.format(self.data[search]['total_cases']), "(\x0309{9}\x03) | Active: \x0307{10}\x03 (\x0310{11}\x03 Mild) "
self.data[search]['new_cases'], "(\x0313{12}\x03 Serious) (\x0310{13}\x03/\x0313{14}\x03) | "
self.data[search]['total_deaths'], "Cases/1M: \x0307{15}\x03 | Deaths/1M: \x0304{16}\x03 | 1st Case: "
self.data[search]['new_deaths'], "{17} | Updated: {18}".format(
ratio_dead, "Global",
self.data[search]['total_recovered'], self.countries[list(self.countries)[0]][
ratio_recovered, self.headers["countries"][1]
self.data[search]['active'], ],
mild, self.countries[list(self.countries)[0]][
self.data[search]['serious'], self.headers["countries"][2]
self.data[search]['cases_million'], ],
self.data[search]['deaths_million'], self.countries[list(self.countries)[0]]["ratio_new_cases"],
self.time_created(updated))) self.countries[list(self.countries)[0]][
else: self.headers["countries"][3]
ratio_dead = "{0:.1%}".format(int(self.data[search]['total_deaths'].replace(',', ''))/self.data[search]['total_cases']) ],
irc.reply("\x02\x1F{0}\x1F: USA Rank: {1} | Cases: \x0307{2}\x03 (\x0307{3}\x03) | Deaths: \x0304{4}\x03 (\x0304{5}\x03) (\x0304{6}\x03) | Active: \x0307{7}\x03 | Updated: {8}".format( self.countries[list(self.countries)[0]][
self.data[search]['name'], self.headers["countries"][4]
self.data[search]['rank'], ],
'{:,}'.format(self.data[search]['total_cases']), self.countries[list(self.countries)[0]]["ratio_new_dead"],
self.data[search]['new_cases'], self.countries[list(self.countries)[0]]["ratio_dead"],
self.data[search]['total_deaths'], self.countries[list(self.countries)[0]][
self.data[search]['new_deaths'], self.headers["countries"][5]
ratio_dead, ],
self.data[search]['active'], self.countries[list(self.countries)[0]]["ratio_recovered"],
self.time_created(updated))) self.countries[list(self.countries)[0]][
elif not top10: self.headers["countries"][6]
if self.data['total:']['serious'].replace(',', '').isdigit(): ],
mild = '{:,}'.format(int(self.data['total:']['active'].replace(',', '')) - int(self.data['total:']['serious'].replace(',', ''))) self.countries[list(self.countries)[0]]["mild"],
else: self.countries[list(self.countries)[0]][
mild = 'N/A' self.headers["countries"][7]
ratio_dead = "{0:.1%}".format(int(self.data['total:']['total_deaths'].replace(',', ''))/self.data['total:']['total_cases']) ],
ratio_recovered = "{0:.1%}".format(int(self.data['total:']['total_recovered'].replace(',', ''))/self.data['total:']['total_cases']) self.countries[list(self.countries)[0]]["ratio_mild"],
irc.reply("\x02\x1F{0}\x1F: Cases: \x0307{1}\x03 (\x0307{2}\x03) | Deaths: \x0304{3}\x03 (\x0304{4}\x03) (\x0304{5}\x03) | Recovered: \x0309{6}\x03 (\x0309{7}\x03) | Active: \x0307{8}\x03 (\x0310{9}\x03 Mild) (\x0313{10}\x03 Serious) | Cases/1M: \x0307{11}\x03 | Deaths/1M: \x0304{12}\x03 | Updated: {13}".format( self.countries[list(self.countries)[0]]["ratio_serious"],
'Global', self.countries[list(self.countries)[0]][
'{:,}'.format(self.data['total:']['total_cases']), self.headers["countries"][8]
self.data['total:']['new_cases'], ],
self.data['total:']['total_deaths'], self.countries[list(self.countries)[0]][
self.data['total:']['new_deaths'], self.headers["countries"][9]
ratio_dead, ],
self.data['total:']['total_recovered'], self.countries["China"][self.headers["countries"][10]],
ratio_recovered, self.time_created(self.updated),
self.data['total:']['active'], )
mild, )
self.data['total:']['serious'],
self.data['total:']['cases_million'], @wrap([optional("text")])
self.data['total:']['deaths_million'], def top10(self, irc, msg, args, search):
self.time_created(updated))) """[usa|global]
else: Return the countries with the most confirmed cases. Valid options are USA or
reply = '' global. Returns global list if no option given.
"""
if not self.get_data():
irc.reply(
"Error retrieving data from https://www.worldometers.info/coronavirus/"
)
return
reply = ""
n = 1 n = 1
for country in self.data: if search:
if n > 10: search = search.strip().lower()
break else:
if self.data[country]['country'] and self.data[country]['rank'] == "#{0}".format(n): search = "global"
reply += " {0}: \x1F{1}\x1F (\x0307{2}\x03/\x0304{3}\x03),".format( if not search.startswith("us"):
self.data[country]['rank'], irc.reply(
self.data[country]['name'], "{0} | Updated: {1}".format(
'{:,}'.format(self.data[country]['total_cases']), ", ".join(self.top["countries"]), self.time_created(self.updated)
self.data[country]['total_deaths']) )
n += 1 )
reply = reply.strip().strip(',') else:
irc.reply("\x02{0} | Updated: {1}".format(reply, self.time_created(updated))) irc.reply(
"{0} | Updated: {1}".format(
", ".join(self.top["states"]), self.time_created(self.updated)
)
)
Class = Corona Class = Corona