From dcdf88a14a9f74e19895a799c37a40b7a118daeb Mon Sep 17 00:00:00 2001 From: chris bell Date: Fri, 20 Nov 2026 19:40:39 -0600 Subject: [PATCH] application stuff --- bot/__main__.py | 1 + bot/cogs/applications.py | 273 +++++++++++++++++++++++++++++++++++++++ bot/cogs/settings.py | 15 +++ bot/db.py | 9 ++ bot/guildconf.py | 1 + 5 files changed, 299 insertions(+) create mode 100644 bot/cogs/applications.py diff --git a/bot/__main__.py b/bot/__main__.py index 6947814..a43fb0a 100644 --- a/bot/__main__.py +++ b/bot/__main__.py @@ -13,6 +13,7 @@ EXTENSIONS = [ "cogs.roles", "cogs.channels", "cogs.countdown", + "cogs.applications", ] diff --git a/bot/cogs/applications.py b/bot/cogs/applications.py new file mode 100644 index 0000000..0fcdb6c --- /dev/null +++ b/bot/cogs/applications.py @@ -0,0 +1,273 @@ +"""Website join applications. + +The site POSTs JSON to /api/join. The bot posts an embed with Accept/Decline +buttons to the applications channel. The applicant gets a random code and polls +/api/join/status with it. Only a hash of the code, a status and (once accepted) +a single-use invite URL are stored in SQLite. Answers live only in the Discord +message, which is cut down to username + decision after review. +""" +import asyncio +import hashlib +import os +import secrets +import time +from collections import deque + +import discord +from aiohttp import web +from discord.ext import commands, tasks + +import config +import guildconf + +PORT = int(os.environ.get("JOIN_API_PORT", "8787")) +SITE_ORIGIN = os.environ.get("SITE_ORIGIN", "https://alp.bellsworne.tech") + +KEEP_SECONDS = 14 * 86400 # rows (and invite links) are deleted after this +INVITE_AGE = 7 * 86400 # accepted invites expire after this +GLOBAL_LIMIT = 10 # max applications per minute, all users +USER_COOLDOWN = 600 # seconds between applications for one username + +# Mirrors the maxlength values in pages/join.html +LIMITS = {"discord": 64, "name": 100, "interest": 1000, + "references": 100, "organisation": 100, "links": 1000} +REQUIRED = ("discord", "interest") + + +def code_hash(code): + return hashlib.sha256(code.encode()).hexdigest() + + +def clean(text): + """Make user text safe to show in an embed (no mentions, no markdown/links).""" + return discord.utils.escape_mentions(discord.utils.escape_markdown(text))[:1024] + + +def reply(data, status=200): + return web.json_response(data, status=status) + + +def parse_application(data): + if not isinstance(data, dict): + return None, "Invalid request." + out = {} + for key, limit in LIMITS.items(): + value = data.get(key, "") + if not isinstance(value, str): + return None, "Invalid request." + value = value.strip() + if len(value) > limit: + return None, "One of your answers is too long." + out[key] = value + if any(not out[k] for k in REQUIRED) or data.get("vote_registration") not in ("yes", "no"): + return None, "Please fill in all required fields." + out["vote_registration"] = data["vote_registration"] + return out, None + + +def build_embed(app): + embed = discord.Embed(title=f"Application: {app['discord']}"[:256], + color=config.LIGHT_BLUE, timestamp=discord.utils.utcnow()) + fields = [ + ("Name", app["name"]), + ("Registered to vote in Alabama", app["vote_registration"].capitalize()), + ("Why they want to join", app["interest"]), + ("Referrals", app["references"]), + ("Political organisations", app["organisation"]), + ("Social media / links", app["links"]), + ] + for label, value in fields: + embed.add_field(name=label, value=clean(value) or "\u2014", inline=False) + return embed + + +class ReviewButton(discord.ui.DynamicItem[discord.ui.Button], + template=r"alp:app:(?Paccept|decline):(?P[0-9]+)"): + """Persistent button: the application id lives in the custom_id, so these + keep working after a restart.""" + + def __init__(self, action, app_id): + accept = action == "accept" + super().__init__(discord.ui.Button( + label="Accept" if accept else "Decline", + style=discord.ButtonStyle.success if accept else discord.ButtonStyle.danger, + custom_id=f"alp:app:{action}:{app_id}")) + self.action = action + self.app_id = app_id + + @classmethod + async def from_custom_id(cls, interaction, item, match, /): + return cls(match["action"], int(match["id"])) + + async def interaction_check(self, interaction): + if await guildconf.is_mod(interaction.client, interaction.user): + return True + await interaction.response.send_message( + "You need to be a moderator to review applications.", ephemeral=True) + return False + + async def callback(self, interaction): + cog = interaction.client.get_cog("Applications") + await cog.review(interaction, self.action, self.app_id) + + +class Applications(commands.Cog): + def __init__(self, bot): + self.bot = bot + self.runner = None + self.lock = asyncio.Lock() + self.recent = deque() + self.cooldowns = {} + + async def cog_load(self): + self.bot.add_dynamic_items(ReviewButton) + app = web.Application(client_max_size=16 * 1024) + app.router.add_post("/api/join", self.handle_join) + app.router.add_post("/api/join/status", self.handle_status) + self.runner = web.AppRunner(app, access_log=None) # never log requests + await self.runner.setup() + await web.TCPSite(self.runner, "127.0.0.1", PORT).start() + self.cleanup.start() + + async def cog_unload(self): + self.cleanup.cancel() + self.bot.remove_dynamic_items(ReviewButton) + if self.runner: + await self.runner.cleanup() + + @tasks.loop(hours=1) + async def cleanup(self): + await self.bot.db.execute( + "DELETE FROM applications WHERE created_at < ?", + int(time.time()) - KEEP_SECONDS) + + # ---- HTTP ---- + + @staticmethod + def origin_ok(request): + return request.headers.get("Origin") == SITE_ORIGIN + + @staticmethod + async def read_json(request): + if request.content_type != "application/json": + return None + try: + return await request.json() + except Exception: + return None + + async def channel(self): + guild = self.bot.get_guild(config.GUILD.id) + channel_id = await guildconf.get_id(self.bot, guildconf.JOIN_CHANNEL) + return guild.get_channel(channel_id) if guild and channel_id else None + + async def handle_join(self, request): + if not self.origin_ok(request): + return reply({"error": "Forbidden."}, 403) + data = await self.read_json(request) + + # Honeypot: pretend it worked so bots don't learn they were caught. + if isinstance(data, dict) and data.get("website"): + return reply({"ok": True, "code": secrets.token_urlsafe(24)}) + + app, error = parse_application(data) + if error: + return reply({"error": error}, 400) + + now = time.time() + while self.recent and now - self.recent[0] > 60: + self.recent.popleft() + self.cooldowns = {k: v for k, v in self.cooldowns.items() if v > now} + key = app["discord"].lower() + if len(self.recent) >= GLOBAL_LIMIT: + return reply({"error": "We're getting a lot of applications right now. " + "Please try again in a few minutes."}, 429) + if key in self.cooldowns: + return reply({"error": "An application for that username was just " + "submitted. Please wait a few minutes."}, 429) + + channel = await self.channel() + if channel is None: + return reply({"error": "Applications are closed right now."}, 503) + + code = secrets.token_urlsafe(24) + app_id = await self.bot.db.execute( + "INSERT INTO applications (code_hash, created_at) VALUES (?, ?)", + code_hash(code), int(now)) + view = discord.ui.View(timeout=None) + view.add_item(ReviewButton("accept", app_id)) + view.add_item(ReviewButton("decline", app_id)) + try: + await channel.send(embed=build_embed(app), view=view, + allowed_mentions=discord.AllowedMentions.none()) + except discord.HTTPException: + await self.bot.db.execute("DELETE FROM applications WHERE id = ?", app_id) + return reply({"error": "We couldn't submit your application. " + "Please try again later."}, 503) + + self.recent.append(now) + self.cooldowns[key] = now + USER_COOLDOWN + return reply({"ok": True, "code": code}) + + async def handle_status(self, request): + # POST (not GET) so the code never appears in a URL or access log. + if not self.origin_ok(request): + return reply({"error": "Forbidden."}, 403) + data = await self.read_json(request) + code = data.get("code") if isinstance(data, dict) else None + if not isinstance(code, str) or not 8 <= len(code) <= 64: + return reply({"status": "unknown"}, 404) + row = await self.bot.db.fetchone( + "SELECT status, invite_url FROM applications WHERE code_hash = ?", + code_hash(code)) + if row is None: + return reply({"status": "unknown"}, 404) + return reply({"status": row["status"], "invite": row["invite_url"]}) + + # ---- Review ---- + + async def invite_channel(self, interaction): + channel_id = await guildconf.get_id(self.bot, guildconf.VERIFY_CHANNEL) + found = interaction.guild.get_channel(channel_id) if channel_id else None + return found or interaction.guild.system_channel or interaction.channel + + async def review(self, interaction, action, app_id): + accept = action == "accept" + async with self.lock: # two mods clicking at once: only the first wins + row = await self.bot.db.fetchone( + "SELECT status FROM applications WHERE id = ?", app_id) + if row is None or row["status"] != "pending": + await interaction.response.send_message( + "This application was already handled or has expired.", + ephemeral=True) + return + await interaction.response.defer() + invite_url = None + if accept: + try: + channel = await self.invite_channel(interaction) + invite = await channel.create_invite( + max_uses=1, max_age=INVITE_AGE, unique=True, + reason=f"Application accepted by {interaction.user}") + invite_url = invite.url + except discord.HTTPException: + await interaction.followup.send( + "I couldn't create an invite. I need Create Invite " + "permission in the verify channel.", ephemeral=True) + return + await self.bot.db.execute( + "UPDATE applications SET status = ?, invite_url = ? WHERE id = ?", + "accepted" if accept else "declined", invite_url, app_id) + + # Cut the embed down to username + decision; the answers are discarded. + username = interaction.message.embeds[0].title.removeprefix("Application: ") + embed = discord.Embed( + title=f"Application: {username}", + description=f"{'Accepted' if accept else 'Declined'} by " + f"{interaction.user.mention} on ", + color=0x318F31 if accept else 0x952626) + await interaction.edit_original_response(embed=embed, view=None) + + +async def setup(bot): + await bot.add_cog(Applications(bot)) \ No newline at end of file diff --git a/bot/cogs/settings.py b/bot/cogs/settings.py index 7b25a19..1387f58 100644 --- a/bot/cogs/settings.py +++ b/bot/cogs/settings.py @@ -66,6 +66,21 @@ class Settings(commands.Cog): await self.bot.db.set_setting(key, role.id) await interaction.response.send_message( f"{label} role set to {role.mention}.", ephemeral=True) + + @group.command(name="applications", description="Set the channel for website join applications") + @app_commands.describe(channel="Private channel where applications are posted") + @app_commands.checks.has_permissions(manage_guild=True) + async def applications(self, interaction: discord.Interaction, + channel: discord.TextChannel): + perms = channel.permissions_for(interaction.guild.me) + if not (perms.view_channel and perms.send_messages and perms.embed_links): + await interaction.response.send_message( + f"I need View Channel, Send Messages and Embed Links in {channel.mention}.", + ephemeral=True) + return + await self.bot.db.set_setting(guildconf.JOIN_CHANNEL, channel.id) + await interaction.response.send_message( + f"Applications will be posted in {channel.mention}.", ephemeral=True) async def setup(bot): diff --git a/bot/db.py b/bot/db.py index 8d730d2..c3affb3 100644 --- a/bot/db.py +++ b/bot/db.py @@ -37,6 +37,15 @@ MIGRATIONS = [ ALTER TABLE pending_verifications ADD COLUMN rules_ok INTEGER NOT NULL DEFAULT 0; ALTER TABLE pending_verifications ADD COLUMN choices TEXT NOT NULL DEFAULT ''; """, + """ + CREATE TABLE applications ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + code_hash TEXT NOT NULL UNIQUE, + status TEXT NOT NULL DEFAULT 'pending', + invite_url TEXT, + created_at INTEGER NOT NULL + ); + """, ] diff --git a/bot/guildconf.py b/bot/guildconf.py index 142651c..f2c5e0c 100644 --- a/bot/guildconf.py +++ b/bot/guildconf.py @@ -9,6 +9,7 @@ VERIFY_CHANNEL = "verify_channel" VERIFY_REVIEW = "verify_review_channel" VERIFY_ENABLED = "verify_enabled" VERIFY_RULES_MSG = "verify_rules_message" +JOIN_CHANNEL = "join_applications_channel" async def get_id(bot, key):