Esempio n. 1
0
async def get_updater(_id: Union[str, int], ctx: MyContext, *, allow_all: bool = False) -> \
        Optional[Union[List[AutoupdaterData], AutoupdaterData]]:
    _id = _id.lower().strip()
    try:
        _id = int(_id)
    except ValueError:
        if not _id == "all":
            return
        else:
            if allow_all:
                updater_list = []
                async for ad in AutoupdaterData().filter(
                        discord_id=ctx.channel.id):
                    updater_list.append(ad)
                return updater_list
            else:
                raise commands.BadArgument("`all` is a invalid ID!")
    else:
        async for ad in AutoupdaterData().filter(discord_id=ctx.channel.id,
                                                 id=_id):
            return ad
Esempio n. 2
0
    async def _state(self, ctx: MyContext, delay: ShortTime, state: str):
        """
        Enable autoupdaters for a state. For a list of states, run /list .
        delay is a human-readable time, like 12h for 12 hours, or 10m for 10 minutes.
        state is the state name. If it includes spaces, be sure to wrap it in quotes.
        This requires at least two vote credits.
        """
        _ = await ctx.get_translate_function()

        delta_seconds = int(
            abs((datetime.datetime.utcnow() - delay.dt).total_seconds()))
        human_update_time = human_timedelta(delay.dt)

        db_guild = await get_from_db(ctx.guild)
        db_channel = await get_from_db(ctx.channel)

        if not await self.do_initial_checks(
                ctx, db_guild, db_channel, delta_seconds, _,
                requires_vote=True):
            return

        info = await self.bot.worldometers_api.try_to_get_name()
        if info is None:
            await ctx.reply(
                _("❌ Failed to find a state with that name! `/list` will show you a list of states "
                  "and their names."))
        elif info[0] == "state":
            iso2_code = friendly_country_name = state
        else:
            cmd_usage = "{0}autoupdate {1} {2}".format(
                ctx.prefix, info[0], '' if info[0] != 'world' else state)
            await ctx.reply(
                _(
                    "I found a {0} instead of a state! You can try `{1}` instead.",
                    info[0], cmd_usage))
            return

        update_delay = delta_seconds
        ad_data = AutoupdaterData(already_set=True,
                                  country_name=iso2_code,
                                  delay=update_delay,
                                  discord_id=ctx.channel.id,
                                  type=AutoupdateTypes.state)
        await ad_data.save()
        db_guild.used_updaters += 1
        db_guild.total_updaters -= 1
        await db_guild.save()
        await db_channel.autoupdater.add(ad_data)
        await db_channel.save()

        await ctx.reply(
            _("✅ Posting stats for {0} in this channel every {1}.",
              friendly_country_name, human_update_time))
Esempio n. 3
0
    async def _country(self, ctx: MyContext, delay: ShortTime, country: str):
        """
        Enable autoupdaters for a continent. For a list of countries, run /list .
        delay is a human-readable time, like 12h for 12 hours, or 10m for 10 minutes.
        continent is the continent name. If it includes spaces, be sure to wrap it in quotes.
        """
        _ = await ctx.get_translate_function()

        delta_seconds = int(
            abs((datetime.datetime.utcnow() - delay.dt).total_seconds()))
        human_update_time = human_timedelta(delay.dt)

        db_guild = await get_from_db(ctx.guild)
        db_channel = await get_from_db(ctx.channel)

        if not await self.do_initial_checks(ctx, db_guild, db_channel,
                                            delta_seconds, _):
            return

        info = await self.bot.worldometers_api.try_to_get_name(country)
        if info is None:
            await ctx.reply(
                _("❌ Failed to get a ISO2 code for the country! `/list` will show you a list of countries "
                  "and their IDs."))
        elif info[0] == "country":
            country_list = await self.bot.worldometers_api.get_all_iso_codes()
            iso2_code = covid19api.get_iso2_code(country, country_list)
            friendly_country_name = covid19api.get_country_name(
                country, country_list)
        else:
            cmd_usage = "{0}autoupdate {1} {2}".format(
                ctx.prefix, info[0], '' if info[0] != 'world' else country)
            await ctx.reply(
                _(
                    "I found a {0} instead of a country! You can try `{1}` instead.",
                    info[0], cmd_usage))
            return

        update_delay = delta_seconds
        ad_data = AutoupdaterData(already_set=True,
                                  country_name=iso2_code,
                                  delay=update_delay,
                                  discord_id=ctx.channel.id,
                                  type=AutoupdateTypes.country)
        await ad_data.save()
        db_guild.used_updaters += 1
        await db_guild.save()
        await db_channel.autoupdater.add(ad_data)
        await db_channel.save()

        await ctx.reply(
            _("✅ Posting stats for {0} in this channel every {1}.",
              friendly_country_name, human_update_time))
