Adding project

This commit is contained in:
chrisbell committed 2026-11-10 17:40:24 -05:00
commit 3bd18050cb
9 files changed
+730

No files matched your search

View File
Whitespace-only changes.
+133
View File
@@ -0,0 +1,133 @@
import discord
from discord import app_commands
from discord.ext import commands
import config
import data
class Channels(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(
name="setup_county_channels",
description="Create private county channels grouped by region",
)
@app_commands.guilds(config.GUILD)
@app_commands.default_permissions(manage_roles=True)
@app_commands.guild_only()
async def setup_county_channels(self, interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True)
guild = interaction.guild
roles = {r.name: r for r in guild.roles}
assigned = [c for cs in data.REGION_COUNTIES.values() for c in cs]
dups = sorted({c for c in assigned if assigned.count(c) > 1})
unassigned = sorted(set(data.COUNTIES) - set(assigned))
unknown = sorted(set(assigned) - set(data.COUNTIES))
if dups or unassigned or unknown:
await interaction.followup.send(
"REGION_COUNTIES needs fixing. "
f"Duplicates: {dups or 'none'}. Unassigned: {unassigned or 'none'}. "
f"Unknown names: {unknown or 'none'}.",
ephemeral=True,
)
return
required = data.COUNTIES + list(data.REGION_COUNTIES)
missing = [n for n in required if n not in roles]
if missing:
await interaction.followup.send(
f"{len(missing)} roles are missing ({', '.join(missing[:10])}...). "
"Run /setup_roles first.",
ephemeral=True,
)
return
notes = []
created = updated = 0
try:
founder = roles.get(data.FOUNDER_ROLE)
if founder is None:
founder = await guild.create_role(
name=data.FOUNDER_ROLE, reason="County channels setup"
)
notes.append(
f"Created the {data.FOUNDER_ROLE} role. Assign it to people yourself."
)
access = discord.PermissionOverwrite(
view_channel=True, send_messages=True, read_message_history=True
)
hidden = discord.PermissionOverwrite(view_channel=False)
# Found by name so channels from earlier runs (including the old
# "Counties: A to B" categories) are moved rather than duplicated.
existing = {
c.name: c
for c in guild.text_channels
if c.category
and (
c.category.name.startswith("Counties:")
or c.category.name.endswith(" Alabama")
)
}
for region, counties in data.REGION_COUNTIES.items():
cat_name = f"{region} Alabama"
category = discord.utils.get(guild.categories, name=cat_name)
if category is None:
category = await guild.create_category(
cat_name,
overwrites={
guild.default_role: hidden,
founder: access,
guild.me: access,
},
reason="County channels setup",
)
wanted = [(f"{region.lower()}-general", roles[region])]
wanted += [(c.lower().replace(" ", "-"), roles[c]) for c in counties]
for chan_name, role in wanted:
overwrites = {
guild.default_role: hidden,
role: access,
founder: access,
guild.me: access,
}
channel = existing.get(chan_name)
if channel is None:
await guild.create_text_channel(
chan_name,
category=category,
overwrites=overwrites,
reason="County channels setup",
)
created += 1
else:
await channel.edit(category=category, overwrites=overwrites)
updated += 1
for cat in guild.categories:
if cat.name.startswith("Counties:") and not cat.channels:
notes.append(
f'The old category "{cat.name}" is empty now. You can delete it.'
)
except discord.Forbidden:
await interaction.followup.send(
"I'm missing a permission (Manage Channels and Manage Roles are needed).",
ephemeral=True,
)
return
msg = f"Created {created} channels, updated {updated}."
if notes:
msg += "\n" + "\n".join(notes)
await interaction.followup.send(msg[:1900], ephemeral=True)
async def setup(bot):
await bot.add_cog(Channels(bot))
+130
View File
@@ -0,0 +1,130 @@
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)
if (
now.hour != DAILY_HOUR
or now.minute >= 5
or self.last_posted == now.date()
):
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)
self.last_posted = now.date()
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))
+152
View File
@@ -0,0 +1,152 @@
import discord
from discord import app_commands
from discord.ext import commands
import config
import data
CATEGORY_CHOICES = [app_commands.Choice(name="All panels", value="all")] + [
app_commands.Choice(name=c["title"], value=c["key"]) for c in data.CATEGORIES
]
def make_groups(cat):
"""Split a category into dropdown groups of at most 25 roles each."""
names = cat["roles"]
if len(names) <= 25:
return [(cat["key"], names, cat["placeholder"])]
chunks = [names[i : i + 25] for i in range(0, len(names), 25)]
return [
(f"{cat['key']}:{i}", chunk, f"{cat['placeholder']}: {chunk[0]} to {chunk[-1]}")
for i, chunk in enumerate(chunks)
]
class GroupSelect(discord.ui.Select):
def __init__(self, key, role_names, placeholder, multi, required):
super().__init__(
custom_id=f"roles:{key}",
placeholder=placeholder,
min_values=1 if required else 0,
max_values=len(role_names) if multi else 1,
options=[discord.SelectOption(label=n, value=n) for n in role_names],
)
self.role_names = role_names
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer()
member = interaction.user
by_name = {r.name: r for r in interaction.guild.roles}
missing = [n for n in self.role_names if n not in by_name]
if missing:
await interaction.followup.send(
"Some roles don't exist yet. An admin needs to run /setup_roles.",
ephemeral=True,
)
return
chosen = set(self.values)
current = {r.name for r in member.roles}
to_add = [by_name[n] for n in chosen if n not in current]
to_remove = [
by_name[n] for n in self.role_names if n not in chosen and n in current
]
try:
if to_add:
await member.add_roles(*to_add, reason="Self-assigned via panel")
if to_remove:
await member.remove_roles(*to_remove, reason="Self-assigned via panel")
except discord.Forbidden:
await interaction.followup.send(
"I couldn't change your roles. An admin needs to move my role "
"above these roles in Server Settings -> Roles.",
ephemeral=True,
)
def build_view(cat):
view = discord.ui.View(timeout=None)
for key, names, placeholder in make_groups(cat):
view.add_item(
GroupSelect(key, names, placeholder, cat["multi"], cat["required"])
)
return view
class Roles(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def cog_load(self):
for cat in data.CATEGORIES:
self.bot.add_view(build_view(cat))
@app_commands.command(
name="setup_roles", description="Create any roles that don't exist yet"
)
@app_commands.guilds(config.GUILD)
@app_commands.default_permissions(manage_roles=True)
@app_commands.guild_only()
async def setup_roles(self, interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True)
guild = interaction.guild
existing = {r.name for r in guild.roles}
created = []
try:
for cat in data.CATEGORIES:
for name in cat["roles"]:
if name in existing:
continue
kwargs = {}
if cat["color"] is not None:
kwargs["colour"] = discord.Colour(cat["color"])
await guild.create_role(
name=name, reason="Alabama Progress setup", **kwargs
)
existing.add(name)
created.append(name)
except discord.Forbidden:
await interaction.followup.send(
"I'm missing the Manage Roles permission.", ephemeral=True
)
return
if created:
msg = f"Created {len(created)} roles: " + ", ".join(created)
else:
msg = "All roles already exist. Nothing to do."
await interaction.followup.send(msg[:1900], ephemeral=True)
@app_commands.command(
name="post_panels", description="Post the role dropdown panels in this channel"
)
@app_commands.guilds(config.GUILD)
@app_commands.describe(category="Which panel to post (default: all)")
@app_commands.choices(category=CATEGORY_CHOICES)
@app_commands.default_permissions(manage_roles=True)
@app_commands.guild_only()
async def post_panels(
self, interaction: discord.Interaction, category: str = "all"
):
await interaction.response.defer(ephemeral=True)
existing = {r.name for r in interaction.guild.roles}
cats = [c for c in data.CATEGORIES if category in ("all", c["key"])]
missing = [n for c in cats for n in c["roles"] if n not in existing]
if missing:
await interaction.followup.send(
f"{len(missing)} roles don't exist yet. Run /setup_roles first.",
ephemeral=True,
)
return
for cat in cats:
await interaction.channel.send(content=cat["text"], view=build_view(cat))
await interaction.followup.send(f"Posted {len(cats)} panel(s).", ephemeral=True)
async def setup(bot):
await bot.add_cog(Roles(bot))