Exemple #1
0
 async def region(self, ctx, *params):
     if len(params):
         if ctx.author.is_on_mobile():
             embed = utils.region_mobile(*params)
             if len(embed.description):
                 pass
             else:
                 embed = discord.Embed(
                     description=
                     "Wrong province/state or country, see `c!help`.",
                     color=utils.COLOR,
                     timestamp=utils.discord_timestamp())
         else:
             embed = utils.make_tab_embed_region(*params)
             if len(embed.fields[0].value) > 0:
                 pass
             else:
                 embed = discord.Embed(
                     description=
                     "Wrong province/state or country, see `c!help`.",
                     color=utils.COLOR,
                     timestamp=utils.discord_timestamp())
     else:
         embed = discord.Embed(
             description=
             "Missing args, see `c!help`.\nSupported countries (**China, Canada, United States, Australia, Cruise Ship**).",
             color=utils.COLOR,
             timestamp=utils.discord_timestamp())
     embed.set_author(name="Coronavirus COVID-19 (State/Province)",
                      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)
Exemple #2
0
async def info_command(bot, ctx: Union[commands.Context, SlashContext]):
    data = await utils.get(bot.http_session, "/all")

    text = utils.string_formatting(data)
    embed = discord.Embed(description=text,
                          color=utils.COLOR,
                          timestamp=utils.discord_timestamp())

    embed.set_author(name=f"All countries affected by Coronavirus COVID-19",
                     url="https://www.who.int/home",
                     icon_url=bot.author_thumb)
    embed.set_thumbnail(url=bot.thumb + str(time.time()))
    embed.set_footer(text="coronavirus.jessicoh.com/api | " +
                     utils.last_update(data[0]["lastUpdate"]),
                     icon_url=bot.user.avatar_url)

    if not os.path.exists(utils.STATS_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(utils.STATS_PATH, history_confirmed, history_recovered,
                       history_deaths)
    with open(utils.STATS_PATH, "rb") as p:
        img = discord.File(p, filename=utils.STATS_PATH)
    embed.set_image(url=f'attachment://{utils.STATS_PATH}')
    await ctx.send(file=img, embed=embed)
Exemple #3
0
 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)
         header, text = utils.string_formatting(
                 DATA,
                 country
             )
         if len(text) > 0:
             embed = discord.Embed(
                 description=header + "\n" + text,
                 color=utils.COLOR,
                 timestamp=utils.discord_timestamp()
             )
         else:
             embed = discord.Embed(
                 description="Wrong country selected or this country/region is not affected by Coronavirus COVID-19",
                 color=utils.COLOR,
                 timestamp=utils.discord_timestamp()
             )
     embed.set_author(name="Current Region/Country 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
     )
     await ctx.send(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
Exemple #5
0
 async def news(self, ctx):
     news = await utils.from_json(utils.NEWS_PATH)
     embed = discord.Embed(
         title=
         ":newspaper: Recent news about Coronavirus COVID-19 :newspaper:",
         timestamp=utils.discord_timestamp(),
         color=utils.COLOR)
     sources = []
     length = 0
     max_size = 5800
     for n in news["articles"]:
         source = n["source"]["name"]
         if source not in sources:
             sources.append(source)
         else:
             continue
         try:
             length += len(
                 f"🞄 **{source}** : {n['title']} {n['description']}  [Link]({n['url']})"
             )
             if length >= max_size:
                 break
             embed.add_field(
                 name=f"🞄 **{source}** : {n['title']}",
                 value=f"{n['description']}  [Link]({n['url']})",
                 inline=False)
         except discord.errors.HTTPException:
             break
     embed.set_thumbnail(
         url="https://avatars2.githubusercontent.com/u/32527401?s=400&v=4")
     embed.set_footer(text=utils.last_update(utils.NEWS_PATH) +
                      " | newsapi.org",
                      icon_url=ctx.guild.me.avatar_url)
     await ctx.send(embed=embed)
Exemple #6
0
 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)