Esempio n. 4
0
 async def _disable(self, ctx: MyContext, _id: str):
     """
     Removes a autoupdater from this channel.
     The only argument should be either a autoupdater ID, or "all" to delete all the updaters in the channel.
     """
     _ = await ctx.get_translate_function()
     db_channel = await get_from_db(ctx.channel)
     all_ad = db_channel.autoupdater
     _id = _id.lower().strip()
     total_updaters = len(all_ad)
     try:
         _id = int(_id)
     except ValueError:
         if not _id == "all":
             await ctx.reply(
                 _("❌ Must pass either {0} or a ID as a argument.",
                   "`all`"))
             return
     await db_channel.fetch_related("guild")
     if _id == "all":
         await db_channel.autoupdater.clear()
         async for ad in AutoupdaterData().filter(
                 discord_id=ctx.channel.id):
             await ad.delete()
         db_channel.guild.used_updaters -= total_updaters
         await db_channel.guild.save()
         await db_channel.save()
         await ctx.reply(_("✅ Deleted all autoupdaters in this channel."))
     else:
         async for ad in AutoupdaterData().filter(discord_id=ctx.channel.id,
                                                  id=_id):
             await ad.delete()
             break
         else:
             await ctx.reply(_("❌ No autoupdater with that ID found."))
             return
         db_channel.guild.used_updaters -= 1
         await db_channel.guild.save()
         await db_channel.save()
         await ctx.reply(_("✅ Deleted autoupdater with ID {0}.", _id))
Esempio n. 5
0
    async def _province(self, ctx: MyContext, delay: ShortTime, province: str):
        _ = await ctx.get_translate_function()

        delta_seconds = int(
            abs((datetime.datetime.utcnow() - delay.dt).total_seconds()))
        human_update_time = human_timedelta(delay.dt)

        db_guild = await get_from_db(ctx.guild)
        db_channel = await get_from_db(ctx.channel)

        if not await self.do_initial_checks(
                ctx, db_guild, db_channel, delta_seconds, _,
                requires_vote=True):
            return

        info = await self.bot.jhucsse_api.try_to_get_name()
        if info is None:
            await ctx.reply(
                _("❌ Failed to find a province with that name! Make sure it is correct."
                  ))
        elif info[0] == "province":
            iso2_code = friendly_country_name = province
        else:
            cmd_usage = "{0}autoupdate {1} {2}".format(
                ctx.prefix, info[0], '' if info[0] != 'world' else province)
            await ctx.reply(
                _(
                    "I found a {0} instead of a province! You can try `{1}` instead.",
                    info[0], cmd_usage))
            return

        update_delay = delta_seconds
        ad_data = AutoupdaterData(already_set=True,
                                  country_name=iso2_code,
                                  delay=update_delay,
                                  discord_id=ctx.channel.id,
                                  type=AutoupdateTypes.province)
        await ad_data.save()
        db_guild.used_updaters += 1
        db_guild.total_updaters -= 1
        await db_guild.save()
        await db_channel.autoupdater.add(ad_data)
        await db_channel.save()

        await ctx.reply(
            _("✅ Posting stats for {0} in this channel every {1}.",
              friendly_country_name, human_update_time))
Esempio n. 6
0
    async def __world(self, ctx: MyContext, delay: ShortTime,
                      logarithmic: bool):
        """
        Enable graph autoupdaters for the world.
        delay is a human-readable time, like 12h for 12 hours, or 10m for 10 minutes.
        logarithmic is whether the graph should be logarithmic.
        """
        _ = await ctx.get_translate_function()

        delta_seconds = int(
            abs((datetime.datetime.utcnow() - delay.dt).total_seconds()))
        human_update_time = human_timedelta(delay.dt)

        db_guild = await get_from_db(ctx.guild)
        db_channel = await get_from_db(ctx.channel)

        if not await self.do_initial_checks(ctx,
                                            db_guild,
                                            db_channel,
                                            delta_seconds,
                                            _,
                                            requires_vote=True,
                                            min_delay=82800):
            return

        update_delay = delta_seconds
        ad_data = AutoupdaterData(
            already_set=True,
            country_name=f"world_{'log' if logarithmic else 'lin'}",
            delay=update_delay,
            discord_id=ctx.channel.id,
            type=AutoupdateTypes.graph)
        await ad_data.save()
        db_guild.used_updaters += 1
        db_guild.total_updaters -= 1
        await db_guild.save()
        await db_channel.autoupdater.add(ad_data)
        await db_channel.save()

        await ctx.reply(
            _("✅ Posting a {0} graph for {1} in this channel every {2}.",
              _("logarithmic") if logarithmic else _("linear"), "world",
              human_update_time))
