update verification process

This commit is contained in:
chrisbell committed 2026-11-10 18:49:55 -06:00
1 parent 65bbaff0cb
commit 744c4f47f9
5 files changed
+279 -29

No files matched your search

+124 -29
View File
@@ -1,3 +1,4 @@
import json
import time
from collections import deque
from datetime import datetime, timedelta, timezone
@@ -7,7 +8,9 @@ from discord import app_commands
from discord.ext import commands, tasks
import config
import data
import guildconf
import onboarding
VERIFY_TIMEOUT = 24 * 3600
REVIEW_TIMEOUT = 7 * 24 * 3600
@@ -16,10 +19,7 @@ YOUNG_ACCOUNT = timedelta(days=30)
SPIKE_JOINS = 5
SPIKE_WINDOW = 60
PANEL_TEXT = (
"**Welcome!**\n"
"Press the button below to get access to the rest of the server."
)
RULES_EMOJI = "\u2705"
REVIEW_ACTIONS = {
"approve": ("Approve", discord.ButtonStyle.success),
@@ -51,9 +51,9 @@ class VerifyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Verify", style=discord.ButtonStyle.success,
@discord.ui.button(label="Continue", style=discord.ButtonStyle.success,
custom_id="verify:start")
async def verify(self, interaction: discord.Interaction, button):
async def start(self, interaction: discord.Interaction, button):
await interaction.client.get_cog("Verification").handle_verify(interaction)
@@ -138,7 +138,30 @@ class Verification(commands.Cog):
if not member.bot and role not in member.roles:
await self.track(member)
async def send_review(self, member, flags, joined_at):
async def grant(self, member, reason):
"""Gives the member their chosen roles plus Verified in one call."""
guild = member.guild
row = await self.bot.db.fetchone(
"SELECT choices FROM pending_verifications WHERE user_id = ?", member.id)
names = json.loads(row["choices"]) if row and row["choices"] else []
by_name = {r.name: r for r in guild.roles}
roles = [by_name[n] for n in names if n in by_name]
roles.append(await self.verified_role(guild))
await member.add_roles(*roles, reason=reason)
async def clear_rules_reaction(self, guild, user_id):
channel_id = await guildconf.get_id(self.bot, guildconf.VERIFY_CHANNEL)
message_id = await guildconf.get_id(self.bot, guildconf.VERIFY_RULES_MSG)
channel = guild.get_channel(channel_id) if channel_id else None
if channel is None or not message_id:
return
try:
await channel.get_partial_message(message_id).remove_reaction(
RULES_EMOJI, discord.Object(id=user_id))
except discord.HTTPException:
pass
async def send_review(self, member, flags, joined_at, choices):
channel = await self.review_channel(member.guild)
if channel is None:
return False
@@ -153,6 +176,8 @@ class Verification(commands.Cog):
embed.add_field(name="Joined", value=f"<t:{joined_at}:R>")
embed.add_field(
name="Flags", value="\n".join(f"- {f}" for f in flags), inline=False)
embed.add_field(
name="Selected roles", value=", ".join(choices) or "None", inline=False)
embed.set_footer(text=f"User ID: {member.id}")
try:
await channel.send(embed=embed, view=review_view(member.id))
@@ -161,18 +186,17 @@ class Verification(commands.Cog):
return True
async def handle_verify(self, interaction):
await interaction.response.defer(ephemeral=True)
member, guild = interaction.user, interaction.guild
role = await self.verified_role(guild)
async def reply(text):
await interaction.followup.send(text, ephemeral=True)
async def say(text):
await interaction.response.send_message(text, ephemeral=True)
if role is None or not await self.enabled():
await reply("Verification isn't active right now.")
await say("Verification isn't active right now.")
return
if role in member.roles:
await reply("You're already verified.")
await say("You're already verified.")
return
await self.track(member)
@@ -180,13 +204,43 @@ class Verification(commands.Cog):
"SELECT * FROM pending_verifications WHERE user_id = ?", member.id)
if row["in_review"]:
await reply("A moderator is already reviewing your account. "
"You'll get access once it's approved.")
await say("A moderator is already reviewing your account. "
"You'll get access once it's approved.")
return
if not row["rules_ok"]:
await say(f"Please react with {RULES_EMOJI} on the rules message first. "
"If it's already there, remove it, add it again, "
"then press Continue.")
return
missing = onboarding.missing_roles(guild)
if missing:
print(f"verify: missing roles: {missing[:10]}", flush=True)
await say("Setup isn't finished yet. Please let a moderator know.")
return
state = onboarding.State(self)
await interaction.response.send_message(
onboarding.PARTY_TEXT, view=onboarding.party_view(state), ephemeral=True)
async def complete(self, interaction, state):
await interaction.response.edit_message(content="Finishing up...", view=None)
member = interaction.user
names = state.role_names()
async def reply(text):
await interaction.edit_original_response(content=text, view=None)
await self.track(member)
await self.bot.db.execute(
"UPDATE pending_verifications SET choices = ? WHERE user_id = ?",
json.dumps(names), member.id)
row = await self.bot.db.fetchone(
"SELECT * FROM pending_verifications WHERE user_id = ?", member.id)
if row["flags"]:
sent = await self.send_review(
member, row["flags"].split(";"), row["joined_at"])
member, row["flags"].split(";"), row["joined_at"], names)
if not sent:
await reply("Verification is temporarily unavailable. "
"Please try again later.")
@@ -200,13 +254,14 @@ class Verification(commands.Cog):
return
try:
await member.add_roles(role, reason="Passed verification")
except discord.HTTPException as e:
print(f"verify: could not add role: {e}", flush=True)
await self.grant(member, "Passed verification")
except (discord.HTTPException, AttributeError) as e:
print(f"verify: could not grant roles: {e}", flush=True)
await reply("Something went wrong. Please contact a moderator.")
return
await self.forget(member.id)
await reply("You're verified. Welcome!")
await reply("You're verified. Welcome! You can change your roles "
"later from the role panels.")
async def handle_review(self, interaction, action, user_id):
check = guildconf.is_admin if action == "ban" else guildconf.is_mod
@@ -218,7 +273,6 @@ class Verification(commands.Cog):
await interaction.response.defer()
guild = interaction.guild
member = guild.get_member(user_id)
role = await self.verified_role(guild)
by = interaction.user
reason = f"Verification review by {by}"
@@ -228,7 +282,7 @@ class Verification(commands.Cog):
else:
try:
if action == "approve":
await member.add_roles(role, reason=reason)
await self.grant(member, reason)
outcome, colour = "Approved", discord.Colour.green()
elif action == "kick":
await dm(member, f"You were removed from {guild.name} after a "
@@ -247,7 +301,8 @@ class Verification(commands.Cog):
except (discord.Forbidden, AttributeError):
await interaction.followup.send(
"I couldn't do that. Check the Verified role exists and that "
"my role is above the member's.", ephemeral=True)
"my role is above the member's and above the roles they chose.",
ephemeral=True)
return
await self.forget(user_id)
@@ -278,6 +333,27 @@ class Verification(commands.Cog):
async def on_member_remove(self, member):
if member.guild.id == config.GUILD.id:
await self.forget(member.id)
await self.clear_rules_reaction(member.guild, member.id)
async def rules_reaction(self, payload, value):
if (payload.guild_id != config.GUILD.id
or payload.user_id == self.bot.user.id
or str(payload.emoji) != RULES_EMOJI):
return
message_id = await guildconf.get_id(self.bot, guildconf.VERIFY_RULES_MSG)
if payload.message_id != message_id:
return
await self.bot.db.execute(
"UPDATE pending_verifications SET rules_ok = ? WHERE user_id = ?",
value, payload.user_id)
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
await self.rules_reaction(payload, 1)
@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
await self.rules_reaction(payload, 0)
@tasks.loop(minutes=1)
async def sweep(self):
@@ -328,6 +404,7 @@ class Verification(commands.Cog):
or discord.utils.get(guild.roles, name="Verified"))
reason = "Verification setup"
step = "creating the Verified role"
try:
if role is None:
role = await guild.create_role(
@@ -335,26 +412,33 @@ class Verification(commands.Cog):
permissions=discord.Permissions(view_channel=True),
reason=reason)
elif not role.permissions.view_channel:
step = "editing the Verified role"
perms = role.permissions
perms.view_channel = True
await role.edit(permissions=perms, reason=reason)
step = f"setting permissions for @everyone in {channel.mention}"
await channel.set_permissions(
guild.default_role, reason=reason,
overwrite=discord.PermissionOverwrite(
view_channel=True, read_message_history=True,
send_messages=False, add_reactions=False))
add_reactions=True, send_messages=False))
step = f"setting permissions for Verified in {channel.mention}"
await channel.set_permissions(
role, reason=reason,
overwrite=discord.PermissionOverwrite(view_channel=False))
step = f"setting permissions for the bot in {channel.mention}"
await channel.set_permissions(
guild.me, reason=reason,
overwrite=discord.PermissionOverwrite(
view_channel=True, send_messages=True, embed_links=True))
except discord.Forbidden:
view_channel=True, send_messages=True, embed_links=True,
add_reactions=True, read_message_history=True,
manage_messages=True))
except discord.Forbidden as e:
await interaction.followup.send(
"I need Manage Roles and Manage Channels, and my role must be "
"above the Verified role.", ephemeral=True)
f"Discord refused while {step}: {e.text}", ephemeral=True)
return
db = self.bot.db
@@ -369,7 +453,7 @@ class Verification(commands.Cog):
ephemeral=True)
@group.command(name="panel",
description="Post the verification button in the verify channel")
description="Post the rules and Continue button in the verify channel")
@guildconf.admin_only()
async def panel(self, interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True)
@@ -378,7 +462,13 @@ class Verification(commands.Cog):
if channel is None:
await interaction.followup.send("Run `/verify setup` first.", ephemeral=True)
return
await channel.send(content=PANEL_TEXT, view=VerifyView())
message = await channel.send(
embed=discord.Embed(
description=data.RULES_TEXT,
colour=discord.Colour(config.LIGHT_BLUE)),
view=VerifyView())
await message.add_reaction(RULES_EMOJI)
await self.bot.db.set_setting(guildconf.VERIFY_RULES_MSG, message.id)
await interaction.followup.send(f"Posted in {channel.mention}.", ephemeral=True)
@group.command(name="grandfather",
@@ -412,14 +502,19 @@ class Verification(commands.Cog):
guild = interaction.guild
role = await self.verified_role(guild)
channel_id = await guildconf.get_id(self.bot, guildconf.VERIFY_CHANNEL)
rules_id = await guildconf.get_id(self.bot, guildconf.VERIFY_RULES_MSG)
problem = None
if role is None or not channel_id or guild.get_channel(channel_id) is None:
problem = "Run `/verify setup` first."
elif not rules_id:
problem = "Run `/verify panel` first."
elif await self.review_channel(guild) is None:
problem = "Set a mod log (`/config modlog`) or a review channel first."
elif not guild.me.guild_permissions.view_channel:
problem = "My role needs the View Channels permission."
elif onboarding.missing_roles(guild):
problem = "Some self-assign roles are missing. Run `/setup_roles` first."
else:
missing = [m for m in guild.members if role not in m.roles]
if missing:
+28
View File
@@ -217,3 +217,31 @@ CATEGORIES = [
"color": None,
},
]
RULES_TEXT = """\
**Welcome to Alabama Progress**
Be kind, be open-minded, and practice empathy. This server draws people from traditional views to progressive ones, beyond party lines, and everyone is welcome. We support progress, not regressive policy or new age fascism. Progress will never be put behind a paywall. Candidates are here too, so what you say shows them what their constituents really want.
**Rules**
1. **Be kind.** Give folks some grace. We won't see eye to eye on everything. Disagreement is welcome, cruelty is not. Assume good faith, and if someone's tone is unclear, ask.
2. **Don't tone police.** Watch your own words, not everyone else's.
3. **No hate speech. Full stop.** That includes slurs, dehumanizing language, calls for violence, genocide denial, transphobia, antisemitism and conspiracy theories about Jewish people, and bigotry framed as "just asking questions." Criticizing the Israeli state is not antisemitism. Mods make the final call, and severe violations mean immediate removal.
4. **Discord isn't encrypted** and has complied with cops before. Don't post plans or evidence of illegal activity, or anything you wouldn't want screenshotted. Use Signal for sensitive stuff.
5. **Don't snitch.** Don't report members to law enforcement, employers, family, or hostile media, and don't take screenshots out of the server without consent. Violations mean a permanent ban.
6. **No doxxing.** Never share someone's personal info without their consent, even if it's public. That includes candidates.
7. **Don't proselytize.** Discuss, debate, and share theory all you want. Just don't run a conversion campaign on people.
8. **Stay on Alabama.** National and global topics are fine when they affect us here.
9. **No bad faith.** No sealioning, concern trolling, or relitigating settled questions, and don't treat marginalized members as your unpaid educators.
10. **No active cops, feds, or intelligence personnel.** We can't stop you from joining, but you'll be removed if identified.
11. **No AI-generated fakes of real people.** Using AI openly for drafting or research is fine. Deceiving people is not.
12. **Use content warnings and image descriptions** for heavy content. No flash spam.
13. **Progress isn't for sale.** No MLMs, crypto, or courses. Promoting campaigns, candidates, and mutual aid is encouraged.
**Tenets**
Pro: human rights (LGBTQIA+, women's, children's, and immigrants' rights), unions, racial justice, marijuana legalization, prison reform, the environment, voting reform, privacy, and homesteader, renter, and unhoused rights.
Anti: the death penalty, censorship and government overreach, and generative AI.
**Expectations**
This isn't a deconstruction space. If you invite someone, you may be asked to help verify them. Use threads for long conversations, post in the right channel, and expect off-topic comments to be moved or deleted.
React with \u2705 to confirm you've read and understand the rules, tenets, and expectations, then press **Continue**."""
+4
View File
@@ -33,6 +33,10 @@ MIGRATIONS = [
in_review INTEGER NOT NULL DEFAULT 0
);
""",
"""
ALTER TABLE pending_verifications ADD COLUMN rules_ok INTEGER NOT NULL DEFAULT 0;
ALTER TABLE pending_verifications ADD COLUMN choices TEXT NOT NULL DEFAULT '';
""",
]
+1
View File
@@ -8,6 +8,7 @@ VERIFIED_ROLE = "verified_role"
VERIFY_CHANNEL = "verify_channel"
VERIFY_REVIEW = "verify_review_channel"
VERIFY_ENABLED = "verify_enabled"
VERIFY_RULES_MSG = "verify_rules_message"
async def get_id(bot, key):
+122
View File
@@ -0,0 +1,122 @@
import discord
import data
TIMEOUT = 600
PARTY_TEXT = "**Step 1 of 3: Party affiliation** (required)\nPick the one that fits best."
REGION_TEXT = "**Step 2 of 3: Region** (required)\nWhich part of Alabama are you in?"
OPTIONAL_TEXT = (
"**Step 3 of 3: A bit more about you** (all optional)\n"
"Pick any you like, or just press **Finish** to skip them."
)
def roles_in(key):
return next(c for c in data.CATEGORIES if c["key"] == key)["roles"]
def missing_roles(guild):
existing = {r.name for r in guild.roles}
return [n for c in data.CATEGORIES for n in c["roles"] if n not in existing]
class State:
def __init__(self, cog):
self.cog = cog
self.party = None
self.region = None
self.counties = []
self.age = None
self.gender = []
def role_names(self):
names = [self.party, self.region, *self.counties]
if self.age:
names.append(self.age)
names.extend(self.gender)
return names
class ChoiceSelect(discord.ui.Select):
def __init__(self, names, placeholder, on_pick):
super().__init__(
placeholder=placeholder, min_values=1, max_values=1,
options=[discord.SelectOption(label=n, value=n) for n in names])
self.on_pick = on_pick
async def callback(self, interaction: discord.Interaction):
await self.on_pick(interaction, self.values[0])
def party_view(state):
async def pick(interaction, value):
state.party = value
await interaction.response.edit_message(
content=REGION_TEXT, view=region_view(state))
view = discord.ui.View(timeout=TIMEOUT)
view.add_item(ChoiceSelect(
roles_in("party"), "Choose your party affiliation", pick))
return view
def region_view(state):
async def pick(interaction, value):
state.region = value
await interaction.response.edit_message(
content=OPTIONAL_TEXT, view=OptionalView(state))
view = discord.ui.View(timeout=TIMEOUT)
view.add_item(ChoiceSelect(roles_in("region"), "Choose your region", pick))
return view
class PickSelect(discord.ui.Select):
def __init__(self, field, names, placeholder, current, multi):
super().__init__(
placeholder=placeholder,
min_values=0,
max_values=len(names) if multi else 1,
options=[discord.SelectOption(label=n, value=n, default=n in current)
for n in names])
self.field = field
self.multi = multi
async def callback(self, interaction: discord.Interaction):
if self.multi:
value = list(self.values)
else:
value = self.values[0] if self.values else None
setattr(self.view.state, self.field, value)
self.view.render()
await interaction.response.edit_message(view=self.view)
class FinishButton(discord.ui.Button):
def __init__(self):
super().__init__(label="Finish", style=discord.ButtonStyle.success)
async def callback(self, interaction: discord.Interaction):
await self.view.state.cog.complete(interaction, self.view.state)
class OptionalView(discord.ui.View):
def __init__(self, state):
super().__init__(timeout=TIMEOUT)
self.state = state
self.render()
def render(self):
s = self.state
self.clear_items()
self.add_item(PickSelect(
"counties", data.REGION_COUNTIES[s.region],
f"{s.region} counties (optional)", s.counties, multi=True))
self.add_item(PickSelect(
"age", roles_in("age"), "Age range (optional)",
[s.age] if s.age else [], multi=False))
self.add_item(PickSelect(
"gender", roles_in("gender"), "Gender identity (optional)",
s.gender, multi=True))
self.add_item(FinishButton())