Exemple #7
0
 async def stats(self, ctx):
     DATA = utils.from_json(utils.DATA_PATH)
     my_csv = utils.from_json(utils.CSV_DATA_PATH)
     t, r, c = utils.difference_on_update(my_csv, DATA)
     confirmed = DATA['total']['confirmed']
     recovered = DATA['total']['recovered']
     deaths = DATA['total']['deaths']
     embed = discord.Embed(
         description="[+**CURRENT_UPDATE-MORNING_UPDATE**]",
         timestamp=utils.discord_timestamp(),
         color=utils.COLOR,
     )
     embed.set_author(name="Coronavirus COVID-19 Stats",
                      icon_url=self.author_thumb)
     embed.set_thumbnail(url=self.thumb)
     embed.add_field(name="<:confirmed:688686089548202004> Confirmed",
                     value=f"**{confirmed}** [+**{t}**]",
                     inline=False)
     embed.add_field(
         name="<:recov:688686059567185940> Recovered",
         value=
         f"**{recovered}** ({utils.percentage(confirmed, recovered)}) [+**{r}**]",
         inline=False)
     embed.add_field(
         name="<:_death:688686194917244928> Deaths",
         value=
         f"**{deaths}** ({utils.percentage(confirmed, deaths)}) [+**{c}**]",
         inline=False)
     embed.set_footer(text=utils.last_update("stats.png"),
                      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)
Exemple #8
0
    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)
Exemple #9
0
async def list_countries_command(bot, ctx: Union[commands.Context,
                                                 SlashContext]):
    text = ""
    i = 1
    data = await utils.get(bot.http_session, "/all")
    text = ""
    overflow_text = ""
    embeds = []
    for c in data:
        overflow_text += c["country"] + ", "
        if len(overflow_text) >= utils.DISCORD_LIMIT:
            embed = discord.Embed(description=text.rstrip(", "),
                                  color=utils.COLOR,
                                  timestamp=utils.discord_timestamp())
            text = overflow_text
            overflow_text = ""
            embeds.append(embed)
        text = overflow_text

    if text:
        embed = discord.Embed(description=text.rstrip(", "),
                              color=utils.COLOR,
                              timestamp=utils.discord_timestamp())

        embeds.append(embed)

    for i, _embed in enumerate(embeds):
        _embed.set_author(
            name=
            f"All countries affected by Coronavirus COVID-19 - Page {i + 1}",
            icon_url=bot.author_thumb)
        _embed.set_footer(text=utils.last_update(data[0]["lastUpdate"]),
                          icon_url=bot.user.avatar_url)
        _embed.set_thumbnail(url=bot.thumb + str(time.time()))
        await ctx.send(embed=_embed)
Exemple #10
0
    async def notification(self, ctx, state=None):
        if state is None:
            embed = discord.Embed(
                title="c!notification",
                description="c!nofitication <enable | disable>")
        elif state.lower() == "enable":
            try:
                db.insert_notif(str(ctx.guild.id), str(ctx.channel.id))
            except IntegrityError:
                db.update_notif(str(ctx.guild.id), str(ctx.channel.id))
            embed = discord.Embed(
                title="Notifications successfully enabled",
                description=
                "You will receive a notification in this channel on data update."
            )
        elif state.lower() == "disable":
            db.delete_notif(str(ctx.guild.id))
            embed = discord.Embed(
                title="Notifications successfully disabled",
                description="Notifications are now interrupted in this channel."
            )

        embed.color = utils.COLOR
        embed.timestamp = utils.discord_timestamp()
        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)
Exemple #11
0
 async def notif_perm_err(self, ctx, error):
     embed = discord.Embed(title="c!notification",
                           description=f"Something went wrong! :/ {error}")
     embed.color = utils.COLOR
     embed.timestamp = utils.discord_timestamp()
     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)