Esempio n. 7
0
    async def _maps(self, ctx: MyContext, delay: ShortTime, map_type: str):
        """
        Enable autoupdaters for maps. This requires two vote credits to enable any of them.
        delay is a human-readable time like 12h for 12 hours or 15m for 15 minutes.
        map_type should be one of the map types under `map types`
        """
        _ = await ctx.get_translate_function()

        if map_type.lower() not in self.bot.maps_api.get_map_names():
            await ctx.reply(
                _(
                    "The map type must exactly match one of the following:\n`{0}`",
                    "` `".join(self.bot.maps_api.get_map_names())))
            return
        delta_seconds = int(
            abs((datetime.datetime.utcnow() - delay.dt).total_seconds()))
        human_update_time = human_timedelta(delay.dt)

        db_guild = await get_from_db(ctx.guild)
        db_channel = await get_from_db(ctx.channel)

        if not await self.do_initial_checks(
                ctx, db_guild, db_channel, delta_seconds, _,
                requires_vote=True):
            return

        update_delay = delta_seconds
        ad_data = AutoupdaterData(already_set=True,
                                  country_name=map_type.lower(),
                                  delay=update_delay,
                                  discord_id=ctx.channel.id,
                                  type=AutoupdateTypes.map)
        await ad_data.save()
        db_guild.used_updaters += 1
        db_guild.total_updaters -= 1
        await db_guild.save()
        await db_channel.autoupdater.add(ad_data)
        await db_channel.save()

        await ctx.reply(
            _("✅ Posting a map for {0} in this channel every {1}.",
              map_type.replace("_", " ").title(), human_update_time))
Esempio n. 8
0
 async def _list(self, ctx: MyContext):
     """
     Lists all autoupdaters in this channel.
     """
     _ = await ctx.get_translate_function()
     cmd_usage = f"{ctx.prefix}autoupdate disable <id>"
     update_embed = discord.Embed(
         title=_("List of Updaters"),
         description=_(
             "To disable one of these updaters, run {0}, replacing {1} with the "
             "ID.", cmd_usage, "`<id>`"))
     async for updater in AutoupdaterData().filter(
             discord_id=ctx.channel.id):
         update_embed.add_field(name=updater.id,
                                value=_(
                                    "Country: {0}\n"
                                    "Delay: {1} seconds",
                                    updater.country_name, updater.delay))
     if len(update_embed.fields) == 0:
         update_embed.add_field(name=_("None 😞"),
                                value=_("Add one with the {0} command!",
                                        "`/autoupdate`"))
     await ctx.reply(embed=update_embed)
Esempio n. 9
0
    async def _custom(self, ctx: MyContext, delay: ShortTime, *, custom: str):
        """
        Enable autoupdaters for maps. This requires two vote credits to enable any of them.
        delay is a human-readable time like 12h for 12 hours or 15m for 15 minutes.
        map_type should be one of the map types under `map types`
        """
        _ = await ctx.get_translate_function()

        try:
            example = self.bot.custom_updater_helper.parse(custom)
        except AttributeError:
            self.custom_updater_helper = CustomUpdater(self.bot)
            await self.custom_updater_helper.setup()
            await ctx.reply(
                _("Try sending your command again. If it errors out again, wait a few moments and then try "
                  "again."))
        except InvalidKeyError as e:
            # five brackets, twice escapes once, so need two of those, and the 5th makes it a placeholder as normal
            await ctx.reply(
                _(
                    "There was a invalid key in your updater: `{0}`. Either escape it with two brackets "
                    "(like so: {{{{{0}}}}}) or remove it.\n"
                    "If you need help finding the correct key, see "
                    "https://wiki.covid19.imaskeleton.me/index.php?title=Custom_Updaters.",
                    e.key))
            return
        delta_seconds = int(
            abs((datetime.datetime.utcnow() - delay.dt).total_seconds()))
        human_update_time = human_timedelta(delay.dt)

        db_guild = await get_from_db(ctx.guild)
        db_channel = await get_from_db(ctx.channel)

        if not await self.do_initial_checks(
                ctx, db_guild, db_channel, delta_seconds, _,
                requires_vote=True):
            return

        def check(m: discord.Message):
            return ctx.author.id == m.author.id and ctx.channel.id == m.channel.id and m.content.lower(
            ) == "ok"

        msg = await ctx.reply(
            _(
                "Your custom updater will look like the following:\n{0}\nType {1} within 15 seconds to "
                "confirm.", example, "`ok`"))
        try:
            await self.bot.wait_for("message", check=check, timeout=15)
        except asyncio.TimeoutError:
            await msg.edit(
                content=_("Timed out. Rerun this command to try again."))
            return
        else:
            await msg.delete()

        update_delay = delta_seconds
        ad_data = AutoupdaterData(already_set=True,
                                  country_name=example,
                                  delay=update_delay,
                                  discord_id=ctx.channel.id,
                                  type=AutoupdateTypes.custom)
        await ad_data.save()
        db_guild.used_updaters += 1
        db_guild.total_updaters -= 1
        await db_guild.save()
        await db_channel.autoupdater.add(ad_data)
        await db_channel.save()

        await ctx.reply(
            _("✅ Posting a custom updater in this channel every {0}.",
              human_update_time))
