async def about(self, ctx): embed = discord.Embed( description=utils.mkheader(), timestamp=utils.discord_timestamp(), color=utils.COLOR ) embed.set_author(name="Coronavirus COVID-19 Tracker", icon_url=ctx.me.avatar_url) embed.set_thumbnail(url=self.thumb) embed.add_field(name="Vote", value="[Click here](https://top.gg/bot/682946560417333283/vote)") embed.add_field(name="Invite Coronavirus COVID-19", value="[Click here](https://discordapp.com/oauth2/authorize?client_id=682946560417333283&scope=bot&permissions=313408)") embed.add_field(name="Discord Support", value="[Click here](https://discordapp.com/invite/wTxbQYb)") embed.add_field(name="Source code", value="[Click here](https://github.com/takitsu21/covid-19-tracker)") embed.add_field(name="Help command", value=f"`{ctx.prefix}help` or `@mention help`") embed.add_field(name="Prefix", value=f"`{ctx.prefix}` or `@mention`") nb_users = 0 channels = 0 for s in self.bot.guilds: nb_users += len(s.members) channels += len(s.channels) data = await utils.get(self.bot.http_session, "/all/world") embed.add_field(name="<:confirmed:688686089548202004> Confirmed", value=data["totalCases"]) embed.add_field(name="<:recov:688686059567185940> Recovered", value=data["totalRecovered"]) embed.add_field(name="<:_death:688686194917244928> Deaths", value=data["totalDeaths"]) embed.add_field(name="<:servers:693053697453850655> Servers", value=len(self.bot.guilds)) embed.add_field(name="<:users:693053423494365214> Members", value=nb_users) embed.add_field(name="<:hashtag:693056105076621342> Channels", value=channels) embed.add_field(name="<:stack:693054261512110091> Shards", value=f"{ctx.guild.shard_id + 1}/{self.bot.shard_count}") embed.set_footer(text="Made by Taki#0853 (WIP) " + utils.last_update(data['lastUpdate']), icon_url=ctx.me.avatar_url) await ctx.send(embed=embed)
async def info(self, ctx): DATA = utils.from_json(utils.DATA_PATH) if ctx.author.is_on_mobile(): header, text = utils.string_formatting(DATA) embed = discord.Embed(description=header + "\n\n" + text, color=utils.COLOR, timestamp=utils.discord_timestamp()) else: my_csv = utils.from_json(utils.CSV_DATA_PATH) embed = utils.make_tab_embed_all() c, r, d = utils.difference_on_update(my_csv, DATA) tot = DATA['total'] header = utils.mkheader( tot["confirmed"], c, tot["recovered"], utils.percentage(tot["confirmed"], tot["recovered"]), r, tot["deaths"], utils.percentage(tot["confirmed"], tot["deaths"]), d, False) embed.description = header embed.set_author( name=f"All countries affected by Coronavirus COVID-19", url="https://www.who.int/home", icon_url=self.author_thumb) embed.set_thumbnail(url=self.thumb) embed.set_footer(text=utils.last_update(utils.DATA_PATH), icon_url=ctx.guild.me.avatar_url) with open("stats.png", "rb") as p: img = discord.File(p, filename="stats.png") embed.set_image(url=f'attachment://stats.png') await ctx.send(file=img, embed=embed)
async def send_tracker(self): tracked = db.send_tracker() DATA = utils.from_json(utils.DATA_PATH) tot = DATA['total'] my_csv = utils.from_json(utils.CSV_DATA_PATH) c, r, d = utils.difference_on_update(my_csv, DATA) header = utils.mkheader( tot["confirmed"], c, tot["recovered"], utils.percentage(tot["confirmed"], tot["recovered"]), r, tot["deaths"], utils.percentage(tot["confirmed"], tot["deaths"]), d, False) for t in tracked: try: dm = self.bot.get_user(int(t["user_id"])) # embed = utils.make_tab_embed_all(is_country=True, params=t["country"].split(" ")) header, text = utils.string_formatting(DATA, t["country"].split(" ")) embed = discord.Embed(description=header + "\n\n" + text, color=utils.COLOR, timestamp=utils.discord_timestamp()) embed.set_author( name="Personal tracker for Coronavirus COVID-19", url="https://www.who.int/home", icon_url=self.author_thumb) embed.set_thumbnail(url=self.thumb) try: guild = self.bot.get_guild(int(t["guild_id"])) embed.set_footer(text=utils.last_update(utils.DATA_PATH), icon_url=guild.me.avatar_url) except: pass await dm.send(embed=embed) except: pass
async def daily(self, ctx: commands.Context, *country): embed = discord.Embed( description=utils.mkheader(), timestamp=dt.datetime.utcnow(), color=utils.COLOR ) try: if country: data_confirmed = await utils.get(self.bot.http_session, f"/daily/confirmed/{' '.join(country).lower()}") data_recovered = await utils.get(self.bot.http_session, f"/daily/recovered/{' '.join(country).lower()}") data_deaths = await utils.get(self.bot.http_session, f"/daily/deaths/{' '.join(country).lower()}") path = data_confirmed["iso2"] + "daily.png" embed.set_author( name=f"Coronavirus COVID-19 Daily cases graph - {data_confirmed['name']}", icon_url=f"https://raw.githubusercontent.com/hjnilsson/country-flags/master/png250px/{data_confirmed['iso2'].lower()}.png" ) else: data_confirmed = await utils.get(self.bot.http_session, f"/daily/confirmed/total") data_recovered = await utils.get(self.bot.http_session, f"/daily/recovered/total") data_deaths = await utils.get(self.bot.http_session, f"/daily/deaths/total") path = "daily_world.png" embed.set_author( name=f"Coronavirus COVID-19 Daily cases graph - World", icon_url=self.bot.author_thumb ) if not os.path.exists(path): await plot_bar_daily(path, data_confirmed, data_recovered, data_deaths) except Exception as e: traceback.print_exc() return await ctx.send("Please provide a valid country.") embed.add_field( name="<:confirmed:688686089548202004> Recent confirmed", value=f"{list(data_confirmed['daily'].keys())[-1]} : {list(data_confirmed['daily'].values())[-1]:,}" ) embed.add_field( name="<:recov:688686059567185940> Recent recovered", value=f"{list(data_recovered['daily'].keys())[-1]} : {list(data_recovered['daily'].values())[-1]:,}" ) embed.add_field( name="<:_death:688686194917244928> Recent deaths", value=f"{list(data_deaths['daily'].keys())[-1]} : {list(data_deaths['daily'].values())[-1]:,}", inline=False ) embed.set_thumbnail( url=self.bot.thumb + str(time.time()) ) with open(path, "rb") as p: img = discord.File(p, filename=path) embed.set_image(url=f'attachment://{path}') embed.set_footer( text="coronavirus.jessicoh.com/api/", icon_url=ctx.me.avatar_url ) await ctx.send(file=img, embed=embed)
async def country(self, ctx, *country): if not len(country): embed = discord.Embed( description= "No args provided, I can't tell you which country/region is affected if you won't tell me everything!", color=utils.COLOR, timestamp=utils.discord_timestamp()) else: DATA = utils.from_json(utils.DATA_PATH) is_mobile = ctx.author.is_on_mobile() if is_mobile: header, text = utils.string_formatting(DATA, country) embed = discord.Embed(description=header + "\n\n" + text, color=utils.COLOR, timestamp=utils.discord_timestamp()) else: try: embed = utils.make_tab_embed_all(is_country=True, params=country) c, r, d = utils.difference_on_update( utils.from_json(utils.CSV_DATA_PATH), DATA) tot = DATA['total'] header = utils.mkheader( tot["confirmed"], c, tot["recovered"], utils.percentage(tot["confirmed"], tot["recovered"]), r, tot["deaths"], utils.percentage(tot["confirmed"], tot["deaths"]), d, is_mobile) embed.description = header except: embed = discord.Embed( description= "Wrong country selected.\nViews information about multiple chosen country/region. You can either use autocompletion or country code. Valid country/region are listed in `c!info`.\nExample : `c!country fr germ it poland`", color=utils.COLOR, timestamp=utils.discord_timestamp()) embed.set_author(name="Country affected by COVID-19", url="https://www.who.int/home", icon_url=self.author_thumb) embed.set_thumbnail(url=self.thumb) embed.set_footer(text=utils.last_update(utils.DATA_PATH), icon_url=ctx.guild.me.avatar_url) await ctx.send(embed=embed)
async def track(self, ctx, *country): if not len(country): embed = discord.Embed( description= "No country provided. **`c!track <COUNTRY>`** work like **`c!country <COUNTRY>`** see `c!help`", color=utils.COLOR, timestamp=utils.discord_timestamp()) embed.set_author(name="c!track", icon_url=self.author_thumb) elif ''.join(country) == "disable": embed = discord.Embed( description= "If you want to reactivate the tracker : **`c!track <COUNTRY>`**", color=utils.COLOR, timestamp=utils.discord_timestamp()) embed.set_author(name="Tracker has been disabled!", icon_url=self.author_thumb) try: db.delete_tracker(str(ctx.author.id)) except: pass else: DATA = utils.from_json(utils.DATA_PATH) if ctx.author.is_on_mobile(): header, text = utils.string_formatting(DATA, country) embed = discord.Embed(description=header + "\n\n" + text, color=utils.COLOR, timestamp=utils.discord_timestamp()) if len(embed.description) > 0: try: db.insert_tracker(str(ctx.author.id), str(ctx.guild.id), ' '.join(country)) except IntegrityError: db.update_tracker(str(ctx.author.id), ' '.join(country)) embed.set_author( name= "Tracker has been set up! You can see your tracked list. Updates will be send in DM", icon_url=self.author_thumb) else: embed = discord.Embed( description="Wrong country selected.", color=utils.COLOR, timestamp=utils.discord_timestamp()) embed.set_author(name="c!track", icon_url=self.author_thumb) else: embed = utils.make_tab_embed_all(is_country=True, params=country) my_csv = utils.from_json(utils.CSV_DATA_PATH) c, r, d = utils.difference_on_update(my_csv, DATA) tot = DATA['total'] header = utils.mkheader( tot["confirmed"], c, tot["recovered"], utils.percentage(tot["confirmed"], tot["recovered"]), r, tot["deaths"], utils.percentage(tot["confirmed"], tot["deaths"]), d, False) embed.description = header if len(embed.fields[0].value) > 0: try: db.insert_tracker(str(ctx.author.id), str(ctx.guild.id), ' '.join(country)) except IntegrityError: db.update_tracker(str(ctx.author.id), ' '.join(country)) embed.set_author( name= "Tracker has been set up! You can see your tracked list. Updates will be send in DM", icon_url=self.author_thumb) else: embed = discord.Embed( description="Wrong country selected.", color=utils.COLOR, timestamp=utils.discord_timestamp()) embed.set_author(name="c!track", icon_url=self.author_thumb) embed.set_thumbnail(url=self.thumb) embed.set_footer(text=utils.last_update(utils.DATA_PATH), icon_url=ctx.guild.me.avatar_url) await ctx.send(embed=embed)
async def send_notifications(self): channels_id = await self.bot.to_send() total_history_confirmed = await utils.get(self.bot.http_session, "/history/confirmed/total/") total_history_recovered = await utils.get(self.bot.http_session, "/history/recovered/total/") total_history_deaths = await utils.get(self.bot.http_session, "/history/deaths/total/") history_confirmed = await utils.get(self.bot.http_session, "/history/confirmed/") history_recovered = await utils.get(self.bot.http_session, "/history/recovered/") history_deaths = await utils.get(self.bot.http_session, "/history/deaths/") all_data = await utils.get(self.bot.http_session, "/all/") for guild in channels_id: # go next, didn't match interval for this guild if self.interval_update % guild["next_update"] != 0: continue try: embed = discord.Embed(description=utils.mkheader(), timestamp=dt.datetime.utcnow(), color=utils.COLOR) path = utils.STATS_PATH if guild["country"].lower() in ("all", "world"): country = "World" else: country = guild["country"] path = (country.replace(" ", "_") + utils.STATS_PATH).lower() data = utils.get_country(all_data, country) if data is None or (data['newCases'] <= 0 and data['newDeaths'] <= 0): continue confirmed = data["totalCases"] recovered = data["totalRecovered"] deaths = data["totalDeaths"] active = data["activeCases"] embed.set_author( name= f"Coronavirus COVID-19 Notification - {data['country']}", icon_url= f"https://raw.githubusercontent.com/hjnilsson/country-flags/master/png250px/{data['iso2'].lower()}.png" ) embed.add_field( name="<:confirmed:688686089548202004> Confirmed", value=f"{confirmed:,}") embed.add_field( name="<:recov:688686059567185940> Recovered", value= f"{recovered:,} (**{utils.percentage(confirmed, recovered)}**)" ) embed.add_field( name="<:_death:688686194917244928> Deaths", value= f"{deaths:,} (**{utils.percentage(confirmed, deaths)}**)") embed.add_field( name="<:_calendar:692860616930623698> Today confirmed", value= f"+{data['newCases']:,} (**{utils.percentage(confirmed, data['newCases'])}**)" ) embed.add_field( name="<:_calendar:692860616930623698> Today deaths", value= f"+{data['newDeaths']:,} (**{utils.percentage(confirmed, data['newDeaths'])}**)" ) embed.add_field( name="<:bed_hospital:692857285499682878> Active", value= f"{active:,} (**{utils.percentage(confirmed, active)}**)") embed.add_field( name="<:critical:752228850091556914> Serious critical", value= f"{data['seriousCritical']:,} (**{utils.percentage(confirmed, data['seriousCritical'])}**)" ) if data["totalTests"]: percent_pop = "" if data["population"]: percent_pop = f"(**{utils.percentage(data['population'], data['totalTests'])}**)" embed.add_field( name="<:test:752252962532884520> Total test", value=f"{data['totalTests']:,} {percent_pop}") if not os.path.exists(path) and country != "World": await plot_csv( path, utils.get_country_history(history_confirmed, country), utils.get_country_history(history_recovered, country), utils.get_country_history(history_deaths, country)) elif not os.path.exists(path): await plot_csv(path, total_history_confirmed, total_history_recovered, total_history_deaths) with open(path, "rb") as p: img = discord.File(p, filename=path) embed.set_image(url=f'attachment://{path}') embed.set_thumbnail(url=self.bot.thumb + str(time.time())) channel = self.bot.get_channel(int(guild["channel_id"])) try: embed.set_footer( text="coronavirus.jessicoh.com/api/ | " + utils.last_update(all_data[0]['lastUpdate'])) except Exception as e: pass await channel.send(file=img, embed=embed) except Exception as e: pass logger.info("Notifications sent")
async def region_command(bot, ctx: Union[commands.Context, SlashContext], *params): if len(params): country, state = utils.parse_state_input(*params) try: if state == "all": history_confirmed = await utils.get( bot.http_session, f"/history/confirmed/{country}/regions") history_recovered = await utils.get( bot.http_session, f"/history/recovered/{country}/regions") history_deaths = await utils.get( bot.http_session, f"/history/deaths/{country}/regions") embeds = utils.region_format(history_confirmed, history_recovered, history_deaths) for i, _embed in enumerate(embeds): _embed.set_author(name=f"All regions in {country}", icon_url=bot.author_thumb) _embed.set_footer( text=f"coronavirus.jessicoh.com/api/ | Page {i + 1}", icon_url=bot.user.avatar_url) _embed.set_thumbnail(url=bot.thumb + str(time.time())) await ctx.send(embed=_embed) return else: path = state.lower().replace(" ", "_") + utils.STATS_PATH history_confirmed = await utils.get( bot.http_session, f"/history/confirmed/{country}/{state}") history_recovered = await utils.get( bot.http_session, f"/history/recovered/{country}/{state}") history_deaths = await utils.get( bot.http_session, f"/history/deaths/{country}/{state}") confirmed = list(history_confirmed["history"].values())[-1] deaths = list(history_deaths["history"].values())[-1] try: is_us = False recovered = list(history_recovered["history"].values())[-1] active = confirmed - (recovered + deaths) except: is_us = True recovered = 0 active = 0 if not os.path.exists(path): await plot_csv(path, history_confirmed, history_recovered, history_deaths, is_us=is_us) embed = discord.Embed(description=utils.mkheader(), timestamp=dt.datetime.utcnow(), color=utils.COLOR) embed.set_author( name=f"Coronavirus COVID-19 - {state.capitalize()}", icon_url=bot.author_thumb) embed.add_field( name="<:confirmed:688686089548202004> Confirmed", value=f"{confirmed:,}") embed.add_field( name="<:_death:688686194917244928> Deaths", value= f"{deaths:,} (**{utils.percentage(confirmed, deaths)}**)") if recovered: embed.add_field( name="<:recov:688686059567185940> Recovered", value= f"{recovered:,} (**{utils.percentage(confirmed, recovered)}**)" ) embed.add_field( name="<:bed_hospital:692857285499682878> Active", value= f"{active:,} (**{utils.percentage(confirmed, active)}**)" ) except Exception as e: logger.exception(e, exc_info=True) raise utils.RegionNotFound( "Region not found, it might be possible that the region isn't yet available in the data." ) else: return await ctx.send("No arguments provided.") with open(path, "rb") as p: img = discord.File(p, filename=path) embed.set_footer( text= f"coronavirus.jessicoh.com/api/ | {list(history_confirmed['history'].keys())[-1]}", icon_url=bot.user.avatar_url) embed.set_thumbnail(url=bot.thumb + str(time.time())) embed.set_image(url=f'attachment://{path}') await ctx.send(file=img, embed=embed)
async def stats_command(bot, ctx: Union[commands.Context, SlashContext], country): is_log = False graph_type = "Linear" embed = discord.Embed(description=utils.mkheader(), timestamp=dt.datetime.utcnow(), color=utils.COLOR) if len(country) == 1 and country[0].lower() == "log" or not len(country): data = await utils.get(bot.http_session, f"/all/world") splited = country if len(splited) == 1 and splited[0].lower() == "log": embed.set_author(name="Coronavirus COVID-19 logarithmic stats", icon_url=bot.author_thumb) is_log = True path = utils.STATS_LOG_PATH graph_type = "Logarithmic" elif not len(country): path = utils.STATS_PATH else: try: if splited[0].lower() == "log": is_log = True joined = ' '.join(country[1:]).lower() data = await utils.get(bot.http_session, f"/all/{joined}") path = data["iso2"].lower() + utils.STATS_LOG_PATH else: joined = ' '.join(country).lower() data = await utils.get(bot.http_session, f"/all/{joined}") path = data["iso2"].lower() + utils.STATS_PATH if not os.path.exists(path): history_confirmed = await utils.get( bot.http_session, f"/history/confirmed/{joined}") history_recovered = await utils.get( bot.http_session, f"/history/recovered/{joined}") history_deaths = await utils.get(bot.http_session, f"/history/deaths/{joined}") await plot_csv(path, history_confirmed, history_recovered, history_deaths, logarithmic=is_log) except Exception as e: path = utils.STATS_PATH confirmed = data["totalCases"] recovered = data["totalRecovered"] deaths = data["totalDeaths"] active = data["activeCases"] if data['iso2']: embed.set_author( name=f"Coronavirus COVID-19 {graph_type} graph - {data['country']}", icon_url= f"https://raw.githubusercontent.com/hjnilsson/country-flags/master/png250px/{data['iso2'].lower()}.png" ) else: embed.set_author( name=f"Coronavirus COVID-19 {graph_type} graph - {data['country']}", icon_url=bot.author_thumb) embed.add_field(name="<:confirmed:688686089548202004> Confirmed", value=f"{confirmed:,}") embed.add_field( name="<:recov:688686059567185940> Recovered", value=f"{recovered:,} (**{utils.percentage(confirmed, recovered)}**)") embed.add_field( name="<:_death:688686194917244928> Deaths", value=f"{deaths:,} (**{utils.percentage(confirmed, deaths)}**)") embed.add_field( name="<:_calendar:692860616930623698> Today confirmed", value= f"+{data['newCases']:,} (**{utils.percentage(confirmed, data['newCases'])}**)" ) embed.add_field( name="<:_calendar:692860616930623698> Today deaths", value= f"+{data['newDeaths']:,} (**{utils.percentage(confirmed, data['newDeaths'])}**)" ) embed.add_field( name="<:bed_hospital:692857285499682878> Active", value=f"{active:,} (**{utils.percentage(confirmed, active)}**)") embed.add_field( name="<:critical:752228850091556914> Serious critical", value= f"{data['seriousCritical']:,} (**{utils.percentage(confirmed, data['seriousCritical'])}**)" ) if data["totalTests"]: percent_pop = "" if data["population"]: percent_pop = f"(**{utils.percentage(data['population'], data['totalTests'])}**)" embed.add_field(name="<:test:752252962532884520> Total test", value=f"{data['totalTests']:,} {percent_pop}") embed.add_field(name="<:population:768055030813032499> Population", value=f"{data['population']:,}") if not os.path.exists(path): history_confirmed = await utils.get(bot.http_session, f"/history/confirmed/total") history_recovered = await utils.get(bot.http_session, f"/history/recovered/total") history_deaths = await utils.get(bot.http_session, f"/history/deaths/total") await plot_csv(path, history_confirmed, history_recovered, history_deaths, logarithmic=is_log) with open(path, "rb") as p: img = discord.File(p, filename=path) embed.set_footer(text="coronavirus.jessicoh.com/api/ | " + utils.last_update(data["lastUpdate"]), icon_url=bot.user.avatar_url) embed.set_thumbnail(url=bot.thumb + str(time.time())) embed.set_image(url=f'attachment://{path}') await ctx.send(file=img, embed=embed)