Exemple #12
0
    async def on_guild_join(self, guild: discord.Guild):
        await self.wait_until_ready()
        chan_logger = self.get_channel(692815717078270052)
        try:
            general = find(lambda x: x.name == "general", guild.text_channels)
            if general and general.permissions_for(guild.me).send_messages:
                embed = discord.Embed(
                        description="You can support me on <:kofi:693473314433138718>[Kofi](https://ko-fi.com/takitsu) and vote on [top.gg](https://top.gg/bot/682946560417333283/vote) for the bot. <:github:693519776022003742> [Source code](https://github.com/takitsu21/covid-19-tracker)",
                        timestamp=utils.discord_timestamp(),
                        color=utils.COLOR
                    )
                embed.set_author(name="Coronavirus COVID-19 Tracker", icon_url=guild.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="c!help")
                embed.add_field(name="Prefix",value="c!")
                nb_users = 0
                channels = 0
                for s in self.guilds:
                    nb_users += len(s.members)
                    channels += len(s.channels)
                embed.add_field(name="<:confirmed:688686089548202004> Confirmed", value=self._data["total"]["confirmed"])
                embed.add_field(name="<:recov:688686059567185940> Recovered", value=self._data["total"]["recovered"])
                embed.add_field(name="<:_death:688686194917244928> Deaths", value=self._data["total"]["deaths"])
                embed.add_field(name="<:servers:693053697453850655> Servers", value=len(self.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(utils.DATA_PATH),
                                icon_url=guild.me.avatar_url)
                await general.send(embed=embed)
        except:
            pass

        embed = discord.Embed(
            title="Bot added to " + guild.name,
            timestamp=datetime.datetime.utcnow(),
            color=utils.COLOR
        )
        embed.add_field(
            name="<:users:693053423494365214> Members",
            value=len(guild.members)
        )
        embed.add_field(
            name="<:hashtag:693056105076621342> Channels",
            value=len(guild.channels)
        )
        embed.set_thumbnail(url=guild.icon_url)
        embed.set_footer(icon_url=guild.me.avatar_url)
        await chan_logger.send(embed=embed)
Exemple #13
0
    async def about(self, ctx):
        DATA = self.bot._data
        embed = discord.Embed(
            description=
            "You can support me on <:kofi:693473314433138718>[Kofi](https://ko-fi.com/takitsu) and vote on [top.gg](https://top.gg/bot/682946560417333283/vote) for the bot. <:github:693519776022003742> [Source code](https://github.com/takitsu21/covid-19-tracker)\n[World Health Organization advices](https://www.who.int/emergencies/diseases/novel-coronavirus-2019/advice-for-public)",
            timestamp=utils.discord_timestamp(),
            color=utils.COLOR)
        embed.set_author(name="Coronavirus COVID-19 Tracker",
                         icon_url=ctx.guild.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="`c!help` or `@mention help`")
        embed.add_field(name="Prefix", value="`c!` or `@mention`")

        nb_users = 0
        channels = 0
        for s in self.bot.guilds:
            nb_users += len(s.members)
            channels += len(s.channels)
        embed.add_field(name="<:confirmed:688686089548202004> Confirmed",
                        value=DATA["total"]["confirmed"])
        embed.add_field(name="<:recov:688686059567185940> Recovered",
                        value=DATA["total"]["recovered"])
        embed.add_field(name="<:_death:688686194917244928> Deaths",
                        value=DATA["total"]["deaths"])
        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(utils.DATA_PATH),
                         icon_url=ctx.guild.me.avatar_url)
        await ctx.send(embed=embed)
Exemple #14
0
 async def notif_perm_err(self, ctx, error):
     embed = discord.Embed(
             title="c!notification",
             description="You are missing permissions (Administrator required)"
         )
     embed.color = utils.COLOR
     embed.timestamp = utils.discord_timestamp()
     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)
Exemple #15
0
    async def list_countries(self, ctx):
        text = ""
        i = 1
        for c in self.bot._data["sorted"]:
            if c["statistics"]["confirmed"] > 0:
                length = len(text + c["country"]["name"] + ", ")

                if length >= utils.DISCORD_LIMIT:
                    embed = discord.Embed(description=text.rstrip(","),
                                          color=utils.COLOR,
                                          timestamp=utils.discord_timestamp())
                    embed.set_author(
                        name=
                        f"All countries affected by Coronavirus COVID-19 - Page {i}",
                        icon_url=self.bot.author_thumb)
                    i += 1
                    text = ""
                    embed.set_footer(text=utils.last_update(utils.DATA_PATH),
                                     icon_url=ctx.guild.me.avatar_url)
                    embed.set_thumbnail(url=self.thumb + str(uuid.uuid4()))
                    await ctx.send(embed=embed)

                try:
                    text += c["country"]["name"] + ", "
                except:
                    pass

        if len(text):
            embed = discord.Embed(description=text.rstrip(","),
                                  color=utils.COLOR,
                                  timestamp=utils.discord_timestamp())
            embed.set_author(
                name=
                f"All countries affected by Coronavirus COVID-19 - Page {i}",
                icon_url=self.bot.author_thumb)
            embed.set_footer(text=utils.last_update(utils.DATA_PATH),
                             icon_url=ctx.guild.me.avatar_url)
            embed.set_thumbnail(url=self.thumb + str(uuid.uuid4()))
            await ctx.send(embed=embed)