Esempio n. 10
0
    async def __state(self, ctx: MyContext, delay: ShortTime, state: str,
                      logarithmic: bool):
        """
        Enable autoupdaters for a US state.
        delay is a human-readable time, like 12h for 12 hours, or 10m for 10 minutes.
        state is the state name.
        logarithmic is whether the graph should be logarithmic.
        """
        _ = await ctx.get_translate_function()

        delta_seconds = int(
            abs((datetime.datetime.utcnow() - delay.dt).total_seconds()))
        human_update_time = human_timedelta(delay.dt)

        db_guild = await get_from_db(ctx.guild)
        db_channel = await get_from_db(ctx.channel)

        if not await self.do_initial_checks(ctx,
                                            db_guild,
                                            db_channel,
                                            delta_seconds,
                                            _,
                                            requires_vote=True,
                                            min_delay=82800):
            return

        info = await self.bot.jhucsse_api.try_to_get_name(state)
        if info is None:
            cmd_usage = f"`{ctx.prefix}list`"
            await ctx.reply(
                _("❌ Failed to find that state name! See {0} for help!",
                  cmd_usage))
            return
        elif info[0] == "state":
            friendly_country_name = state
        else:
            cmd_usage = f"{ctx.prefix}autoupdate graphs {info[0]} {'' if info[0] != 'world' else state}"
            await ctx.reply(
                _(
                    "I found a {0} instead of a state! You can try `{1}` instead.",
                    info[0], cmd_usage))
            return

        update_delay = delta_seconds
        ad_data = AutoupdaterData(
            already_set=True,
            country_name=f"{info[1].title() if info[1] else 'world'}_"
            f"{'log' if logarithmic else 'lin'}",
            delay=update_delay,
            discord_id=ctx.channel.id,
            type=AutoupdateTypes.graph)
        await ad_data.save()
        db_guild.used_updaters += 1
        db_guild.total_updaters -= 1
        await db_guild.save()
        await db_channel.autoupdater.add(ad_data)
        await db_channel.save()

        await ctx.reply(
            _("✅ Posting a {0} graph for {1} in this channel every {2}.",
              _("logarithmic") if logarithmic else _("linear"),
              friendly_country_name, human_update_time))
Esempio n. 11
0
    async def __country(self, ctx: MyContext, delay: ShortTime, country: str,
                        logarithmic: bool):
        """
        Enable autoupdaters for a country.
        delay is a human-readable time, like 12h for 12 hours, or 10m for 10 minutes.
        country is the country name. For a list of countries, run /list.
        logarithmic is whether the graph should be logarithmic.
        """
        _ = await ctx.get_translate_function()

        delta_seconds = int(
            abs((datetime.datetime.utcnow() - delay.dt).total_seconds()))
        human_update_time = human_timedelta(delay.dt)

        db_guild = await get_from_db(ctx.guild)
        db_channel = await get_from_db(ctx.channel)

        if not await self.do_initial_checks(ctx,
                                            db_guild,
                                            db_channel,
                                            delta_seconds,
                                            _,
                                            requires_vote=True,
                                            min_delay=82800):
            return

        info = await self.bot.jhucsse_api.try_to_get_name(country)
        if info is None:
            await ctx.reply(
                _("❌ Failed to get a ISO2 code for the country! `/list` will show you a list of countries "
                  "and their IDs."))
            return
        elif info[0] == "country":
            country_list = await self.bot.worldometers_api.get_all_iso_codes()
            friendly_country_name = covid19api.get_country_name(
                country, country_list)
        else:
            cmd_usage = f"{ctx.prefix}autoupdate graphs {info[0]} {'' if info[0] != 'world' else country}"
            await ctx.reply(
                _(
                    "I found a {0} instead of a country! You can try `{1}` instead.",
                    info[0], cmd_usage))
            return

        update_delay = delta_seconds
        ad_data = AutoupdaterData(
            already_set=True,
            country_name=f"{info[1].title() if info[1] else 'world'}_"
            f"{'log' if logarithmic else 'lin'}",
            delay=update_delay,
            discord_id=ctx.channel.id,
            type=AutoupdateTypes.graph)
        await ad_data.save()
        db_guild.used_updaters += 1
        db_guild.total_updaters -= 1
        await db_guild.save()
        await db_channel.autoupdater.add(ad_data)
        await db_channel.save()

        await ctx.reply(
            _("✅ Posting a {0} graph for {1} in this channel every {2}.",
              _("logarithmic") if logarithmic else _("linear"),
              friendly_country_name, human_update_time))