Skip to content

Commit

Permalink
numerous changes, fixes and improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
apex2504 committed Mar 30, 2020
1 parent a232807 commit 346dae0
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 48 deletions.
55 changes: 37 additions & 18 deletions corona_api/client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import datetime
import aiohttp
from .statistics import GlobalStatistics, CountryStatistics, StateStatistics, CountryHistory, HistoryEntry
from .statistics import GlobalStatistics, CountryStatistics, StateStatistics, HistoricalStatistics, HistoryEntry

class APIerror(Exception):
pass
Expand Down Expand Up @@ -39,7 +39,8 @@ async def all(self):
cases = global_data.get("cases", 0)
deaths = global_data.get("deaths", 0)
recoveries = global_data.get("recovered", 0)
updated_epoch = global_data.get("updated", None)
updated_epoch = global_data.get("updated", 0)
active = global_data.get("active", cases-deaths-recoveries)
updated = datetime.fromtimestamp(updated_epoch/1000.0)

today_cases = 0
Expand All @@ -58,6 +59,7 @@ async def all(self):
today_cases,
today_deaths,
total_critical,
active,
updated
)

Expand All @@ -79,7 +81,11 @@ async def get_country_data(self, country):
today_cases = country_stats.get("todayCases", 0)
today_deaths = country_stats.get("todayDeaths", 0)
total_critical = country_stats.get("critical", 0)
active = country_stats.get("active", 0)
cases_per_million = country_stats.get("casesPerOneMillion", 0)
deaths_per_million = country_stats.get("deathsPerOneMillion", 0)
updated_epoch = country_stats.get("updated", 0)
updated = datetime.fromtimestamp(updated_epoch/1000.0)
flag = country_stats["countryInfo"].get("flag", None)

return CountryStatistics(
Expand All @@ -90,7 +96,10 @@ async def get_country_data(self, country):
today_cases,
today_deaths,
total_critical,
active,
cases_per_million,
deaths_per_million,
updated,
flag
)

Expand All @@ -112,7 +121,6 @@ async def get_state_info(self, state):
state_name = state_info.get("state", "Null")
total_state_cases = state_info.get("cases", 0)
total_state_deaths = state_info.get("deaths", 0)
total_state_recoveries = state_info.get("recovered", 0)
today_cases = state_info.get("todayCases", 0)
today_deaths = state_info.get("todayDeaths", 0)
active = state_info.get("active", 0)
Expand All @@ -121,16 +129,16 @@ async def get_state_info(self, state):
state_name,
total_state_cases,
total_state_deaths,
total_state_recoveries,
today_cases,
today_deaths,
active
)


async def get_history(self, country):
async def get_history(self, country="all"):
"""
Get historical data for a specific country.
Get historical data for a specific country or globally.
Defaults to 'all' in order to get global data. This can be overridden by the client.
"""
async with self.session.get(self.historical.format(country)) as resp:
if not resp.status == 200:
Expand All @@ -140,19 +148,27 @@ async def get_history(self, country):

case_history = []
death_history = []
#recovery_history = []
recovery_history = []

name = historical_stats["country"]

if not historical_stats["timeline"]["cases"]:
raise APIerror('Couldn\'t get stats for given country')

for date in list(historical_stats["timeline"]["cases"].keys()): #pass on all historical data. let the client decide how much of it they want
case_history.append(HistoryEntry(date, historical_stats["timeline"]["cases"][date]))
death_history.append(HistoryEntry(date, historical_stats["timeline"]["deaths"][date]))
#recovery_history.append(HistoryEntry(date, historical_stats["timeline"]["recovered"][date])) #history v2 no longer includes recovery data

return CountryHistory(name, case_history, death_history) #, recovery_history)
name = historical_stats.get("country", "Global")

if "timeline" not in historical_stats:
d = historical_stats

else:
d = historical_stats["timeline"]

for date in list(d["cases"].keys()): #pass on all historical data. let the client decide how much of it they want
case_history.append(HistoryEntry(date, d["cases"][date]))
death_history.append(HistoryEntry(date, d["deaths"][date]))
recovery_history.append(HistoryEntry(date, d["recovered"][date]))