Exemple #16
0
    async def region(self, ctx, *params):
        if len(params):
            country, state = utils.parse_state_input(*params)
            header, text = utils.region_format(self.bot._data, country, state)
            embed = discord.Embed(color=utils.COLOR,
                                  timestamp=dt.datetime.utcnow())
            if len(text):
                embed.description = header + text
            else:
                try:

                    available_states = ""
                    for c in utils.get_states(self.bot._data, country):
                        available_states += c["name"] + "\n"
                    if len(available_states):
                        embed = discord.Embed(
                            description=
                            f"**Here is a list of available province/state for this country:**\n{available_states}",
                            color=utils.COLOR,
                            timestamp=utils.discord_timestamp())
                    else:
                        embed = discord.Embed(
                            description=
                            "Wrong province/state or country, see `c!help`.",
                            color=utils.COLOR,
                            timestamp=utils.discord_timestamp())
                except Exception as e:
                    embed = discord.Embed(
                        description=
                        "Wrong province/state or country, see `c!help`.",
                        color=utils.COLOR,
                        timestamp=utils.discord_timestamp())
        else:
            embed = discord.Embed(
                description=
                "Missing args, see `c!help`.\nSupported countries (**try your region if it doesn't work that mean this region is not yet supported**).",
                color=utils.COLOR,
                timestamp=utils.discord_timestamp())
        embed.set_author(name="Coronavirus COVID-19 (State/Province)",
                         icon_url=self.bot.author_thumb)

        embed.set_footer(text=utils.last_update(utils.DATA_PATH),
                         icon_url=ctx.guild.me.avatar_url)
        try:
            embed.set_thumbnail(url=stats["country"]["map"])
        except:
            embed.set_thumbnail(url=self.thumb + str(uuid.uuid4()))
        try:
            await ctx.send(file=img, embed=embed)
        except:
            await ctx.send(embed=embed)
 async def send_notifications(self, channels_id, old_data, new_data):
     # __, text = utils.string_formatting(new_data)
     confirmed = new_data['total']['confirmed']
     recovered = new_data['total']['recovered']
     deaths = new_data['total']['deaths']
     t, r, c = utils.difference_on_update(old_data, new_data)
     # header = f"""Total Confirmed **{tot['confirmed']}** [+{c}]
     # Total Recovered **{tot['recovered']}** ({utils.percentage(tot['confirmed'], tot['recovered'])}) [+{r}]
     # Total Deaths **{tot['deaths']}** ({utils.percentage(tot['confirmed'], tot['deaths'])}) [+{d}]\n"""
     embed = discord.Embed(
         # description=header + "\n" + text,
         description=
         "Below you can find the new stats for the past hour. (Data are updated ~ every 1 hour)",
         color=utils.COLOR,
         timestamp=utils.discord_timestamp())
     embed.set_author(name="Notification Coronavirus COVID-19",
                      url="https://www.who.int/home",
                      icon_url=self.author_thumb)
     embed.set_thumbnail(url=self.thumb)
     embed.add_field(name="Confirmed",
                     value=f"**{confirmed}** [+**{t}**]",
                     inline=False)
     embed.add_field(
         name="Recovered",
         value=
         f"**{recovered}** ({utils.percentage(confirmed, recovered)}) [+**{r}**]",
         inline=False)
     embed.add_field(
         name="Deaths",
         value=
         f"**{deaths}** ({utils.percentage(confirmed, deaths)}) [+**{c}**]",
         inline=False)
     for _ in channels_id:
         try:
             with open("stats.png", "rb") as p:
                 img = discord.File(p, filename="stats.png")
             embed.set_image(url=f'attachment://stats.png')
             channel = self.bot.get_channel(int(_["channel_id"]))
             try:
                 guild = self.bot.get_guild(int(_["guild_id"]))
                 embed.set_footer(text=utils.last_update(utils.DATA_PATH),
                                  icon_url=guild.me.avatar_url)
             except:
                 pass
             await channel.send(file=img, embed=embed)
         except Exception as e:
             pass
     logger.info("Notifications sended")
