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

+29
View File
@@ -0,0 +1,29 @@
import discord
from discord.ext import commands
import config
EXTENSIONS = [
"cogs.roles",
"cogs.channels",
"cogs.countdown",
]
class Bot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned,
intents=discord.Intents.default(),
)
async def setup_hook(self):
for ext in EXTENSIONS:
await self.load_extension(ext)
await self.tree.sync(guild=config.GUILD)
async def on_ready(self):
print(f"Logged in as {self.user} (id {self.user.id})", flush=True)
Bot().run(config.TOKEN)
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))
+8
View File
@@ -0,0 +1,8 @@
import os
import discord
TOKEN = os.environ["DISCORD_BOT_TOKEN"]
GUILD = discord.Object(id=int(os.environ["DISCORD_GUILD_ID"]))
LIGHT_BLUE = 0x87CEEB
+219
View File
@@ -0,0 +1,219 @@
import config
FOUNDER_ROLE = "Founder"
COUNTIES = [
"Autauga",
"Baldwin",
"Barbour",
"Bibb",
"Blount",
"Bullock",
"Butler",
"Calhoun",
"Chambers",
"Cherokee",
"Chilton",
"Choctaw",
"Clarke",
"Clay",
"Cleburne",
"Coffee",
"Colbert",
"Conecuh",
"Coosa",
"Covington",
"Crenshaw",
"Cullman",
"Dale",
"Dallas",
"DeKalb",
"Elmore",
"Escambia",
"Etowah",
"Fayette",
"Franklin",
"Geneva",
"Greene",
"Hale",
"Henry",
"Houston",
"Jackson",
"Jefferson",
"Lamar",
"Lauderdale",
"Lawrence",
"Lee",
"Limestone",
"Lowndes",
"Macon",
"Madison",
"Marengo",
"Marion",
"Marshall",
"Mobile",
"Monroe",
"Montgomery",
"Morgan",
"Perry",
"Pickens",
"Pike",
"Randolph",
"Russell",
"Saint Clair",
"Shelby",
"Sumter",
"Talladega",
"Tallapoosa",
"Tuscaloosa",
"Walker",
"Washington",
"Wilcox",
"Winston",
]
REGION_COUNTIES = {
"North": [
"Lauderdale",
"Colbert",
"Franklin",
"Marion",
"Lamar",
"Madison",
"Limestone",
"Morgan",
"Lawrence",
"Cullman",
"Winston",
"Jackson",
"Marshall",
"DeKalb",
"Cherokee",
"Etowah",
],
"West": [
"Bibb",
"Choctaw",
"Fayette",
"Greene",
"Hale",
"Marengo",
"Pickens",
"Sumter",
"Tuscaloosa",
"Perry",
],
"South": [
"Mobile",
"Baldwin",
"Houston",
"Dale",
"Coffee",
"Geneva",
"Henry",
"Covington",
"Escambia",
"Conecuh",
"Monroe",
"Clarke",
"Washington",
"Pike",
"Barbour",
"Butler",
"Crenshaw",
"Wilcox",
],
"Central": [
"Jefferson",
"Shelby",
"Saint Clair",
"Blount",
"Walker",
"Montgomery",
"Autauga",
"Elmore",
"Chilton",
"Dallas",
"Lowndes",
],
"East": [
"Lee",
"Russell",
"Chambers",
"Tallapoosa",
"Randolph",
"Macon",
"Calhoun",
"Cleburne",
"Clay",
"Talladega",
"Coosa",
"Bullock",
],
}
# Order here is the order panels are posted in.
# multi=False swaps the old choice for the new one; multi=True allows any number.
# color=None uses Discord's default role color.
CATEGORIES = [
{
"key": "party",
"title": "Party affiliation",
"text": "**Party affiliation** (required)\nPick the one that fits best.",
"placeholder": "Choose your party affiliation",
"roles": [
"Democrat",
"Republican",
"Independent",
"Libertarian",
"Green",
"Other Third Party",
],
"multi": False,
"required": True,
"color": None,
},
{
"key": "region",
"title": "Region",
"text": "**Region** (required)\nWhich part of Alabama are you in?",
"placeholder": "Choose your region",
"roles": ["North", "Central", "South", "East", "West"],
"multi": False,
"required": True,
"color": None,
},
{
"key": "counties",
"title": "Counties",
"text": (
"**County** (optional)\nPick any that apply. "
"(Counties are split across three menus alphabetically)."
),
"placeholder": "Counties",
"roles": COUNTIES,
"multi": True,
"required": False,
"color": config.LIGHT_BLUE,
},
{
"key": "age",
"title": "Age range",
"text": "**Age range** (optional)",
"placeholder": "Choose your age range",
"roles": ["18-29", "30-49", "50-64", "65+"],
"multi": False,
"required": False,
"color": None,
},
{
"key": "gender",
"title": "Gender identity",
"text": "**Gender identity** (optional)",
"placeholder": "Choose your gender identity",
"roles": ["Male", "Female", "Non-binary", "Gender fluid", "Ask for pronouns"],
"multi": True,
"required": False,
"color": None,
},
]
Generated
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1794042290,
"narHash": "sha256-ziZn2PvCJE5JEEpqTdxXwJpPB+L3YqoCpTAMCzyaP3U=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "f4a03c008967841f2a0b3cb7c436fc6fc31671f6",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+32
View File
@@ -0,0 +1,32 @@
{
description = "Alabama Progress Discord bot";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
outputs = { self, nixpkgs }:
let
system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system};
python = pkgs.python3.withPackages (ps: [ ps.discordpy ]);
in {
devShells.${system}.default = pkgs.mkShell {
packages = [ python pkgs.ruff ];
shellHook = ''
secrets=/var/lib/secrets
if [ -r "$secrets/discord_token" ]; then
export DISCORD_BOT_TOKEN="$(cat "$secrets/discord_token")"
else
echo "warning: cannot read $secrets/discord_token" >&2
fi
if [ -r "$secrets/discord_guild_id" ]; then
export DISCORD_GUILD_ID="$(cat "$secrets/discord_guild_id")"
else
echo "warning: cannot read $secrets/discord_guild_id" >&2
fi
'';
};
};
}