Add election countdown

This commit is contained in:
Nexus 2024-07-04 01:53:08 +01:00
parent f092e4db48
commit 0ea24df64e
Signed by: nex
GPG key ID: 0FA334385D0B689F

View file

@ -4,12 +4,13 @@ This module is only meant to be loaded during election times.
import asyncio
import datetime
import logging
import random
import re
import discord
import httpx
from bs4 import BeautifulSoup
from discord.ext import commands
from discord.ext import commands, tasks
SPAN_REGEX = re.compile(
@ -39,10 +40,66 @@ class ElectionCog(commands.Cog):
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 "
"Safari/537.36",
}
ETA = datetime.datetime(
2024,
7,
4,
23,
30,
tzinfo=datetime.datetime.now().astimezone().tzinfo
)
def __init__(self, bot):
self.bot = bot
self.bot: commands.Bot = bot
self.log = logging.getLogger("jimmy.cogs.election")
self.countdown_message = None
self.check_election.start()
def cog_unload(self) -> None:
self.check_election.cancel()
@tasks.loop(minutes=1)
async def check_election(self):
if not self.bot.is_ready():
await self.bot.wait_until_ready()
guild = self.bot.get_guild(994710566612500550)
if not guild:
return self.log.error("Nonsense guild not found. Can't do countdown.")
channel = discord.utils.get(guild.text_channels, name="countdown")
if not channel:
return self.log.error("Countdown channel not found.")
await asyncio.sleep(random.randint(0, 10))
now = discord.utils.utcnow()
diff = (self.ETA - now).total_seconds()
if diff < -86400:
return self.log.debug("Countdown long expired.")
if diff > 3600:
hours, remainder = map(round, divmod(diff, 3600))
minutes, seconds = map(round, divmod(remainder, 60))
message = f"+ {hours} hours, {minutes} minutes, and {seconds} seconds."
elif diff > 60:
minutes, seconds = map(round, divmod(diff, 60))
message = f"+ {minutes} minutes and {seconds} seconds."
elif diff >= 0:
message = f"+ {round(diff)} seconds."
else:
message = "Results time!"
if self.countdown_message:
try:
return await self.countdown_message.edit(
content=f"```diff\n{message}```"
)
except discord.HTTPException:
self.log.exception("Failed to edit countdown message.")
self.countdown_message = await channel.send(
f"```diff\n{message}```"
)
self.log.debug("Sent countdown message")
def process_soup(self, soup: BeautifulSoup) -> dict[str, list[int]] | None:
good_soup = soup.find(attrs={"data-testid": "election-banner-results-bar"})