Exemple #18
0
    async def track(self, ctx, *country):
        if not len(country):
            embed = discord.Embed(
                description=
                f"No country provided. **`{ctx.prefix}track <COUNTRY>`** work like **`{ctx.prefix}country <COUNTRY>`** see `{ctx.prefix}help`",
                color=utils.COLOR,
                timestamp=utils.discord_timestamp())
            embed.set_author(name=f"{ctx.prefix}track",
                             icon_url=self.bot.author_thumb)
        elif ''.join(country) == "disable":
            embed = discord.Embed(
                description=
                f"If you want to reactivate the tracker : **`{ctx.prefix}track <COUNTRY>`**",
                color=utils.COLOR,
                timestamp=utils.discord_timestamp())
            embed.set_author(name="Tracker has been disabled!",
                             icon_url=self.bot.author_thumb)
            try:
                db.delete_tracker(str(ctx.author.id))
            except:
                pass
        else:
            header, text = utils.string_formatting(self.bot._data, country)
            embed = discord.Embed(description=header + "\n\n" + text,
                                  color=utils.COLOR,
                                  timestamp=utils.discord_timestamp())
            if len(text) > 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.bot.author_thumb)
            else:
                embed = discord.Embed(description="Wrong country selected.",
                                      color=utils.COLOR,
                                      timestamp=utils.discord_timestamp())
                embed.set_author(name=f"{ctx.prefix}track",
                                 icon_url=self.bot.author_thumb)
        embed.set_thumbnail(url=self.bot.thumb + str(time.time()))
        embed.set_footer(text=utils.last_update(utils.DATA_PATH),
                         icon_url=ctx.me.avatar_url)
        await ctx.send(embed=embed)
Exemple #19
0
 async def send_notifications(self, old_data, new_data):
     confirmed = new_data['total']['confirmed']
     recovered = new_data['total']['recovered']
     deaths = new_data['total']['deaths']
     channels_id = db.to_send()
     t, r, c = utils.difference_on_update(old_data, new_data)
     embed = discord.Embed(
         description=
         "Below you can find the new stats for the past hour. (Data are updated ~ every 1 hour)\n[+**CURRENT_UPDATE-LAST_HOUR_UPDATE**]",
         color=utils.COLOR,
         timestamp=utils.discord_timestamp())
     embed.set_author(name="Notification Coronavirus COVID-19",
                      url="https://www.who.int/home",
                      icon_url=self.author_thumb)
     embed.set_thumbnail(url=self.thumb)
     embed.add_field(name="<:confirmed:688686089548202004> Confirmed",
                     value=f"**{confirmed}** [+**{t}**]",
                     inline=False)
     embed.add_field(
         name="<:recov:688686059567185940> Recovered",
         value=
         f"**{recovered}** ({utils.percentage(confirmed, recovered)}) [+**{r}**]",
         inline=False)
     embed.add_field(
         name="<:_death:688686194917244928> Deaths",
         value=
         f"**{deaths}** ({utils.percentage(confirmed, deaths)}) [+**{c}**]",
         inline=False)
     if t or c or r:
         for _ in channels_id:
             try:
                 with open("stats.png", "rb") as p:
                     img = discord.File(p, filename="stats.png")
                 embed.set_image(url=f'attachment://stats.png')
                 channel = self.bot.get_channel(int(_["channel_id"]))
                 try:
                     guild = self.bot.get_guild(int(_["guild_id"]))
                     embed.set_footer(text=utils.last_update(
                         utils.DATA_PATH),
                                      icon_url=guild.me.avatar_url)
                 except:
                     pass
                 await channel.send(file=img, embed=embed)
             except Exception as e:
                 pass
     logger.info("Notifications sended")
Exemple #20
0
 async def about(self, ctx):
     DATA = utils.from_json(utils.DATA_PATH)
     embed = discord.Embed(
         description=
         "[Wold Health Organization advices](https://www.who.int/emergencies/diseases/novel-coronavirus-2019/advice-for-public)",
         timestamp=utils.discord_timestamp(),
         color=utils.COLOR)
     embed.set_author(name="Coronavirus COVID-19 Tracker",
                      icon_url=ctx.guild.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="c!help")
     embed.add_field(name="Prefix", value="c!")
     embed.add_field(
         name="Donate",
         value=
         "[Patreon](https://www.patreon.com/takitsu)\nBuy me a [Ko-fi](https://ko-fi.com/takitsu)"
     )
     nb_users = 0
     for s in self.bot.guilds:
         nb_users += len(s.members)
     embed.add_field(name="Confirmed", value=DATA["total"]["confirmed"])
     embed.add_field(name="Recovered", value=DATA["total"]["recovered"])
     embed.add_field(name="Deaths", value=DATA["total"]["deaths"])
     embed.add_field(name="Servers", value=len(self.bot.guilds))
     embed.add_field(name="Members", value=nb_users)
     embed.set_footer(text="Made by Taki#0853 (WIP) " +
                      utils.last_update(utils.DATA_PATH),
                      icon_url=ctx.guild.me.avatar_url)
     await ctx.send(embed=embed)