return HistoricalStatistics(
name,
case_history,
death_history,
recovery_history
)


async def get_sorted_data(self, sort):
Expand Down Expand Up @@ -185,7 +201,10 @@ async def get_sorted_data(self, sort):
country["todayCases"],
country["todayDeaths"],
country["critical"],
country["active"],
country["casesPerOneMillion"],
country["deathsPerOneMillion"],
datetime.fromtimestamp(country["updated"]/1000.0),
country["countryInfo"]["flag"]
)
sorted_data.append(c)
Expand Down
17 changes: 10 additions & 7 deletions corona_api/statistics.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,36 @@
class GlobalStatistics:
def __init__(self, cases, deaths, recoveries, today_cases, today_deaths, total_critical, updated):
def __init__(self, cases, deaths, recoveries, today_cases, today_deaths, total_critical, active, updated):
self.cases = cases
self.deaths = deaths
self.recoveries = recoveries
self.today_cases = today_cases
self.today_deaths = today_deaths
self.critical = total_critical
self.active = active
self.updated = updated


class CountryStatistics:
def __init__(self, name, cases, deaths, recoveries, today_cases, today_deaths, critical, cases_per_million, flag):
def __init__(self, name, cases, deaths, recoveries, today_cases, today_deaths, critical, active, cases_per_million, deaths_per_million, updated, flag):
self.name = name
self.cases = cases
self.deaths = deaths
self.recoveries = recoveries
self.today_cases = today_cases
self.today_deaths = today_deaths
self.critical = critical
self.active = active
self.cases_per_million = cases_per_million
self.deaths_per_million = deaths_per_million
self.updated = updated
self.flag = flag


class StateStatistics:
def __init__(self, name, cases, deaths, recoveries, today_cases, today_deaths, active):
def __init__(self, name, cases, deaths, today_cases, today_deaths, active):
self.name = name
self.cases = cases
self.deaths = deaths
self.recoveries = recoveries
self.today_cases = today_cases
self.today_deaths = today_deaths
self.active = active
Expand All @@ -39,9 +42,9 @@ def __init__(self, date, value):
self.value = value


class CountryHistory:
def __init__(self, name, case_history, death_history): # , recovery_history):
class HistoricalStatistics:
def __init__(self, name, case_history, death_history, recovery_history):
self.name = name
self.case_history = case_history
self.death_history = death_history
#self.recovery_history = recovery_history
self.recovery_history = recovery_history
62 changes: 40 additions & 22 deletions examples/discord_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,34 @@
from discord.ext import commands
import corona_api


def generate_base_embed(embed, data):
embed.add_field(name="Total cases", value = corona_api.format_number(data.cases))
embed.add_field(name="Cases today", value = corona_api.format_number(data.today_cases))
embed.add_field(name="Total deaths", value = corona_api.format_number(data.deaths))
embed.add_field(name="Deaths today", value = corona_api.format_number(data.today_deaths))

def generate_all_embed(embed, data):
embed.add_field(name="Total recoveries", value = corona_api.format_number(data.recoveries))
embed.add_field(name="Total critical cases", value = corona_api.format_number(data.critical))
embed.add_field(name="Active cases", value = corona_api.format_number(data.active))
embed.add_field(name="Last updated", value = corona_api.format_date(data.updated))

def generate_country_embed(embed, data):
embed.add_field(name="Total recoveries", value = corona_api.format_number(data.recoveries))
embed.add_field(name="Total critical cases", value = corona_api.format_number(data.critical))
embed.add_field(name="Active cases", value = corona_api.format_number(data.active))
embed.add_field(name="Cases per million people", value = corona_api.format_number(data.cases_per_million))
embed.add_field(name="Deaths per million people", value = corona_api.format_number(data.deaths_per_million))
embed.add_field(name="Last updated", value = corona_api.format_date(data.updated))
embed.description = "**Country: {}**".format(data.name)
embed.set_thumbnail(url=data.flag)

