A persistent jail for Discord moderation, and the bugs an audit found
Krypton's jail: saved roles, restore on release, rejoin handling, one hierarchy check for every action. Plus the moderation bugs an audit found, from global concurrency to slowmode that added digits.
Before adding a jail to Krypton, I audited the moderation cog it would live in. Some of what turned up is worth sharing, because these bugs are common in Discord bots.
What the audit found
- Global concurrency.
max_concurrency(1, per=BucketType.default)on mute, kick, ban and more meant one command at a time across every server. A pending 20-second kick confirmation blocked kicks everywhere. - Daily limits that were lifetime limits. The check compared against all-time totals, so a moderator was blocked forever after reaching the "daily" number.
- Durations that never parsed.
str.replacewas called without using its result, so10minor1h30mfailed, and there was no 28-day cap for timeouts. - Slowmode added digits.
15sbecame 1 + 5 = 6 seconds. - DMs after the ban. A banned user can no longer receive the bot's DM, so they almost never did.
- Temporary roles never removed, because
asyncio.sleepwas given a tuple. - Half-locked servers. One failing channel aborted "lock all", leaving the rest unlocked.
One target check for every action
Moderation actions now go through one function that refuses: yourself, the bot, the owner, the backup owner, extra owners, higher-ranked staff, members at or above the bot's role, and, when the server does not use the bot's admin lists, members at or above your own top role. Duration and reason parsing, numbered cases and the moderation log are shared helpers too.
How the jail works
jailsaves and removes the member's manageable roles, gives the jail role, posts in the jail channel, DMs them and logs a case. It refuses anyone who would keep Administrator.unjailrestores the saved roles, skipping deleted, managed and above-bot roles, and never restores a role above the moderator's own. It works for members who left, clearing their record.- Rejoining does not escape the jail: the record persists and the jail role is applied again.
- Setup creates a private channel and a jail role, hides every other channel from that role and opens the jail channel to it.
- Each member has a lock, so two moderators acting at once cannot corrupt the saved roles.
Data model
One jail row per member, keyed by bot, server and user, so duplicates are impossible. Cases have per-server counters. Dashboard requests to jail or release someone go into a queue the bot claims with FOR UPDATE SKIP LOCKED, and the schema is created under a PostgreSQL advisory lock so every cluster can start at once. Both patterns are explained in PostgreSQL patterns for multi-process bots.