Exemple #21
0
    async def help(self, ctx):
        embed = discord.Embed(
            title=":newspaper: Coronavirus COVID-19 Commands",
            description=
            """[Wold Health Organization advices](https://www.who.int/emergencies/diseases/novel-coronavirus-2019/advice-for-public)
            **`<something>`** is required
            **`[something]`** is optional
            **`arg1 | arg2`** mean arg1 or arg2\n""",
            color=utils.COLOR,
            timestamp=utils.discord_timestamp())
        embed.add_field(name="**`c!info`**",
                        value="Views every confirmed cases",
                        inline=False)
        embed.add_field(
            name="**`c!country <COUNTRY>`**",
            value=
            "Views 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`",
            inline=False)
        embed.add_field(name="**`c!stats`**",
                        value="Views graphical statistics",
                        inline=False)
        embed.add_field(name="**`c!about`**",
                        value="Views informations about the bot",
                        inline=False)
        embed.add_field(name="**`c!source`**",
                        value="Views source data which the bot is based on.",
                        inline=False)
        embed.add_field(
            name="**`c!notification <enable | disable>`**",
            value=
            "(Only administrator) When new datas are downloaded the bot will send you a notification where you typed the command."
        )
        embed.add_field(name="**`c!ping`**",
                        value="Views bot ping.",
                        inline=False)
        embed.add_field(name="**`c!invite`**",
                        value="Views bot link invite.",
                        inline=False)
        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)
Exemple #22
0
 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)
Exemple #23
0
    async def info(self, ctx):
        DATA = self.bot._data

        header, text = utils.string_formatting(DATA)
        embed = discord.Embed(description=header + "\n\n" + text,
                              color=utils.COLOR,
                              timestamp=utils.discord_timestamp())

        embed.set_author(
            name=f"All countries affected by Coronavirus COVID-19",
            url="https://www.who.int/home",
            icon_url=self.bot.author_thumb)
        embed.set_thumbnail(url=self.thumb + str(uuid.uuid4()))
        embed.set_footer(text=utils.last_update(utils.DATA_PATH),
                         icon_url=ctx.guild.me.avatar_url)

        with open(utils.STATS_PATH, "rb") as p:
            img = discord.File(p, filename=utils.STATS_PATH)
        embed.set_image(url=f'attachment://{utils.STATS_PATH}')
        await ctx.send(file=img, embed=embed)
Exemple #24
0
 async def info_error(self, ctx, error):
     DATA = utils.from_json(utils.DATA_PATH)
     header, text = utils.string_formatting(DATA)
     embed = discord.Embed(
         description=header + "\n" + text,
         color=utils.COLOR,
         timestamp=utils.discord_timestamp()
     )
     embed.set_author(name="Country/Region affected by Coronavirus COVID-19 (Cases confirmed)",
                      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)
Exemple #25
0
    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:

            header, text = utils.string_formatting(self.bot._data, country)
            embed = discord.Embed(description=header + "\n\n" + text,
                                  color=utils.COLOR,
                                  timestamp=utils.discord_timestamp())
            if not len(text):
                embed = discord.Embed(description="Wrong country selected",
                                      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.bot.author_thumb)
        embed.set_thumbnail(url=self.bot.thumb + str(time.time()))
        embed.set_footer(text=utils.last_update(utils.DATA_PATH),
                         icon_url=ctx.me.avatar_url)
        await ctx.send(embed=embed)
