diff options
| author | 2021-12-02 13:46:17 +0400 | |
|---|---|---|
| committer | 2021-12-02 13:46:17 +0400 | |
| commit | 38892a5d51dc40dad8024eedaef134406768deb7 (patch) | |
| tree | 84dc98070154ad7fa8eb51d270ebd1c0561dacad | |
| parent | Revert change to if statement checking if staff in `.aoc join` (diff) | |
| parent | Merge pull request #950 from onerandomusername/patch-3 (diff) | |
Merge branch 'main' into update-role-constants
| -rw-r--r-- | bot/exts/events/advent_of_code/_cog.py | 36 | ||||
| -rw-r--r-- | bot/exts/holidays/hanukkah/hanukkah_embed.py | 84 | ||||
| -rw-r--r-- | bot/utils/pagination.py | 10 | 
3 files changed, 51 insertions, 79 deletions
| diff --git a/bot/exts/events/advent_of_code/_cog.py b/bot/exts/events/advent_of_code/_cog.py index 34ade5b1..65a16fdd 100644 --- a/bot/exts/events/advent_of_code/_cog.py +++ b/bot/exts/events/advent_of_code/_cog.py @@ -102,32 +102,26 @@ class AdventOfCode(commands.Cog):      @whitelist_override(channels=AOC_WHITELIST)      async def aoc_countdown(self, ctx: commands.Context) -> None:          """Return time left until next day.""" -        if not _helpers.is_in_advent(): -            datetime_now = arrow.now(_helpers.EST) - -            # Calculate the delta to this & next year's December 1st to see which one is closest and not in the past -            this_year = arrow.get(datetime(datetime_now.year, 12, 1), _helpers.EST) -            next_year = arrow.get(datetime(datetime_now.year + 1, 12, 1), _helpers.EST) -            deltas = (dec_first - datetime_now for dec_first in (this_year, next_year)) -            delta = min(delta for delta in deltas if delta >= timedelta())  # timedelta() gives 0 duration delta - -            # Add a finer timedelta if there's less than a day left -            if delta.days == 0: -                delta_str = f"approximately {delta.seconds // 3600} hours" -            else: -                delta_str = f"{delta.days} days" +        if _helpers.is_in_advent(): +            tomorrow, _ = _helpers.time_left_to_est_midnight() +            next_day_timestamp = int(tomorrow.timestamp()) -            await ctx.send( -                "The Advent of Code event is not currently running. " -                f"The next event will start in {delta_str}." -            ) +            await ctx.send(f"Day {tomorrow.day} starts <t:{next_day_timestamp}:R>.")              return -        tomorrow, time_left = _helpers.time_left_to_est_midnight() +        datetime_now = arrow.now(_helpers.EST) +        # Calculate the delta to this & next year's December 1st to see which one is closest and not in the past +        this_year = arrow.get(datetime(datetime_now.year, 12, 1), _helpers.EST) +        next_year = arrow.get(datetime(datetime_now.year + 1, 12, 1), _helpers.EST) +        deltas = (dec_first - datetime_now for dec_first in (this_year, next_year)) +        delta = min(delta for delta in deltas if delta >= timedelta())  # timedelta() gives 0 duration delta -        hours, minutes = time_left.seconds // 3600, time_left.seconds // 60 % 60 +        next_aoc_timestamp = int((datetime_now + delta).timestamp()) -        await ctx.send(f"There are {hours} hours and {minutes} minutes left until day {tomorrow.day}.") +        await ctx.send( +            "The Advent of Code event is not currently running. " +            f"The next event will start <t:{next_aoc_timestamp}:R>." +        )      @adventofcode_group.command(name="about", aliases=("ab", "info"), brief="Learn about Advent of Code")      @whitelist_override(channels=AOC_WHITELIST) diff --git a/bot/exts/holidays/hanukkah/hanukkah_embed.py b/bot/exts/holidays/hanukkah/hanukkah_embed.py index ac3eab7b..5767f91e 100644 --- a/bot/exts/holidays/hanukkah/hanukkah_embed.py +++ b/bot/exts/holidays/hanukkah/hanukkah_embed.py @@ -21,45 +21,41 @@ class HanukkahEmbed(commands.Cog):      def __init__(self, bot: Bot):          self.bot = bot -        self.hanukkah_days = [] -        self.hanukkah_months = [] -        self.hanukkah_years = [] +        self.hanukkah_dates: list[datetime.date] = [] -    async def get_hanukkah_dates(self) -> list[str]: +    def _parse_time_to_datetime(self, date: list[str]) -> datetime.datetime: +        """Format the times provided by the api to datetime forms.""" +        try: +            return datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S%z") +        except ValueError: +            # there is a possibility of an event not having a time, just a day +            # to catch this, we try again without time information +            return datetime.datetime.strptime(date, "%Y-%m-%d") + +    async def fetch_hanukkah_dates(self) -> list[datetime.date]:          """Gets the dates for hanukkah festival.""" -        hanukkah_dates = [] +        # clear the datetime objects to prevent a memory link +        self.hanukkah_dates = []          async with self.bot.http_session.get(HEBCAL_URL) as response:              json_data = await response.json()          festivals = json_data["items"]          for festival in festivals:              if festival["title"].startswith("Chanukah"):                  date = festival["date"] -                hanukkah_dates.append(date) -        return hanukkah_dates +                self.hanukkah_dates.append(self._parse_time_to_datetime(date).date()) +        return self.hanukkah_dates      @in_month(Month.NOVEMBER, Month.DECEMBER)      @commands.command(name="hanukkah", aliases=("chanukah",))      async def hanukkah_festival(self, ctx: commands.Context) -> None:          """Tells you about the Hanukkah Festivaltime of festival, festival day, etc).""" -        hanukkah_dates = await self.get_hanukkah_dates() -        self.hanukkah_dates_split(hanukkah_dates) -        hanukkah_start_day = int(self.hanukkah_days[0]) -        hanukkah_start_month = int(self.hanukkah_months[0]) -        hanukkah_start_year = int(self.hanukkah_years[0]) -        hanukkah_end_day = int(self.hanukkah_days[8]) -        hanukkah_end_month = int(self.hanukkah_months[8]) -        hanukkah_end_year = int(self.hanukkah_years[8]) - -        hanukkah_start = datetime.date(hanukkah_start_year, hanukkah_start_month, hanukkah_start_day) -        hanukkah_end = datetime.date(hanukkah_end_year, hanukkah_end_month, hanukkah_end_day) +        hanukkah_dates = await self.fetch_hanukkah_dates() +        start_day = hanukkah_dates[0] +        end_day = hanukkah_dates[-1]          today = datetime.date.today() -        # today = datetime.date(2019, 12, 24) (for testing) -        day = str(today.day) -        month = str(today.month) -        year = str(today.year)          embed = Embed(title="Hanukkah", colour=Colours.blue) -        if day in self.hanukkah_days and month in self.hanukkah_months and year in self.hanukkah_years: -            if int(day) == hanukkah_start_day: +        if start_day <= today <= end_day: +            if start_day == today:                  now = datetime.datetime.utcnow()                  hours = now.hour + 4  # using only hours                  hanukkah_start_hour = 18 @@ -77,35 +73,27 @@ class HanukkahEmbed(commands.Cog):                      )                      await ctx.send(embed=embed)                      return -            festival_day = self.hanukkah_days.index(day) +            festival_day = hanukkah_dates.index(today)              number_suffixes = ["st", "nd", "rd", "th"]              suffix = number_suffixes[festival_day - 1 if festival_day <= 3 else 3]              message = ":menorah:" * festival_day -            embed.description = f"It is the {festival_day}{suffix} day of Hanukkah!\n{message}" -            await ctx.send(embed=embed) +            embed.description = ( +                f"It is the {festival_day}{suffix} day of Hanukkah!\n{message}" +            ) +        elif today < start_day: +            format_start = start_day.strftime("%d of %B") +            embed.description = ( +                "Hanukkah has not started yet. " +                f"Hanukkah will start at sundown on {format_start}." +            )          else: -            if today < hanukkah_start: -                festival_starting_month = hanukkah_start.strftime("%B") -                embed.description = ( -                    f"Hanukkah has not started yet. " -                    f"Hanukkah will start at sundown on {hanukkah_start_day}th " -                    f"of {festival_starting_month}." -                ) -            else: -                festival_end_month = hanukkah_end.strftime("%B") -                embed.description = ( -                    f"Looks like you missed Hanukkah!" -                    f"Hanukkah ended on {hanukkah_end_day}th of {festival_end_month}." -                ) - -            await ctx.send(embed=embed) +            format_end = end_day.strftime("%d of %B") +            embed.description = ( +                "Looks like you missed Hanukkah! " +                f"Hanukkah ended on {format_end}." +            ) -    def hanukkah_dates_split(self, hanukkah_dates: list[str]) -> None: -        """We are splitting the dates for hanukkah into days, months and years.""" -        for date in hanukkah_dates: -            self.hanukkah_days.append(date[8:10]) -            self.hanukkah_months.append(date[5:7]) -            self.hanukkah_years.append(date[0:4]) +        await ctx.send(embed=embed)  def setup(bot: Bot) -> None: diff --git a/bot/utils/pagination.py b/bot/utils/pagination.py index 013ef9e7..188b279f 100644 --- a/bot/utils/pagination.py +++ b/bot/utils/pagination.py @@ -211,8 +211,6 @@ class LinePaginator(Paginator):                  log.debug(f"Got first page reaction - changing to page 1/{len(paginator.pages)}") -                embed.description = "" -                await message.edit(embed=embed)                  embed.description = paginator.pages[current_page]                  if footer_text:                      embed.set_footer(text=f"{footer_text} (Page {current_page + 1}/{len(paginator.pages)})") @@ -226,8 +224,6 @@ class LinePaginator(Paginator):                  log.debug(f"Got last page reaction - changing to page {current_page + 1}/{len(paginator.pages)}") -                embed.description = "" -                await message.edit(embed=embed)                  embed.description = paginator.pages[current_page]                  if footer_text:                      embed.set_footer(text=f"{footer_text} (Page {current_page + 1}/{len(paginator.pages)})") @@ -245,8 +241,6 @@ class LinePaginator(Paginator):                  current_page -= 1                  log.debug(f"Got previous page reaction - changing to page {current_page + 1}/{len(paginator.pages)}") -                embed.description = "" -                await message.edit(embed=embed)                  embed.description = paginator.pages[current_page]                  if footer_text: @@ -266,8 +260,6 @@ class LinePaginator(Paginator):                  current_page += 1                  log.debug(f"Got next page reaction - changing to page {current_page + 1}/{len(paginator.pages)}") -                embed.description = "" -                await message.edit(embed=embed)                  embed.description = paginator.pages[current_page]                  if footer_text: @@ -428,8 +420,6 @@ class ImagePaginator(Paginator):                  reaction_type = "next"              # Magic happens here, after page and reaction_type is set -            embed.description = "" -            await message.edit(embed=embed)              embed.description = paginator.pages[current_page]              image = paginator.images[current_page] or EmptyEmbed | 
