From 9f8ac0d29ee62e06d27e45b353c68fb3515c22a8 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Fri, 25 Sep 2026 20:11:00 +0200 Subject: [PATCH 1/2] feat(moderation): add the unmute and unban commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A sanction could be applied but never lifted from Discord, so undoing a mistake meant leaving the bot for the server settings. Both lifts are recorded next to the sanctions they lift, which means widening the moderation history CHECK constraint through a table rebuild. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- README.en.md | 2 + README.md | 2 + src/commands/moderation/unban.js | 62 +++++++++++++++++++ src/commands/moderation/unmute.js | 52 ++++++++++++++++ src/config/constants.js | 2 + .../010-moderation-lifted-actions.sql | 23 +++++++ src/services/moderation/moderation-service.js | 6 +- tests/database.test.js | 15 +++++ 8 files changed, 162 insertions(+), 2 deletions(-) create mode 100644 src/commands/moderation/unban.js create mode 100644 src/commands/moderation/unmute.js create mode 100644 src/database/migrations/010-moderation-lifted-actions.sql diff --git a/README.en.md b/README.en.md index ae2454d..a9e08bb 100644 --- a/README.en.md +++ b/README.en.md @@ -289,6 +289,8 @@ Every command checks the FWS level **and** the matching Discord permission. The | ---------------- | ----------------------------------------- | ------------------ | ----- | ------------------------------------------------------------------ | | `/warn` | `user`, `reason` (required) | Moderate Members | ✅ | Warns, notifies the member by DM and records the action | | `/mute` | `user`, `minutes` (1–40320), `reason` | Moderate Members | ✅ | Temporary timeout (28 days max) + DM notification | +| `/unmute` | `user`, `reason` | Moderate Members | ✅ | Lifts the timeout early (clear message when nobody is muted) | +| `/unban` | `user`, `reason` | Ban Members | ✅ | Lifts the ban, even if the member already left, and DMs them | | `/kick` | `user`, `reason` | Kick Members | ✅ | Kicks from the server and logs the action | | `/ban` | `user`, `reason`, `delete_days` (0–7) | Ban Members | ✅ | Bans (even if the member already left), optional message purge | | `/clear` | `amount` (1–100) | Manage Messages | ✅ | Deletes the last N messages (those older than 14 days are skipped) | diff --git a/README.md b/README.md index ac18f5b..565f630 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,8 @@ Chaque commande vérifie le niveau FWS **et** la permission Discord correspondan | --- | --- | --- | --- | --- | | `/warn` | `user`, `reason` (obligatoires) | Modérer les membres | ✅ | Avertit, prévient le membre en MP et enregistre l'action | | `/mute` | `user`, `minutes` (1–40320), `reason` | Modérer les membres | ✅ | Timeout temporaire (28 j max) + notification en MP | +| `/unmute` | `user`, `reason` | Modérer les membres | ✅ | Lève le timeout avant l’échéance (message clair si la personne n’est pas en exclusion) | +| `/unban` | `user`, `reason` | Bannir | ✅ | Lève le bannissement, même si la personne a déjà quitté, et la prévient en MP | | `/kick` | `user`, `reason` | Expulser | ✅ | Expulse du serveur et journalise l'action | | `/ban` | `user`, `reason`, `delete_days` (0–7) | Bannir | ✅ | Bannit (même si le membre a déjà quitté), purge optionnelle des messages | | `/clear` | `amount` (1–100) | Gérer les messages | ✅ | Supprime les N derniers messages (ceux de plus de 14 j sont ignorés) | diff --git a/src/commands/moderation/unban.js b/src/commands/moderation/unban.js new file mode 100644 index 0000000..3748322 --- /dev/null +++ b/src/commands/moderation/unban.js @@ -0,0 +1,62 @@ +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { UserFacingError } from '../../core/errors.js'; +import { + assertModerationTarget, + logModerationAction, + notifyTarget, + targetNoticeEmbed, +} from '../../services/moderation/moderation-service.js'; +import { successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +export const data = new SlashCommandBuilder() + .setName('unban') + .setDescription('Lever le bannissement d’un membre') + .setDefaultMemberPermissions(PermissionFlagsBits.BanMembers) + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) + .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)); + +/** Counterpart of `/ban`, usable whether or not the member already left. */ +export async function execute(interaction) { + const user = interaction.options.getUser('user', true); + const reason = interaction.options.getString('reason'); + + // Fetching the ban first turns “not banned” into a clear message instead of + // the missing-ban error Discord returns from the removal itself. + const ban = await interaction.guild.bans.fetch(user.id).catch(() => null); + if (!ban) { + throw new UserFacingError(`${user.tag} n’est pas banni de ce serveur : il n’y a rien à lever.`); + } + + // A banned member has usually already left, so the hierarchy is only checked + // while they are still on the server (a ban applied too quickly, typically). + const member = await interaction.guild.members.fetch(user.id).catch(() => null); + if (member) assertModerationTarget(interaction, member); + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + await interaction.guild.bans.remove( + user.id, + reason ?? `Débannissement demandé par ${interaction.user.tag}`, + ); + + await logModerationAction(interaction, { action: 'unban', targetId: user.id, reason }); + // A direct message is the only way to tell someone they may come back. + const recipient = member ?? (await interaction.client.users.fetch(user.id).catch(() => null)); + if (recipient) { + await notifyTarget( + recipient, + { embeds: [targetNoticeEmbed({ action: 'unban', guildName: interaction.guild.name, reason })] }, + interaction.guildId, + ); + } + + await interaction.editReply({ + embeds: [ + successEmbed( + `C’est fait : **${user.tag}** peut de nouveau rejoindre le serveur. L’historique reste consultable avec \`/mod logs\`.`, + ), + ], + }); +} diff --git a/src/commands/moderation/unmute.js b/src/commands/moderation/unmute.js new file mode 100644 index 0000000..71b3ff6 --- /dev/null +++ b/src/commands/moderation/unmute.js @@ -0,0 +1,52 @@ +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import { ACCESS_LEVELS } from '../../config/constants.js'; +import { UserFacingError } from '../../core/errors.js'; +import { + assertModerationTarget, + fetchTargetMember, + logModerationAction, + notifyTarget, + targetNoticeEmbed, +} from '../../services/moderation/moderation-service.js'; +import { successEmbed } from '../../ui/embeds.js'; + +export const access = ACCESS_LEVELS.STAFF; + +export const data = new SlashCommandBuilder() + .setName('unmute') + .setDescription('Lever l’exclusion temporaire d’un membre avant la fin') + .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers) + .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) + .addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)); + +/** Counterpart of `/mute`: clears the timeout early and keeps the trail. */ +export async function execute(interaction) { + const user = interaction.options.getUser('user', true); + const reason = interaction.options.getString('reason'); + + const target = await fetchTargetMember(interaction, user.id); + assertModerationTarget(interaction, target); + // Discord answers a timeout removal on a member who is not muted with an + // opaque error, so the check turns it into an explicit message. + if (!target.isCommunicationDisabled()) { + throw new UserFacingError( + `${target.user.tag} n’est pas en exclusion temporaire : cette personne peut déjà écrire.`, + ); + } + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + await target.timeout(null, reason ?? `Levée d’exclusion demandée par ${interaction.user.tag}`); + + await logModerationAction(interaction, { action: 'unmute', targetId: target.id, reason }); + await notifyTarget(target, { + embeds: [targetNoticeEmbed({ action: 'unmute', guildName: interaction.guild.name, reason })], + }); + + await interaction.editReply({ + embeds: [ + successEmbed( + `C’est fait : **${target.user.tag}** peut de nouveau écrire sur le serveur. L’historique reste consultable avec \`/mod logs\`.`, + ), + ], + }); +} diff --git a/src/config/constants.js b/src/config/constants.js index 788998c..248a529 100644 --- a/src/config/constants.js +++ b/src/config/constants.js @@ -32,8 +32,10 @@ export const ACCESS_LABELS = Object.freeze({ export const MODERATION_ACTIONS = Object.freeze({ warn: { label: 'Avertissement', color: COLORS.warning, duration: false }, mute: { label: 'Exclusion temporaire', color: COLORS.moderation, duration: true }, + unmute: { label: 'Levée d’exclusion temporaire', color: COLORS.success, duration: false }, kick: { label: 'Expulsion', color: COLORS.moderation, duration: false }, ban: { label: 'Bannissement', color: COLORS.error, duration: false }, + unban: { label: 'Débannissement', color: COLORS.success, duration: false }, clear: { label: 'Suppression de messages', color: COLORS.warning, duration: false }, role: { label: 'Modification de rôle', color: COLORS.primary, duration: false }, }); diff --git a/src/database/migrations/010-moderation-lifted-actions.sql b/src/database/migrations/010-moderation-lifted-actions.sql new file mode 100644 index 0000000..277a622 --- /dev/null +++ b/src/database/migrations/010-moderation-lifted-actions.sql @@ -0,0 +1,23 @@ +-- Lifted sanctions join the sanctions in the moderation history +-- +-- `/unmute` and `/unban` are recorded like `/mute` and `/ban`, but SQLite cannot +-- alter a CHECK constraint: the table is rebuilt and the rows copied over so the +-- history already stored survives the migration. + +CREATE TABLE moderation_actions_lifted ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + guild_id TEXT NOT NULL, + action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'unmute', 'kick', 'ban', 'unban', 'clear', 'role')), + target_id TEXT, + moderator_id TEXT NOT NULL, + reason TEXT, + duration_ms INTEGER, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +INSERT INTO moderation_actions_lifted (id, guild_id, action, target_id, moderator_id, reason, duration_ms, created_at) + SELECT id, guild_id, action, target_id, moderator_id, reason, duration_ms, created_at FROM moderation_actions; + +DROP TABLE moderation_actions; +ALTER TABLE moderation_actions_lifted RENAME TO moderation_actions; +CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id); diff --git a/src/services/moderation/moderation-service.js b/src/services/moderation/moderation-service.js index 2afeae0..e0c12c7 100644 --- a/src/services/moderation/moderation-service.js +++ b/src/services/moderation/moderation-service.js @@ -100,9 +100,11 @@ export async function sendModerationLog( * Sends the private notice to the sanctioned member, when the server wants one * (M8-T07). Never throws: plenty of accounts refuse direct messages, and that * must not turn a successful sanction into an error. + * @param guildId Server the sanction belongs to. A lifted ban targets someone + * who has left the server, so a plain `User` is accepted with an explicit id. */ -export async function notifyTarget(member, payload) { - if (!readSetting('moderation.dmTarget', member.guild.id)) return false; +export async function notifyTarget(member, payload, guildId = member.guild?.id) { + if (!readSetting('moderation.dmTarget', guildId)) return false; return member .send(payload) .then(() => true) diff --git a/tests/database.test.js b/tests/database.test.js index da39f42..d28cf4d 100644 --- a/tests/database.test.js +++ b/tests/database.test.js @@ -1,6 +1,7 @@ import assert from 'node:assert/strict'; import { after, before, describe, it } from 'node:test'; import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js'; +import { listActions, recordAction } from '../src/database/repositories/moderation-repository.js'; import { getSetting, setSetting } from '../src/database/repositories/settings-repository.js'; describe('database', () => { @@ -22,6 +23,20 @@ describe('database', () => { assert.equal(getSetting('guild-b', 'welcome'), null); }); + it('records a lifted sanction next to the sanction it lifts', () => { + // `/unmute` and `/unban` go through the same CHECK constraint as `/mute` + // and `/ban`, so a migration that forgets them breaks the history. + for (const action of ['unban', 'unmute']) { + recordAction({ guildId: 'g', action, moderatorId: 'mod', targetId: 'u', reason: 'Erreur' }); + } + + const rows = listActions({ guildId: 'g', targetId: 'u' }); + assert.deepEqual( + rows.map((row) => row.action).sort(), + ['unban', 'unmute'], + ); + }); + it('prevents two open tickets for the same author and category', () => { const insert = getDatabase().prepare( "INSERT INTO tickets (guild_id, category_id, author_id) VALUES ('g', 'bug', 'u')", -- 2.39.5 From d720c0a17edd8df2d7dac374ac6d0db02c4b9c37 Mon Sep 17 00:00:00 2001 From: BlackAngelTV Date: Fri, 25 Sep 2026 20:11:05 +0200 Subject: [PATCH 2/2] chore(changelog): regenerate from the commit history MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 99d0462..efda883 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ The project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] ### Features +- **moderation:** _(feat)_ add the unmute and unban commands ([9f8ac0d]) - **web:** _(feat)_ publish a public status page at /status ([a1e1de7]) - **web:** _(feat)_ search the whole panel from one place ([9acb523]) - **projects:** _(feat)_ gather the cards one member carries ([fcc82d8]) -- 2.39.5