コード例 #1
0
async def update_names(bot: Bot) -> None:
    """Background updater task that performs the daily channel name update."""
    while True:
        # Since we truncate the compute timedelta to seconds, we add one second to ensure
        # we go past midnight in the `seconds_to_sleep` set below.
        today_at_midnight = datetime.utcnow().replace(microsecond=0,
                                                      second=0,
                                                      minute=0,
                                                      hour=0)
        next_midnight = today_at_midnight + timedelta(days=1)
        seconds_to_sleep = (next_midnight - datetime.utcnow()).seconds + 1
        await asyncio.sleep(seconds_to_sleep)

        try:
            channel_0_name, channel_1_name, channel_2_name = await bot.api_client.get(
                'bot/off-topic-channel-names', params={'random_items': 3})
        except ResponseCodeError as e:
            log.error(
                f"Failed to get new off topic channel names: code {e.response.status}"
            )
            continue
        channel_0, channel_1, channel_2 = (bot.get_channel(channel_id)
                                           for channel_id in CHANNELS)

        await channel_0.edit(name=f'ot0-{channel_0_name}')
        await channel_1.edit(name=f'ot1-{channel_1_name}')
        await channel_2.edit(name=f'ot2-{channel_2_name}')
        log.debug("Updated off-topic channel names to"
                  f" {channel_0_name}, {channel_1_name} and {channel_2_name}")
コード例 #2
0
async def new_puzzle_notification(bot: Bot) -> None:
    """
    Announce the release of a new Advent of Code puzzle.

    This background task hibernates until just before the Advent of Code starts
    and will then start announcing puzzles as they are published. After the
    event has finished, this task will terminate.
    """
    # We wake up one hour before the event starts to prepare the announcement
    # of the release of the first puzzle.
    await wait_for_advent_of_code(hours_before=1)

    log.info("The Advent of Code has started or will start soon, waking up notification task.")

    # Ensure that the guild cache is loaded so we can get the Advent of Code
    # channel and role.
    await bot.wait_until_guild_available()
    aoc_channel = bot.get_channel(Channels.advent_of_code)
    aoc_role = aoc_channel.guild.get_role(AdventOfCode.role_id)

    if not aoc_channel:
        log.error("Could not find the AoC channel to send notification in")
        return

    if not aoc_role:
        log.error("Could not find the AoC role to announce the daily puzzle")
        return

    # The last event day is 25 December, so we only have to schedule
    # a reminder if the current day is before 25 December.
    end = arrow.get(datetime.datetime(AdventOfCode.year, 12, 25), EST)
    while arrow.now(EST) < end:
        log.trace("Started puzzle notification loop.")
        tomorrow, time_left = time_left_to_est_midnight()

        # Use `total_seconds` to get the time left in fractional seconds This
        # should wake us up very close to the target. As a safe guard, the sleep
        # duration is padded with 0.1 second to make sure we wake up after
        # midnight.
        sleep_seconds = time_left.total_seconds() + 0.1
        log.trace(f"The puzzle notification task will sleep for {sleep_seconds} seconds")
        await asyncio.sleep(sleep_seconds)

        puzzle_url = f"https://adventofcode.com/{AdventOfCode.year}/day/{tomorrow.day}"

        # Check if the puzzle is already available to prevent our members from spamming
        # the puzzle page before it's available by making a small HEAD request.
        for retry in range(1, 5):
            log.debug(f"Checking if the puzzle is already available (attempt {retry}/4)")
            async with bot.http_session.head(puzzle_url, raise_for_status=False) as resp:
                if resp.status == 200:
                    log.debug("Puzzle is available; let's send an announcement message.")
                    break
            log.debug(f"The puzzle is not yet available (status={resp.status})")
            await asyncio.sleep(10)
        else:
            log.error(
                "The puzzle does does not appear to be available "
                "at this time, canceling announcement"
            )
            break

        await aoc_channel.send(
            f"{aoc_role.mention} Good morning! Day {tomorrow.day} is ready to be attempted. "
            f"View it online now at {puzzle_url}. Good luck!",
            allowed_mentions=discord.AllowedMentions(
                everyone=False,
                users=False,
                roles=[aoc_role],
            )
        )

        # Ensure that we don't send duplicate announcements by sleeping to well
        # over midnight. This means we're certain to calculate the time to the
        # next midnight at the top of the loop.
        await asyncio.sleep(120)
コード例 #3
0
ファイル: tortoise_api.py プロジェクト: ycl310/Tortoise-BOT
 def __init__(self, bot: Bot):
     self.bot: Bot = bot
     self.system_log_channel = bot.get_channel(
         constants.system_log_channel_id)
     self.user_suggestions_channel = bot.get_channel(
         constants.suggestions_channel_id)
コード例 #4
0
 def __init__(self, bot: Bot):
     self.bot: Bot = bot
     self.system_log_channel = bot.get_channel(constants.system_log_channel_id)