125 lines
4.1 KiB
Python
125 lines
4.1 KiB
Python
from datetime import datetime, timedelta, timezone
|
|
from zoneinfo import ZoneInfo
|
|
|
|
import discord
|
|
from discord import app_commands
|
|
from discord.ext import commands, tasks
|
|
|
|
import config
|
|
|
|
try:
|
|
CENTRAL = ZoneInfo("America/Chicago")
|
|
except Exception:
|
|
CENTRAL = timezone(timedelta(hours=-6))
|
|
|
|
ELECTION_NAME = "Alabama Primary Election"
|
|
ELECTION_DATE = datetime(2028, 3, 7, tzinfo=CENTRAL)
|
|
|
|
DAILY_CHANNEL = "52419sqmi"
|
|
DAILY_HOUR = 9
|
|
|
|
|
|
def countdown_embed():
|
|
"""Return the countdown embed, or None if the election has passed."""
|
|
now = datetime.now(CENTRAL)
|
|
days = (ELECTION_DATE.date() - now.date()).days
|
|
if days < 0:
|
|
return None
|
|
|
|
date_text = (
|
|
f"{ELECTION_DATE.strftime('%A, %B')} {ELECTION_DATE.day}, {ELECTION_DATE.year}"
|
|
)
|
|
ts = int(ELECTION_DATE.timestamp())
|
|
|
|
if days == 0:
|
|
title = f"🗳️ {ELECTION_NAME} IS TODAY! GO VOTE!"
|
|
body = f"**{date_text}**"
|
|
else:
|
|
weeks, extra = divmod(days, 7)
|
|
title = f"🗳️ {days:,} day{'s' if days != 1 else ''} until Election Day"
|
|
body = (
|
|
f"{ELECTION_NAME}: **{date_text}**\n"
|
|
f"That's {weeks:,} weeks and {extra} days, or <t:{ts}:R>."
|
|
)
|
|
|
|
embed = discord.Embed(
|
|
title=title, description=body, colour=discord.Colour(config.LIGHT_BLUE)
|
|
)
|
|
embed.set_footer(text="Source: Alabama Secretary of State election calendar")
|
|
return embed
|
|
|
|
|
|
class Countdown(commands.Cog):
|
|
def __init__(self, bot):
|
|
self.bot = bot
|
|
self.last_posted = None
|
|
|
|
async def cog_load(self):
|
|
self.daily_countdown.start()
|
|
|
|
async def cog_unload(self):
|
|
self.daily_countdown.cancel()
|
|
|
|
@app_commands.command(name="countdown", description="Days until the next election")
|
|
@app_commands.guilds(config.GUILD)
|
|
@app_commands.guild_only()
|
|
@app_commands.checks.cooldown(1, 30.0, key=lambda i: i.channel_id)
|
|
async def countdown(self, interaction: discord.Interaction):
|
|
embed = countdown_embed()
|
|
if embed is None:
|
|
await interaction.response.send_message(
|
|
f"The {ELECTION_NAME} has passed. "
|
|
"An admin needs to update ELECTION_DATE in the bot.",
|
|
ephemeral=True,
|
|
)
|
|
return
|
|
await interaction.response.send_message(embed=embed)
|
|
|
|
@countdown.error
|
|
async def countdown_error(self, interaction: discord.Interaction, error):
|
|
if isinstance(error, app_commands.CommandOnCooldown):
|
|
await interaction.response.send_message(
|
|
f"Someone just ran this here. Try again in {error.retry_after:.0f}s.",
|
|
ephemeral=True,
|
|
)
|
|
else:
|
|
raise error
|
|
|
|
@tasks.loop(minutes=1)
|
|
async def daily_countdown(self):
|
|
"""Posts once per day during the 9:00-9:04 Central window."""
|
|
try:
|
|
now = datetime.now(CENTRAL)
|
|
today = now.date().isoformat()
|
|
if now.hour != DAILY_HOUR or now.minute >= 5:
|
|
return
|
|
if await self.bot.db.get_setting("countdown_last_posted") == today:
|
|
return
|
|
|
|
embed = countdown_embed()
|
|
if embed is None:
|
|
return
|
|
|
|
guild = self.bot.get_guild(config.GUILD.id)
|
|
channel = (discord.utils.get(guild.text_channels, name=DAILY_CHANNEL)
|
|
if guild else None)
|
|
if channel is None:
|
|
print(f"daily_countdown: no channel named {DAILY_CHANNEL!r}", flush=True)
|
|
return
|
|
|
|
await channel.send(embed=embed)
|
|
await self.bot.db.set_setting("countdown_last_posted", today)
|
|
print(f"daily_countdown: posted in #{DAILY_CHANNEL}", flush=True)
|
|
except discord.HTTPException as e:
|
|
print(f"daily_countdown: could not post: {e}", flush=True)
|
|
except Exception as e:
|
|
print(f"daily_countdown: unexpected error: {e!r}", flush=True)
|
|
|
|
@daily_countdown.before_loop
|
|
async def before_daily_countdown(self):
|
|
await self.bot.wait_until_ready()
|
|
|
|
|
|
async def setup(bot):
|
|
await bot.add_cog(Countdown(bot))
|