Exemple #26
0
    async def send_notifications(self):
        data = self.bot._data
        channels_id = db.to_send()

        for guild in channels_id:
            # go next, didn't match interval for this guild
            if self.interval_update % guild["next_update"] != 0:
                continue
            try:
                version = utils.STATS_PATH
                if guild["country"] != "all":
                    stats = utils._get_country(data, guild["country"])
                    today = stats["today"]
                    confirmed = stats["statistics"]["confirmed"]
                    recovered = stats["statistics"]["recovered"]
                    deaths = stats["statistics"]["deaths"]
                    active = stats["statistics"]["active"]
                    country_name = stats["country"]["name"]
                    thumb = f"https://raw.githubusercontent.com/hjnilsson/country-flags/master/png250px/{stats['country']['code'].lower()}.png"

                    version = stats["country"]["code"].lower(
                    ) + utils.STATS_PATH

                    if not os.path.exists(version):
                        await plot_csv(version,
                                       self.bot._data,
                                       country=guild["country"])

                elif guild["country"] == "all":
                    stats = data["total"]
                    today = stats["today"]
                    confirmed = stats["confirmed"]
                    recovered = stats["recovered"]
                    deaths = stats["deaths"]
                    active = stats["active"]
                    thumb = self.bot.author_thumb
                    country_name = "All"

                    if not os.path.exists(version):
                        await plot_csv(version, self.bot._data)

                else:
                    continue

                embed = discord.Embed(
                    description=
                    "You can support me on <:kofi:693473314433138718>[Kofi](https://ko-fi.com/takitsu) and vote on [top.gg](https://top.gg/bot/682946560417333283/vote) for the bot. <:github:693519776022003742> [Source code](https://github.com/takitsu21/covid-19-tracker)",
                    timestamp=dt.datetime.utcnow(),
                    color=utils.COLOR)
                embed.set_author(name="Notification Coronavirus COVID-19",
                                 icon_url=self.bot.author_thumb)
                embed.set_author(
                    name=f"Coronavirus COVID-19 Notification - {country_name}",
                    icon_url=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"+{today['confirmed']:,} (**{utils.percentage(confirmed, today['confirmed'])}**)"
                )
                embed.add_field(
                    name="<:_calendar:692860616930623698> Today recovered",
                    value=
                    f"+{today['recovered']:,} (**{utils.percentage(confirmed, today['recovered'])}**)"
                )
                embed.add_field(
                    name="<:_calendar:692860616930623698> Today deaths",
                    value=
                    f"+{today['deaths']:,} (**{utils.percentage(confirmed, today['deaths'])}**)"
                )
                embed.add_field(
                    name="<:bed_hospital:692857285499682878> Active",
                    value=
                    f"{active:,} (**{utils.percentage(confirmed, active)}**)")
                with open(version, "rb") as p:
                    img = discord.File(p, filename=version)
                embed.set_image(url=f'attachment://{version}')
                try:
                    embed.set_thumbnail(url=stats["country"]["map"])
                except:
                    embed.set_thumbnail(url=self.bot.thumb + str(uuid.uuid4()))
                channel = self.bot.get_channel(int(guild["channel_id"]))
                try:
                    guild = self.bot.get_guild(int(guild["guild_id"]))
                    embed.set_footer(text=utils.last_update(utils.DATA_PATH),
                                     icon_url=guild.me.avatar_url)
                except Exception as e:
                    pass
                await channel.send(file=img, embed=embed)
            except Exception as e:
                pass
        logger.info("Notifications sent")
Exemple #27
0
    async def send_tracker(self):
        embed = discord.Embed(
            description=
            "You can support me on [Kofi](https://ko-fi.com/takitsu) and vote on [top.gg](https://top.gg/bot/682946560417333283/vote) for the bot.\n[World Health Organization advices](https://www.who.int/emergencies/diseases/novel-coronavirus-2019/advice-for-public)",
            timestamp=dt.datetime.utcnow(),
            color=utils.COLOR)
        embed.set_author(name="Personal tracker for Coronavirus COVID-19",
                         icon_url=self.bot.author_thumb)
        embed.set_thumbnail(url=self.bot.thumb + str(uuid.uuid4()))
        embed.add_field(name="<:confirmed:688686089548202004> Confirmed",
                        value=f"{self.bot._data['total']['confirmed']:,}")
        embed.add_field(
            name="<:recov:688686059567185940> Recovered",
            value=
            f"{self.bot._data['total']['recovered']:,} (**{utils.percentage(self.bot._data['total']['confirmed'], self.bot._data['total']['recovered'])}**)"
        )
        embed.add_field(
            name="<:_death:688686194917244928> Deaths",
            value=
            f"{self.bot._data['total']['deaths']:,} (**{utils.percentage(self.bot._data['total']['confirmed'], self.bot._data['total']['deaths'])}**)"
        )

        embed.add_field(
            name="<:_calendar:692860616930623698> Today confirmed",
            value=
            f"+{self.bot._data['total']['today']['confirmed']:,} (**{utils.percentage(self.bot._data['total']['confirmed'], self.bot._data['total']['today']['confirmed'])}**)"
        )
        embed.add_field(
            name="<:_calendar:692860616930623698> Today recovered",
            value=
            f"+{self.bot._data['total']['today']['recovered']:,} (**{utils.percentage(self.bot._data['total']['confirmed'], self.bot._data['total']['today']['recovered'])}**)"
        )
        embed.add_field(
            name="<:_calendar:692860616930623698> Today deaths",
            value=
            f"+{self.bot._data['total']['today']['deaths']:,} (**{utils.percentage(self.bot._data['total']['confirmed'], self.bot._data['total']['today']['deaths'])}**)"
        )
        embed.add_field(
            name="<:bed_hospital:692857285499682878> Active",
            value=
            f"{self.bot._data['total']['active']:,} (**{utils.percentage(self.bot._data['total']['confirmed'], self.bot._data['total']['active'])}**)"
        )
        tracked = db.send_tracker()
        for t in tracked:
            try:
                dm = self.bot.get_user(int(t["user_id"]))
                header, text = utils.string_formatting(self.bot._data,
                                                       t["country"].split(" "))
                embed.description = "You can support me on <:kofi:693473314433138718>[Kofi](https://ko-fi.com/takitsu) and vote on [top.gg](https://top.gg/bot/682946560417333283/vote) for the bot. <:github:693519776022003742> [Source code](https://github.com/takitsu21/covid-19-tracker)\n\n" + text

                with open("stats.png", "rb") as p:
                    img = discord.File(p, filename="stats.png")
                embed.set_image(url=f'attachment://stats.png')
                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(file=img, embed=embed)
            except Exception as e:
                pass
