Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ffb54a8e37
|
||
|
|
e6ce594b34
|
||
|
|
22e9723700
|
||
|
|
31c0fc861a
|
||
|
|
20ffbbacad | ||
|
|
c61a13176e
|
||
|
|
44e990d04b
|
||
|
|
99e1fd2723
|
||
|
|
859b229181 | ||
|
|
d720c0a17e
|
||
|
|
9f8ac0d29e
|
||
|
|
b8be549fda
|
No files matched your search
@@ -1,12 +1,12 @@
|
||||
# AGENTS.md — Instructions pour les agents IA
|
||||
|
||||
> Fichier de référence pour les agents IA (Codebuff, Cursor, Claude Code, GitHub Copilot…) qui travaillent sur un repo de l'organisation **FWS**. Un agent doit lire ce fichier en premier : il contient les instructions à respecter. Le `README.md` apporte le contexte complet.
|
||||
> Fichier de référence pour les agents IA (Codebuff, Cursor, Claude Code, GitHub Copilot…) qui travaillent sur un dépôt de l'organisation **FWS**. Un agent doit lire ce fichier en premier : il contient les instructions à respecter. Le `README.md` présente l'organisation et le `CONTRIBUTING.md` détaille les conventions de collaboration.
|
||||
|
||||
## Contexte
|
||||
|
||||
- **FWS** est une organisation open source multi-projets : chaque projet choisit librement sa stack (pas de restriction de langage).
|
||||
- Projet principal : **FWS Arch** — un fork d'Arch Linux avec une surcouche conviviale pour simplifier l'installation et l'usage au quotidien.
|
||||
- Conventions détaillées : `README.md` (FR) / `README.en.md` (EN).
|
||||
- **FWS** est une organisation open source multi-projets : chaque projet choisit librement sa stack technique (sans restriction de langage).
|
||||
- Projet principal : **FWS ISO** — une distribution Linux basée sur Arch Linux, pensée pour simplifier l'installation et l'usage au quotidien.
|
||||
- Conventions détaillées : `CONTRIBUTING.md` (FR) / `CONTRIBUTING.en.md` (EN).
|
||||
|
||||
## Règles à respecter
|
||||
|
||||
@@ -24,29 +24,36 @@
|
||||
|
||||
### Code & commentaires
|
||||
|
||||
- Commentaires en **anglais**, style « pourquoi » : pas de commentaire si le code est explicite, documenter le non-évident (choix d'implémentation, trade-offs, cas limites).
|
||||
- Respecter la stack et les conventions existantes du repo avant d'ajouter de nouvelles dépendances.
|
||||
- Commentaires en **anglais**, style « pourquoi » : pas de commentaire si le code est explicite ; documenter le non-évident (choix d'implémentation, compromis, cas limites).
|
||||
- Respecter la stack technique et les conventions existantes du dépôt avant d'ajouter de nouvelles dépendances.
|
||||
|
||||
### Fichiers sensibles (`.gitignore`)
|
||||
|
||||
- Ne **jamais** committer : fichiers d'environnement (`.env*`), données d'assistants de développement (`.freebuff/`), artefacts compilés (`dist/`, `build/`, `target/`, `__pycache__/`…), dépendances (`node_modules/`), secrets.
|
||||
- Un `.gitignore` doit exister à la racine de chaque repo.
|
||||
- Ne **jamais** versionner : fichiers d'environnement (`.env*`), données d'assistants de développement (`.freebuff/`), artefacts compilés (`dist/`, `build/`, `target/`, `__pycache__/`…), dépendances (`node_modules/`), secrets.
|
||||
- Un `.gitignore` doit exister à la racine de chaque dépôt.
|
||||
|
||||
### Tests
|
||||
|
||||
- Fichiers de test : `*.test.*`, noms `describe` / `it` en anglais.
|
||||
- Fichiers de test : `*.test.*` ; noms de tests `describe` / `it` en anglais.
|
||||
- Vérifier que les tests (et le typecheck / lint quand ils existent) passent avant de considérer une tâche terminée.
|
||||
|
||||
### Issues & signalement de bugs
|
||||
|
||||
- Les bugs et demandes sont suivis via les **issues**, liées au tableau Kanban.
|
||||
- Une PR qui corrige un bug référence l'issue dans son titre ou sa description (`Fixes #123`).
|
||||
- Les bugs et demandes sont suivis via les **issues** et, lorsqu'il existe, le tableau Kanban du projet.
|
||||
- Une pull request qui corrige un bug référence l'issue dans son titre ou sa description (`Fixes #123`).
|
||||
- Ne pas fermer ni modifier une issue sans demande explicite de l'utilisateur.
|
||||
|
||||
### Commits demandés par l'utilisateur
|
||||
|
||||
- Lorsque l'utilisateur demande explicitement de créer un commit, l'IA doit le faire après avoir vérifié les changements et les contrôles disponibles, sans attendre une confirmation supplémentaire.
|
||||
- Le titre et le corps du commit ne doivent jamais mentionner l'IA, l'assistant, Codebuff ou l'outil utilisé.
|
||||
- Ne pas ajouter l'IA comme auteur ou co-auteur dans le message du commit.
|
||||
|
||||
## Bonnes pratiques pour un agent
|
||||
|
||||
- Lire `AGENTS.md` puis `README.md` avant d'éditer du code.
|
||||
- Lire `AGENTS.md`, le `README.md` et le `CONTRIBUTING.md` avant d'éditer du code.
|
||||
- Les commits doivent être signés.
|
||||
- Faire les changements les plus petits possibles qui répondent à la demande.
|
||||
- Ne pas pousser, merger ni publier sans demande explicite de l'utilisateur.
|
||||
- Suivre les cartes du tableau Kanban du projet pour l'organisation du travail.
|
||||
- En cas de doute, demander plutôt que deviner.
|
||||
- Ne pas pousser, fusionner ni publier sans demande explicite de l'utilisateur.
|
||||
- Suivre les cartes du tableau Kanban lorsqu'il existe pour organiser le travail.
|
||||
- En cas de doute, demander plutôt que de deviner.
|
||||
@@ -7,6 +7,8 @@ The project follows [Semantic Versioning](https://semver.org/).
|
||||
## [Unreleased]
|
||||
|
||||
### Features
|
||||
- **rules:** _(feat)_ write the rules from the dashboard and republish them ([31c0fc8])
|
||||
- **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])
|
||||
@@ -91,6 +93,8 @@ The project follows [Semantic Versioning](https://semver.org/).
|
||||
- **config:** _(feat)_ load and expose environment settings ([d1388b6])
|
||||
|
||||
### Bug Fixes
|
||||
- **rules:** _(fix)_ show the rules field with a save button and edit the message ([e6ce594])
|
||||
- **moderation:** _(fix)_ tell a mute apart from a kick in the logs ([99e1fd2])
|
||||
- **wiki:** _(fix)_ render the public pages on the server ([8869c74])
|
||||
- **web:** _(fix)_ stop caching the interface modules ([3f4a570])
|
||||
- **web:** _(fix)_ keep the stack when a view fails ([c031b4d])
|
||||
@@ -109,6 +113,7 @@ The project follows [Semantic Versioning](https://semver.org/).
|
||||
- **notifications:** _(fix)_ apply the channel overrides set from Discord ([92405ac])
|
||||
|
||||
### Other changes
|
||||
- **agents:** _(docs)_ update the repository conventions and commit rules ([44e990d])
|
||||
- **web:** _(docs)_ document my tasks, the search and the status page ([566af4d])
|
||||
- **web:** _(refactor)_ extract the build marker into its own module ([d2256e2])
|
||||
- **ops:** _(docs)_ correct the deployment path for a panel without a shell ([e3ce266])
|
||||
|
||||
+5
-2
@@ -126,7 +126,8 @@ Full template: [`.env.example`](.env.example). Default values in brackets.
|
||||
| Variable | Usage |
|
||||
| -------------------------------- | --------------------------------------------------------------------------- |
|
||||
| `CHANNEL_WELCOME_ID` | Welcome messages |
|
||||
| `CHANNEL_RULES_ID` | Rules (link sent to newcomers) |
|
||||
| `CHANNEL_RULES_ID` | Rules: link sent to newcomers, and where the dashboard pins the message. |
|
||||
| | Later saves edit that same message |
|
||||
| `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements |
|
||||
| `CHANNEL_LOGS_ID` | Functional logs |
|
||||
| `CHANNEL_MOD_LOGS_ID` | Moderation logs |
|
||||
@@ -289,6 +290,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) |
|
||||
@@ -324,7 +327,7 @@ No added dependency: `node:http` for the server, `node:sqlite` for the sessions,
|
||||
|
||||
The bot also serves **public documentation** at `/wiki`, readable without an account and written from the panel. It ships with **terms of use** and a **privacy policy** aligned with the Swiss LPD, describing exactly what this code processes — the bracketed details still have to be filled in and reviewed.
|
||||
|
||||
The panel also **publishes the slash commands** to Discord without shell access, and gathers under **Settings** everything that can be changed without touching the `.env`: welcome, moderation, tickets, voice, notifications.
|
||||
The panel also **publishes the slash commands** to Discord without shell access, and gathers under **Settings** everything that can be changed without touching the `.env`: welcome, moderation, rules, tickets, voice, notifications.
|
||||
|
||||
### 6.1 Getting started
|
||||
|
||||
|
||||
@@ -128,7 +128,7 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare
|
||||
| Variable | Usage |
|
||||
| --- | --- |
|
||||
| `CHANNEL_WELCOME_ID` | Messages de bienvenue |
|
||||
| `CHANNEL_RULES_ID` | Règlement (lien envoyé aux nouveaux) |
|
||||
| `CHANNEL_RULES_ID` | Règlement : lien envoyé aux nouveaux, et salon où le tableau de bord publie le message épinglé (les enregistrements suivants le modifient) |
|
||||
| `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS |
|
||||
| `CHANNEL_LOGS_ID` | Logs fonctionnels |
|
||||
| `CHANNEL_MOD_LOGS_ID` | Logs de modération |
|
||||
@@ -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) |
|
||||
@@ -326,7 +328,7 @@ Aucune dépendance ajoutée : `node:http` pour le serveur, `node:sqlite` pour le
|
||||
|
||||
Le bot sert aussi une **documentation publique** sur `/wiki`, lisible sans compte et rédigée depuis le panel. Elle est livrée avec des **conditions d'utilisation** et une **politique de confidentialité** conformes à la LPD suisse, décrivant précisément les données que ce code traite — les mentions entre crochets restent à compléter et à faire relire.
|
||||
|
||||
Le panel permet aussi de **publier les commandes slash** sur Discord sans accès shell, et regroupe dans **Paramètres** tout ce qui se règle sans toucher au `.env` : accueil, modération, tickets, vocaux, notifications.
|
||||
Le panel permet aussi de **publier les commandes slash** sur Discord sans accès shell, et regroupe dans **Paramètres** tout ce qui se règle sans toucher au `.env` : accueil, modération, règlement, tickets, vocaux, notifications.
|
||||
|
||||
### 6.1 Démarrer
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ Le commutateur en bas de la barre latérale masque ou révèle les panneaux tech
|
||||
| **Serveur Discord** | Membres, rôles, modération, annonces, routage des notifications, inventaire des commandes |
|
||||
| **Tickets & vocaux** | Tickets, sondages, salons vocaux temporaires, rotation des statuts du bot |
|
||||
| **Journaux** | Événements fonctionnels et fichiers de logs techniques, secrets masqués |
|
||||
| **Paramètres** | Comportement du bot, connexions, sessions, jetons d'API, maintenance |
|
||||
| **Paramètres** | Comportement du bot, règlement, connexions, sessions, jetons d'API, maintenance |
|
||||
| **Configuration .env** | L'assistant pas à pas, accessible aussi une fois le bot configuré |
|
||||
|
||||
## 4. Assistant de configuration
|
||||
@@ -206,10 +206,14 @@ Une page supprimée par erreur est recréée au démarrage suivant ; une page r
|
||||
|
||||
## 9. Réglages du serveur
|
||||
|
||||
**Tableau de bord → Paramètres** regroupe ce qui se change sans toucher au `.env` : accueil des membres, modération, tickets, salons vocaux, notifications, interface. Chaque réglage est décrit une seule fois dans `src/config/guild-settings.js`, et un test vérifie que **chaque clé déclarée est réellement lue par le code** — un interrupteur qui ne fait rien est pire que pas d'interrupteur.
|
||||
**Tableau de bord → Paramètres** regroupe ce qui se change sans toucher au `.env` : accueil des membres, modération, règlement, tickets, salons vocaux, notifications, interface. Chaque réglage est décrit une seule fois dans `src/config/guild-settings.js`, et un test vérifie que **chaque clé déclarée est réellement lue par le code** — un interrupteur qui ne fait rien est pire que pas d'interrupteur.
|
||||
|
||||
Les changements prennent effet immédiatement, sans redémarrage, contrairement aux valeurs du `.env`.
|
||||
|
||||
### Rédiger et publier le règlement
|
||||
|
||||
La section **Règlement** de la page Paramètres écrit les règles en markdown (celui de Discord : `**gras**`, `*italique*`, `code`, listes, titres) et **Enregistrer** les publie dans `CHANNEL_RULES_ID` sous forme d'un embed épinglé. L'identifiant du message est retenu en base (`rules_messages`) : les enregistrements suivants **modifient ce message**, même lien, même place dans le salon et épingle conservée, au lieu d'empiler les versions. Un message supprimé à la main, un salon devenu inaccessible ou un bot qui ne peut plus éditer font repartir sur un nouveau message ; un épinglage refusé est signalé sans bloquer la publication. Le texte est enregistré même si la publication échoue, pour ne pas perdre ce qui a été écrit. Niveau **Dev** requis.
|
||||
|
||||
## 10. Publier les commandes slash
|
||||
|
||||
**Tableau de bord → Serveur Discord → Commandes slash → Publier sur Discord** fait ce que fait `npm run deploy:commands`, sans accès shell. Les commandes par serveur sont actives immédiatement. À relancer après chaque ajout ou modification de commande.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS, COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
|
||||
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
|
||||
import { listActions } from '../../database/repositories/moderation-repository.js';
|
||||
import { formatDuration } from '../../services/moderation/moderation-service.js';
|
||||
import { formatDuration, moderationLabel } from '../../services/moderation/moderation-service.js';
|
||||
import { baseEmbed, infoEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.STAFF;
|
||||
@@ -20,11 +20,10 @@ export const data = new SlashCommandBuilder()
|
||||
);
|
||||
|
||||
function formatEntry(row) {
|
||||
const meta = MODERATION_ACTIONS[row.action];
|
||||
const target = row.target_id ? `<@${row.target_id}>` : 'salon';
|
||||
const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : '';
|
||||
return (
|
||||
`\`${row.created_at}\` **${meta?.label ?? row.action}** — ${target}${duration}\n` +
|
||||
`\`${row.created_at}\` **${moderationLabel(row.action)}** — ${target}${duration}\n` +
|
||||
`↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ export async function execute(interaction) {
|
||||
assertModerationTarget(interaction, target);
|
||||
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
await target.timeout(durationMs, reason ?? `Exclusion temporaire de ${minutes} minutes`);
|
||||
await target.timeout(durationMs, reason ?? `Mise en sourdine de ${minutes} minutes`);
|
||||
|
||||
await logModerationAction(interaction, {
|
||||
action: 'mute',
|
||||
@@ -55,7 +55,7 @@ export async function execute(interaction) {
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
successEmbed(
|
||||
`C’est fait : **${target.user.tag}** est en exclusion temporaire pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`,
|
||||
`C’est fait : **${target.user.tag}** est en sourdine pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`,
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
@@ -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\`.`,
|
||||
),
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -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\`.`,
|
||||
),
|
||||
],
|
||||
});
|
||||
}
|
||||
+19
-7
@@ -28,14 +28,26 @@ export const ACCESS_LABELS = Object.freeze({
|
||||
[ACCESS_LEVELS.OWNER]: 'Owner',
|
||||
});
|
||||
|
||||
/** Moderation actions: Discord label, embed color and stored duration (M8). */
|
||||
/**
|
||||
* Moderation actions: Discord label, embed color and stored duration (M8).
|
||||
* The emoji belongs to the entry so every surface (log channel, direct message,
|
||||
* `/mod logs`, dashboard) tells a mute from a kick at a glance: the wording
|
||||
* alone read like a temporary kick.
|
||||
*/
|
||||
export const MODERATION_ACTIONS = Object.freeze({
|
||||
warn: { label: 'Avertissement', color: COLORS.warning, duration: false },
|
||||
mute: { label: 'Exclusion temporaire', color: COLORS.moderation, duration: true },
|
||||
kick: { label: 'Expulsion', color: COLORS.moderation, duration: false },
|
||||
ban: { label: 'Bannissement', color: COLORS.error, duration: false },
|
||||
clear: { label: 'Suppression de messages', color: COLORS.warning, duration: false },
|
||||
role: { label: 'Modification de rôle', color: COLORS.primary, duration: false },
|
||||
warn: { label: 'Avertissement', emoji: '⚠️', color: COLORS.warning, duration: false },
|
||||
mute: { label: 'Mise en sourdine', emoji: '🔇', color: COLORS.moderation, duration: true },
|
||||
unmute: {
|
||||
label: 'Levée de la mise en sourdine',
|
||||
emoji: '🔊',
|
||||
color: COLORS.success,
|
||||
duration: false,
|
||||
},
|
||||
kick: { label: 'Expulsion', emoji: '👢', color: COLORS.moderation, duration: false },
|
||||
ban: { label: 'Bannissement', emoji: '🔨', color: COLORS.error, duration: false },
|
||||
unban: { label: 'Débannissement', emoji: '🔓', color: COLORS.success, duration: false },
|
||||
clear: { label: 'Supclusion de messages', emoji: '🧹', color: COLORS.warning, duration: false },
|
||||
role: { label: 'Modification de rôle', emoji: '🏷️', color: COLORS.primary, duration: false },
|
||||
});
|
||||
|
||||
/** Ticket categories and who can see them (M0-T05 / M6-T01). */
|
||||
|
||||
@@ -17,6 +17,11 @@ export const SETTING_SECTIONS = Object.freeze([
|
||||
summary: 'Ce que le bot fait quand quelqu’un rejoint ou quitte.',
|
||||
},
|
||||
{ id: 'moderation', title: 'Modération', summary: 'Comportement par défaut des sanctions.' },
|
||||
{
|
||||
id: 'rules',
|
||||
title: 'Règlement',
|
||||
summary: 'Message affiché et épinglé dans le salon des règles.',
|
||||
},
|
||||
{ id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' },
|
||||
{
|
||||
id: 'voice',
|
||||
@@ -91,7 +96,7 @@ export const GUILD_SETTINGS = Object.freeze([
|
||||
{
|
||||
key: 'moderation.defaultMuteMinutes',
|
||||
section: 'moderation',
|
||||
label: 'Durée d’exclusion par défaut (min)',
|
||||
label: 'Durée de mise en sourdine par défaut (min)',
|
||||
help: 'Proposée quand `/mute` est lancé sans durée.',
|
||||
type: 'int',
|
||||
default: 60,
|
||||
@@ -110,6 +115,17 @@ export const GUILD_SETTINGS = Object.freeze([
|
||||
advanced: true,
|
||||
},
|
||||
|
||||
// --- Règlement ---------------------------------------------------------------
|
||||
{
|
||||
key: 'rules.markdown',
|
||||
section: 'rules',
|
||||
label: 'Règlement (markdown)',
|
||||
help: 'Enregistré et épinglé dans le salon des règles (`CHANNEL_RULES_ID`). Markdown de Discord : **gras**, *italique*, `code`, listes, titres. Enregistrer modifie le message déjà publié.',
|
||||
type: 'markdown',
|
||||
default: '',
|
||||
maxLength: 4000,
|
||||
},
|
||||
|
||||
// --- Tickets ---------------------------------------------------------------
|
||||
{
|
||||
key: 'tickets.deleteChannelOnClose',
|
||||
|
||||
@@ -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);
|
||||
@@ -0,0 +1,13 @@
|
||||
-- The rules message published from the dashboard (M19)
|
||||
--
|
||||
-- The bot republishes the rules by deleting the previous message and sending
|
||||
-- the new one, so it has to remember which message it owns. Without this the
|
||||
-- channel would slowly fill with outdated copies.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS rules_messages (
|
||||
guild_id TEXT PRIMARY KEY,
|
||||
channel_id TEXT NOT NULL,
|
||||
message_id TEXT NOT NULL,
|
||||
updated_by TEXT,
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
@@ -0,0 +1,24 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
/** The rules message the bot published, so the next version can replace it. */
|
||||
export function setRulesMessage({ guildId, channelId, messageId, updatedBy = null }) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO rules_messages (guild_id, channel_id, message_id, updated_by)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (guild_id) DO UPDATE SET
|
||||
channel_id = excluded.channel_id,
|
||||
message_id = excluded.message_id,
|
||||
updated_by = excluded.updated_by,
|
||||
updated_at = datetime('now')`,
|
||||
)
|
||||
.run(guildId, channelId, messageId, updatedBy);
|
||||
}
|
||||
|
||||
export function getRulesMessage(guildId) {
|
||||
return getDatabase().prepare('SELECT * FROM rules_messages WHERE guild_id = ?').get(guildId) ?? null;
|
||||
}
|
||||
|
||||
export function clearRulesMessage(guildId) {
|
||||
return getDatabase().prepare('DELETE FROM rules_messages WHERE guild_id = ?').run(guildId).changes;
|
||||
}
|
||||
@@ -7,6 +7,17 @@ import { logEvent } from '../../database/repositories/event-log-repository.js';
|
||||
import { recordAction } from '../../database/repositories/moderation-repository.js';
|
||||
import { baseEmbed } from '../../ui/embeds.js';
|
||||
|
||||
/**
|
||||
* Label shown for an action everywhere it is rendered (log channel, direct
|
||||
* message, `/mod logs`, dashboard). Falls back to the raw action name, so a
|
||||
* row written by another version still reads as something.
|
||||
* @param {string} action
|
||||
*/
|
||||
export function moderationLabel(action) {
|
||||
const meta = MODERATION_ACTIONS[action];
|
||||
return meta ? `${meta.emoji} ${meta.label}` : action;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08).
|
||||
* @param {import('discord.js').ChatInputCommandInteraction} interaction
|
||||
@@ -82,7 +93,7 @@ export async function sendModerationLog(
|
||||
|
||||
const meta = MODERATION_ACTIONS[action];
|
||||
const embed = baseEmbed(meta?.color)
|
||||
.setTitle(`🛡️ Modération — ${meta?.label ?? action}`)
|
||||
.setTitle(`🛡️ Modération — ${moderationLabel(action)}`)
|
||||
.addFields(
|
||||
{ name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true },
|
||||
{ name: 'Par', value: `<@${moderatorId}>`, inline: true },
|
||||
@@ -100,9 +111,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)
|
||||
@@ -115,7 +128,7 @@ export function targetNoticeEmbed({ action, guildName, reason = null, durationMs
|
||||
const embed = baseEmbed(meta?.color)
|
||||
.setTitle(`Sanction sur ${guildName}`)
|
||||
.setDescription(
|
||||
`Action : **${meta?.label ?? action}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`,
|
||||
`Action : **${moderationLabel(action)}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`,
|
||||
)
|
||||
.addFields({ name: 'Motif', value: reason || 'Non précisé' });
|
||||
if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) });
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { COLORS } from '../../config/constants.js';
|
||||
import { env } from '../../config/env.js';
|
||||
import { createLogger } from '../../core/logger.js';
|
||||
import { logEvent } from '../../database/repositories/event-log-repository.js';
|
||||
import { getRulesMessage, setRulesMessage } from '../../database/repositories/rules-repository.js';
|
||||
import { baseEmbed } from '../../ui/embeds.js';
|
||||
|
||||
/**
|
||||
* Rules of the server, written from the dashboard and kept in a single pinned
|
||||
* message in `CHANNEL_RULES_ID` (M19).
|
||||
*
|
||||
* Saving edits the message already published, so the channel keeps one set of
|
||||
* rules — same link, same position, and the pin survives. A new message is
|
||||
* only sent when the bot has none yet, or when the previous one was deleted by
|
||||
* hand.
|
||||
*/
|
||||
|
||||
const log = createLogger('rules');
|
||||
|
||||
/** Discord refuses an embed description longer than that. */
|
||||
export const RULES_MAX_LENGTH = 4000;
|
||||
|
||||
const TITLE = '📜 Règlement';
|
||||
|
||||
const rulesEmbed = (content) =>
|
||||
baseEmbed(COLORS.primary)
|
||||
.setTitle(TITLE)
|
||||
.setDescription(content)
|
||||
.setFooter({ text: 'Mis à jour depuis le tableau de bord FWS-Bot' })
|
||||
.setTimestamp(new Date());
|
||||
|
||||
/**
|
||||
* Publishes the rules, editing the message already there when there is one.
|
||||
* @param {import('discord.js').Client} client
|
||||
* @param {{ guildId: string, markdown: string, actorId?: string | null, channelId?: string }} options
|
||||
* @returns {Promise<{ messageId: string, url: string | null, channelId: string, pinned: boolean, edited: boolean }>}
|
||||
*/
|
||||
export async function publishRules(
|
||||
client,
|
||||
{ guildId, markdown, actorId = null, channelId = env.channels.rules },
|
||||
) {
|
||||
if (!channelId) {
|
||||
throw new Error('Aucun salon des règles configuré : renseigne CHANNEL_RULES_ID dans le .env.');
|
||||
}
|
||||
|
||||
const content = String(markdown ?? '').trim();
|
||||
if (content === '') throw new Error('Le règlement est vide.');
|
||||
if (content.length > RULES_MAX_LENGTH) {
|
||||
throw new Error(`${RULES_MAX_LENGTH} caractères maximum pour un règlement.`);
|
||||
}
|
||||
|
||||
const channel = await client.channels.fetch(channelId).catch(() => null);
|
||||
if (!channel?.isSendable()) {
|
||||
throw new Error('Salon des règles introuvable, ou le bot n’y peut pas écrire.');
|
||||
}
|
||||
|
||||
const edited = await editPublishedRules(client, guildId, content);
|
||||
const message = edited ?? (await channel.send({ embeds: [rulesEmbed(content)] }));
|
||||
|
||||
// Only a brand new message has to be pinned: an edited one keeps its pin.
|
||||
const pinned = edited
|
||||
? true
|
||||
: await message
|
||||
.pin()
|
||||
.then(() => true)
|
||||
.catch((error) => {
|
||||
// A bot without “Gérer les messages” still publishes the rules.
|
||||
log.warn('Could not pin the rules message', error);
|
||||
return false;
|
||||
});
|
||||
|
||||
setRulesMessage({
|
||||
guildId,
|
||||
channelId,
|
||||
messageId: message.id,
|
||||
updatedBy: actorId,
|
||||
});
|
||||
logEvent({
|
||||
guildId,
|
||||
type: 'web.rules.published',
|
||||
actorId,
|
||||
payload: { channelId, messageId: message.id, pinned, edited: Boolean(edited) },
|
||||
});
|
||||
log.info('Rules saved from the dashboard', {
|
||||
channelId,
|
||||
messageId: message.id,
|
||||
edited: Boolean(edited),
|
||||
actor: actorId,
|
||||
});
|
||||
|
||||
return {
|
||||
messageId: message.id,
|
||||
url: message.url ?? null,
|
||||
channelId,
|
||||
pinned,
|
||||
edited: Boolean(edited),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites the message the bot published last time.
|
||||
* @returns the edited message, or null when there is none to edit
|
||||
*/
|
||||
async function editPublishedRules(client, guildId, content) {
|
||||
const stored = getRulesMessage(guildId);
|
||||
if (!stored) return null;
|
||||
|
||||
const channel = await client.channels.fetch(stored.channel_id).catch(() => null);
|
||||
const message = await channel?.messages?.fetch(stored.message_id).catch(() => null);
|
||||
if (!message?.editable) return null;
|
||||
|
||||
return message
|
||||
.edit({ embeds: [rulesEmbed(content)] })
|
||||
.then((edited) => edited ?? message)
|
||||
.catch((error) => {
|
||||
// A message deleted by hand, or one the bot may no longer edit, must not
|
||||
// stop the publication: a fresh one takes its place.
|
||||
log.warn('Could not edit the previous rules message', error);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** What the dashboard needs to show the current state of the rules. */
|
||||
export function rulesStatus(guildId, channelId = env.channels.rules) {
|
||||
const stored = getRulesMessage(guildId);
|
||||
return {
|
||||
channelId: channelId || null,
|
||||
configured: Boolean(channelId),
|
||||
messageId: stored?.message_id ?? null,
|
||||
publishedAt: stored?.updated_at ?? null,
|
||||
publishedBy: stored?.updated_by ?? null,
|
||||
};
|
||||
}
|
||||
+39
-4
@@ -1,6 +1,7 @@
|
||||
import { ChannelType, REST, Routes } from 'discord.js';
|
||||
import { ACCESS_LABELS, ACCESS_LEVELS, MODERATION_ACTIONS } from '../../config/constants.js';
|
||||
import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { env } from '../../config/env.js';
|
||||
import { readSetting, writeSetting } from '../../config/guild-settings.js';
|
||||
import { ExternalApiError } from '../../core/errors.js';
|
||||
import { createLogger } from '../../core/logger.js';
|
||||
import { canActOn, getAccessLevel } from '../../core/permissions.js';
|
||||
@@ -15,7 +16,8 @@ import {
|
||||
removeNotificationChannel,
|
||||
setNotificationChannel,
|
||||
} from '../../database/repositories/notification-repository.js';
|
||||
import { sendModerationLog } from '../../services/moderation/moderation-service.js';
|
||||
import { moderationLabel, sendModerationLog } from '../../services/moderation/moderation-service.js';
|
||||
import { publishRules, rulesStatus } from '../../services/rules/rules-service.js';
|
||||
import { badRequest, forbidden, notFound } from '../http.js';
|
||||
|
||||
/** Discord server management from the dashboard (M16-T05). */
|
||||
@@ -201,7 +203,7 @@ export function registerDiscordRoutes(router) {
|
||||
const reason = String(body.reason ?? '').trim() || 'Non précisé';
|
||||
const durationMs = action === 'mute' ? Number.parseInt(body.durationMs ?? 0, 10) : null;
|
||||
if (action === 'mute' && (!Number.isInteger(durationMs) || durationMs <= 0)) {
|
||||
throw badRequest('Une durée en millisecondes est requise pour une exclusion temporaire.');
|
||||
throw badRequest('Une durée en millisecondes est requise pour une mise en sourdine.');
|
||||
}
|
||||
|
||||
const audit = `${reason} — ${actor.displayName ?? actor.username} (tableau de bord)`;
|
||||
@@ -231,7 +233,7 @@ export function registerDiscordRoutes(router) {
|
||||
durationMs,
|
||||
});
|
||||
|
||||
return { ok: true, action, label: MODERATION_ACTIONS[action]?.label ?? action };
|
||||
return { ok: true, action, label: moderationLabel(action) };
|
||||
},
|
||||
{ access: ACCESS_LEVELS.STAFF },
|
||||
);
|
||||
@@ -292,6 +294,39 @@ export function registerDiscordRoutes(router) {
|
||||
{ access: ACCESS_LEVELS.STAFF },
|
||||
);
|
||||
|
||||
// --- Server rules ----------------------------------------------------------
|
||||
|
||||
router.get(
|
||||
'/api/discord/rules',
|
||||
() => ({ markdown: readSetting('rules.markdown', guildId()), ...rulesStatus(guildId()) }),
|
||||
{ access: ACCESS_LEVELS.STAFF },
|
||||
);
|
||||
|
||||
/** Publishes the rules, replacing the message the bot posted last time. */
|
||||
router.post(
|
||||
'/api/discord/rules',
|
||||
async ({ context, body, actor }) => {
|
||||
const markdown = writeSetting('rules.markdown', body.markdown, {
|
||||
guildId: guildId(),
|
||||
updatedBy: actor.userId,
|
||||
});
|
||||
|
||||
try {
|
||||
const published = await publishRules(context.client, {
|
||||
guildId: guildId(),
|
||||
markdown,
|
||||
actorId: actor.userId,
|
||||
});
|
||||
return { ok: true, ...published, ...rulesStatus(guildId()) };
|
||||
} catch (error) {
|
||||
// The text is saved either way: a channel that is simply not configured
|
||||
// yet must not throw away what was written.
|
||||
throw badRequest(error.message);
|
||||
}
|
||||
},
|
||||
{ access: ACCESS_LEVELS.DEV },
|
||||
);
|
||||
|
||||
// --- Notification routing --------------------------------------------------
|
||||
router.get(
|
||||
'/api/discord/notifications',
|
||||
|
||||
@@ -33,11 +33,13 @@ const DURATIONS = [
|
||||
{ value: String(7 * 24 * 60 * 60_000), label: '7 jours' },
|
||||
];
|
||||
|
||||
// Mirrors MODERATION_ACTIONS in `src/config/constants.js`, emoji included: the
|
||||
// panel must not be the one place where a mute reads like a kick.
|
||||
const MODERATION_ACTIONS = [
|
||||
{ value: 'warn', label: 'Avertissement' },
|
||||
{ value: 'mute', label: 'Exclusion temporaire' },
|
||||
{ value: 'kick', label: 'Expulsion' },
|
||||
{ value: 'ban', label: 'Bannissement' },
|
||||
{ value: 'warn', label: '⚠️ Avertissement' },
|
||||
{ value: 'mute', label: '🔇 Mise en sourdine' },
|
||||
{ value: 'kick', label: '👢 Expulsion' },
|
||||
{ value: 'ban', label: '🔨 Bannissement' },
|
||||
];
|
||||
|
||||
async function moderate(member, reload) {
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
stat,
|
||||
table,
|
||||
toast,
|
||||
textarea,
|
||||
toggle,
|
||||
} from '../core/ui.js';
|
||||
|
||||
@@ -55,6 +56,30 @@ function settingControl(setting, value, apply) {
|
||||
);
|
||||
}
|
||||
|
||||
// Markdown is a long text: a single-line input would hide what is written.
|
||||
if (setting.type === 'markdown') {
|
||||
const editor = textarea({
|
||||
value: value ?? '',
|
||||
rows: 12,
|
||||
maxlength: setting.maxLength,
|
||||
placeholder: '## Règlement\n\n1. …\n2. …',
|
||||
});
|
||||
return field(
|
||||
setting.label,
|
||||
h(
|
||||
'div',
|
||||
{ class: 'stack' },
|
||||
editor,
|
||||
h(
|
||||
'div',
|
||||
{ class: 'row' },
|
||||
button('Enregistrer', () => apply(editor.value), { tone: 'primary' }),
|
||||
),
|
||||
),
|
||||
{ help: setting.help },
|
||||
);
|
||||
}
|
||||
|
||||
const control = input({
|
||||
value: value ?? '',
|
||||
type: setting.type === 'int' ? 'number' : 'text',
|
||||
@@ -110,6 +135,20 @@ function behaviourCard(data, level, reload) {
|
||||
|
||||
const apply = async (next) => {
|
||||
try {
|
||||
// The rules are a message on Discord, not a stored value: saving
|
||||
// them has to publish them.
|
||||
if (setting.key === 'rules.markdown') {
|
||||
const published = await api.post('/api/discord/rules', { markdown: next });
|
||||
values[setting.key] = next;
|
||||
toast(
|
||||
published.edited
|
||||
? 'Règlement mis à jour dans le salon des règles.'
|
||||
: 'Règlement publié et épinglé dans le salon des règles.',
|
||||
published.pinned ? 'success' : 'info',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const saved = await api.put(`/api/settings/values/${setting.key}`, { value: next });
|
||||
toast(`« ${setting.label} » enregistré.`);
|
||||
values[setting.key] = saved.value;
|
||||
|
||||
@@ -230,7 +230,7 @@ export const VARIABLES = Object.freeze([
|
||||
key: 'CHANNEL_MOD_LOGS_ID',
|
||||
section: 'channels',
|
||||
label: 'Salon des logs de modération',
|
||||
help: 'Avertissements, exclusions, bannissements.',
|
||||
help: 'Avertissements, mises en sourdine, bannissements.',
|
||||
type: 'snowflake',
|
||||
},
|
||||
{
|
||||
|
||||
@@ -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')",
|
||||
|
||||
@@ -94,6 +94,30 @@ describe('webhook entry points', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('moderation labels', () => {
|
||||
it('tells every action apart by wording and emoji', async () => {
|
||||
const { MODERATION_ACTIONS } = await import('../src/config/constants.js');
|
||||
const { moderationLabel } = await import('../src/services/moderation/moderation-service.js');
|
||||
|
||||
const emojis = Object.values(MODERATION_ACTIONS).map((meta) => meta.emoji);
|
||||
assert.ok(emojis.every(Boolean), 'an action has no emoji');
|
||||
assert.equal(new Set(emojis).size, emojis.length, 'two actions share an emoji');
|
||||
|
||||
const labels = Object.keys(MODERATION_ACTIONS).map(moderationLabel);
|
||||
assert.equal(new Set(labels).size, labels.length, 'two actions read the same');
|
||||
assert.equal(moderationLabel('inconnu'), 'inconnu', 'an unknown action must stay readable');
|
||||
});
|
||||
|
||||
it('never reads a mute like a kick', async () => {
|
||||
// Reported from the moderation log channel: a timeout was filed as a
|
||||
// temporary kick because both labels sat next to each other.
|
||||
const { moderationLabel } = await import('../src/services/moderation/moderation-service.js');
|
||||
|
||||
assert.equal(moderationLabel('mute'), '🔇 Mise en sourdine');
|
||||
assert.equal(moderationLabel('kick'), '👢 Expulsion');
|
||||
});
|
||||
});
|
||||
|
||||
describe('event modules', () => {
|
||||
it('exports a name and a handler', async () => {
|
||||
const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js'));
|
||||
|
||||
@@ -11,6 +11,11 @@ import {
|
||||
removeNotificationChannel,
|
||||
setNotificationChannel,
|
||||
} from '../src/database/repositories/notification-repository.js';
|
||||
import {
|
||||
clearRulesMessage,
|
||||
getRulesMessage,
|
||||
setRulesMessage,
|
||||
} from '../src/database/repositories/rules-repository.js';
|
||||
import {
|
||||
castVote,
|
||||
closePoll,
|
||||
@@ -29,7 +34,7 @@ import {
|
||||
|
||||
const reset = () =>
|
||||
getDatabase().exec(
|
||||
'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels;',
|
||||
'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels; DELETE FROM rules_messages;',
|
||||
);
|
||||
|
||||
describe('ticket repository', () => {
|
||||
@@ -187,3 +192,25 @@ describe('notification repository', () => {
|
||||
assert.equal(removeNotificationChannel('g', 'release'), 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rules repository', () => {
|
||||
before(() => initDatabase(':memory:'));
|
||||
after(() => closeDatabase());
|
||||
beforeEach(reset);
|
||||
|
||||
it('keeps one rules message per guild and replaces it', () => {
|
||||
setRulesMessage({ guildId: 'g', channelId: 'c1', messageId: 'm1', updatedBy: 'mod' });
|
||||
setRulesMessage({ guildId: 'g', channelId: 'c1', messageId: 'm2', updatedBy: 'mod' });
|
||||
|
||||
const stored = getRulesMessage('g');
|
||||
assert.equal(stored.message_id, 'm2');
|
||||
assert.equal(stored.updated_by, 'mod');
|
||||
assert.equal(getRulesMessage('other'), null);
|
||||
});
|
||||
|
||||
it('forgets the message when it is cleared', () => {
|
||||
setRulesMessage({ guildId: 'g', channelId: 'c1', messageId: 'm1' });
|
||||
assert.equal(clearRulesMessage('g'), 1);
|
||||
assert.equal(getRulesMessage('g'), null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, beforeEach, describe, it } from 'node:test';
|
||||
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
|
||||
import { publishRules, rulesStatus } from '../src/services/rules/rules-service.js';
|
||||
|
||||
// The dashboard relies on `CHANNEL_RULES_ID`, which no CI run declares, so the
|
||||
// channel is passed explicitly here rather than read from the environment.
|
||||
const RULES_CHANNEL = '1234567890123456789';
|
||||
|
||||
/** A Discord client reduced to what saving the rules touches. */
|
||||
function harness({ pinFails = false, notEditable = false } = {}) {
|
||||
const state = { sent: [], edited: [], pinned: [], messages: new Map() };
|
||||
|
||||
// Discord edits a message in place: the id, the link and the pin stay.
|
||||
const withEdit = (message) => ({
|
||||
...message,
|
||||
edit: async ({ embeds }) => {
|
||||
state.edited.push({ id: message.id, description: embeds[0].toJSON().description });
|
||||
return message;
|
||||
},
|
||||
});
|
||||
|
||||
const channel = {
|
||||
isSendable: () => true,
|
||||
async send(payload) {
|
||||
const id = `message-${state.sent.length + 1}`;
|
||||
state.sent.push({ id, payload });
|
||||
state.messages.set(id, { id, editable: !notEditable });
|
||||
return {
|
||||
...withEdit({ id, url: `https://discord.test/${id}` }),
|
||||
pin: async () => {
|
||||
if (pinFails) throw new Error('Missing Permissions');
|
||||
state.pinned.push(id);
|
||||
},
|
||||
};
|
||||
},
|
||||
messages: {
|
||||
fetch: async (id) => {
|
||||
const message = state.messages.get(id);
|
||||
return message ? withEdit(message) : null;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return { state, client: { channels: { fetch: async () => channel } } };
|
||||
}
|
||||
|
||||
const publish = (client, markdown = '## Règlement\n\n1. Reste.bg') =>
|
||||
publishRules(client, { guildId: 'g', markdown, actorId: 'mod', channelId: RULES_CHANNEL });
|
||||
|
||||
const description = (entry) => entry.payload.embeds[0].toJSON().description;
|
||||
|
||||
describe('rules service', () => {
|
||||
before(() => initDatabase(':memory:'));
|
||||
after(() => closeDatabase());
|
||||
beforeEach(() => getDatabase().exec('DELETE FROM rules_messages;'));
|
||||
|
||||
it('sends and pins the rules the first time', async () => {
|
||||
const { state, client } = harness();
|
||||
|
||||
const result = await publish(client, '**Pas de contenu illégal.**');
|
||||
|
||||
assert.equal(state.sent.length, 1);
|
||||
assert.equal(description(state.sent[0]), '**Pas de contenu illégal.**');
|
||||
assert.deepEqual(state.pinned, ['message-1']);
|
||||
assert.deepEqual({ pinned: result.pinned, edited: result.edited }, { pinned: true, edited: false });
|
||||
assert.equal(rulesStatus('g', RULES_CHANNEL).messageId, 'message-1');
|
||||
});
|
||||
|
||||
it('edits the published message instead of sending a second one', async () => {
|
||||
const { state, client } = harness();
|
||||
|
||||
await publish(client, 'Version 1');
|
||||
const result = await publish(client, 'Version 2');
|
||||
|
||||
assert.equal(state.sent.length, 1, 'a second message was sent');
|
||||
assert.deepEqual(state.edited, [{ id: 'message-1', description: 'Version 2' }]);
|
||||
assert.equal(result.messageId, 'message-1', 'the message id must not change');
|
||||
assert.equal(result.edited, true);
|
||||
});
|
||||
|
||||
it('sends a new one when the previous message is gone', async () => {
|
||||
const { state, client } = harness();
|
||||
|
||||
await publish(client, 'Version 1');
|
||||
state.messages.clear();
|
||||
|
||||
const result = await publish(client, 'Version 2');
|
||||
|
||||
assert.equal(state.sent.length, 2);
|
||||
assert.equal(result.edited, false);
|
||||
assert.equal(result.messageId, 'message-2');
|
||||
});
|
||||
|
||||
it('sends a new one when the bot may no longer edit it', async () => {
|
||||
const { state, client } = harness({ notEditable: true });
|
||||
|
||||
await publish(client, 'Version 1');
|
||||
const result = await publish(client, 'Version 2');
|
||||
|
||||
assert.equal(state.sent.length, 2);
|
||||
assert.equal(result.edited, false);
|
||||
});
|
||||
|
||||
it('publishes even when the bot cannot pin', async () => {
|
||||
const { state, client } = harness({ pinFails: true });
|
||||
|
||||
const result = await publish(client);
|
||||
|
||||
assert.deepEqual(state.pinned, []);
|
||||
assert.equal(result.pinned, false);
|
||||
assert.equal(rulesStatus('g', RULES_CHANNEL).messageId, 'message-1');
|
||||
});
|
||||
|
||||
it('refuses an empty or oversized regulation', async () => {
|
||||
const { client } = harness();
|
||||
|
||||
await assert.rejects(() => publish(client, ' '), /vide/);
|
||||
await assert.rejects(() => publish(client, 'a'.repeat(4001)), /4000 caractères/);
|
||||
});
|
||||
|
||||
it('refuses to publish without a rules channel', async () => {
|
||||
const { client } = harness();
|
||||
|
||||
await assert.rejects(
|
||||
() => publishRules(client, { guildId: 'g', markdown: 'Règlement', channelId: '' }),
|
||||
/CHANNEL_RULES_ID/,
|
||||
);
|
||||
});
|
||||
|
||||
it('reports the configured channel to the dashboard', () => {
|
||||
assert.deepEqual(rulesStatus('g', RULES_CHANNEL), {
|
||||
channelId: RULES_CHANNEL,
|
||||
configured: true,
|
||||
messageId: null,
|
||||
publishedAt: null,
|
||||
publishedBy: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user