def generate_state_embed(embed, data):
embed.add_field(name="Active cases", value = corona_api.format_number(data.active))
embed.description = "**State: {}**".format(data.name)


class Coronavirus(commands.Cog):

"""
Expand Down Expand Up @@ -51,32 +79,22 @@ async def coronavirus(self, ctx, country=None, *, state=None):
embed = discord.Embed(title="Coronavirus (COVID-19) stats", color=65280)
embed.set_footer(text="These stats are what has been officially confirmed. It is possible that real figures are different.")

embed.add_field(name="Total cases", value = corona_api.format_number(data.cases))
embed.add_field(name="Cases today", value = corona_api.format_number(data.today_cases))
embed.add_field(name="Total deaths", value = corona_api.format_number(data.deaths))
embed.add_field(name="Deaths today", value = corona_api.format_number(data.today_deaths))
embed.add_field(name="Total recoveries", value = corona_api.format_number(data.recoveries))

if not isinstance(data, corona_api.StateStatistics):
embed.add_field(name="Total critical cases", value = corona_api.format_number(data.critical))
generate_base_embed(embed, data)

if isinstance(data, corona_api.GlobalStatistics):
embed.add_field(name="Last updated", value = corona_api.format_date(data.updated))
generate_all_embed(embed, data)

elif isinstance(data, corona_api.CountryStatistics):
embed.add_field(name="Cases per million people", value = corona_api.format_number(data.cases_per_million))
embed.description = "**Country: {}**".format(data.name)
embed.set_thumbnail(url=data.flag)
generate_country_embed(embed, data)

else:
embed.add_field(name="Active cases", value=corona_api.format_number(data.active))
embed.description = "**State: {}**".format(data.name)
elif isinstance(data, corona_api.StateStatistics):
generate_state_embed(embed, data)

await ctx.send(embed=embed)


@commands.command(name="coronavirushistory", aliases=["cvhistory", "cvh", "coronahistory"])
async def coronavirushistory(self, ctx, *, country):
async def coronavirushistory(self, ctx, *, country="all"):

"""
Get the history for Coronavirus (COVID-19) for a specified country.
Expand All @@ -99,11 +117,11 @@ async def coronavirushistory(self, ctx, *, country):

case_history_value = ''
death_history_value = ''
#recovery_history_value = ''
recovery_history_value = ''

last_case_fortnight = data.case_history[-14:]
last_death_fortnight = data.death_history[-14:]
#last_recovered_fortnight = data.recovery_history[-14:]
last_recovered_fortnight = data.recovery_history[-14:]

for i in range(14):
case_history_value = "{}\n**{}:** \
Expand All @@ -112,13 +130,13 @@ async def coronavirushistory(self, ctx, *, country):
death_history_value = "{}\n**{}:** \
{}".format(death_history_value, last_death_fortnight[i].date,
corona_api.format_number(last_death_fortnight[i].value) if last_death_fortnight[i].value is not None else 'Unknown')
#recovery_history_value = "{}\n**{}:** \
# {}".format(recovery_history_value, last_recovered_fortnight[i].date,
# corona_api.format_number(last_recovered_fortnight[i].value) if last_recovered_fortnight[i].value is not None else 'Unknown')
recovery_history_value = "{}\n**{}:** \
{}".format(recovery_history_value, last_recovered_fortnight[i].date,
corona_api.format_number(last_recovered_fortnight[i].value) if last_recovered_fortnight[i].value is not None else 'Unknown')

embed.add_field(name="Number of cases", value=case_history_value)
embed.add_field(name="Number of deaths", value=death_history_value)
#embed.add_field(name="Number of recoveries",value=recovery_history_value)
embed.add_field(name="Number of recoveries",value=recovery_history_value)

await ctx.send(embed=embed)

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
setup(
name = 'corona_api',
packages = ['corona_api'],
version = '0.4.7',
version = '0.5.0',
license='MIT',
description = 'An asynchronous wrapper for the corona.lmao.ninja API written in Python.',
long_description= long_desc,
Expand Down

0 comments on commit 346dae0

Please sign in to comment.