Exemple #28
0
    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")
Exemple #29
0
    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)
Exemple #30
0
    async def info(self, ctx):
        DATA = utils.from_json(utils.DATA_PATH)
        header, text = utils.string_formatting(DATA)
        # pages = self.generate_pages(DATA, len(header))
        # index = 0

        # page_length = len(pages)
        # print(page_length)
        # if page_length > 1:
            # page_left = "⬅️"
            # page_right = "➡️"
            # base_reactions = [page_left, page_right]
            # embed.set_author(
            #         name=f"Page {index + 1}",
            #         url="https://www.who.int/home",
            #         icon_url=self.author_thumb
            #         )
            # pagination = await ctx.send(embed=embed)
            # for reaction in base_reactions:
            #     await pagination.add_reaction(reaction)
            # while True:
            #     def check(reaction, user):
            #         return user == ctx.message.author and str(reaction.emoji) in base_reactions
            #     try:
            #         reaction, user = await self.bot.wait_for('reaction_add', check=check, timeout=300.0)
            #         emoji = str(reaction.emoji)
            #     except asyncio.TimeoutError:
            #         try:
            #             await ctx.message.delete()
            #         except:
            #             pass
            #         return await pagination.delete()
            #     if page_left in emoji and index > 0:
            #         index -= 1
            #     elif page_right in emoji and index < page_length:
            #         index += 1
            #     if index >= 0 and index <= page_length:
            #         embed = discord.Embed(
            #             description=pages[0][index]
            #         )
            #         embed.set_author(
            #             name=f"Page {index + 1}",
            #             url="https://www.who.int/home",
            #             icon_url=self.author_thumb
            #             )
            #         embed.color = utils.COLOR
            #         embed.timestamp = utils.discord_timestamp()
            #         embed.set_thumbnail(url=self.thumb)
            #         embed.set_footer(text=utils.last_update(utils.DATA_PATH),
            #                         icon_url=ctx.guild.me.avatar_url)

            #         await pagination.edit(embed=embed)
        #     for i, _p in enumerate(pages):
        #         embed = discord.Embed(
        #             description=header + "\n" + _p[i],
        #             color=utils.COLOR,
        #             timestamp=utils.discord_timestamp()
        #         )
        #         embed.set_author(
        #                 name=f"Coronavrius COVID-19 Pages {i + 1}/{page_length} (Cases confirmed)",
        #                 url="https://www.who.int/home",
        #                 icon_url=self.author_thumb
        #                 )
        #         embed.color = utils.COLOR
        #         embed.timestamp = utils.discord_timestamp()
        #         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)
        # else:
        embed = discord.Embed(
            description=header + "\n" + text,
            color=utils.COLOR,
            timestamp=utils.discord_timestamp()
        )
        embed.set_author(
                name=f"Country/Region affected by Coronavirus COVID-19 (Cases confirmed)",
                url="https://www.who.int/home",
                icon_url=self.author_thumb
                )
        embed.color = utils.COLOR
        embed.timestamp = utils.discord_timestamp()
        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)