12 Commits
Author SHA1 Message Date
BlackAngelTV be4981aa75 docs(readme): document the implemented features and the voice manager
The status tables now describe real behaviour, and the required intents and invite permissions include the new voice features so a fresh install works on the first try.
2026-09-15 14:51:22 +02:00
BlackAngelTV aa5343b4b2 test(app): add command and event loading smoke tests
Loading every module catches broken imports and invalid slash command definitions, which unit tests on the services cannot see.
2026-09-15 14:51:18 +02:00
BlackAngelTV 5191942d5a feat(voice): add temporary voice channel manager
Joining the trigger channel must feel instant and never leave orphan channels behind, so the ownership is stored in SQLite, empty channels are deleted after a short grace period and a startup sweep cleans up whatever a restart left behind.
2026-09-15 14:51:17 +02:00
BlackAngelTV ef1bedbc65 feat(polls): implement polls, fun and statistics commands
A poll must end even when nobody is there to close it, so a scheduler reads the stored end dates and finalises the results at startup and while running.
2026-09-15 14:50:54 +02:00
BlackAngelTV f29c09577a feat(members): add welcome, default role and departure reporting
The welcome direct message is best effort: a member with closed private messages must still receive the channel message and the default role.
2026-09-15 14:50:48 +02:00
BlackAngelTV c49c60071d feat(moderation): implement the moderation service and commands
Every action checks the role hierarchy before touching Discord, then records the sanction in SQLite and mirrors it in the moderation log channel, so the history outlives the audit log.
2026-09-15 14:50:48 +02:00
BlackAngelTV e8c95b2ba3 feat(tickets): implement the ticket service, command and channel controls
Each ticket category is visible to a different set of staff roles, and the claim and close actions must also be reachable from the channel itself, so the buttons live in the ticket and share the service checks.
2026-09-15 14:50:47 +02:00
BlackAngelTV a5280ce205 feat(notifications): dispatch Gitea webhooks through the notification service
A guild can reroute a notification type to its own channel from SQLite, with the environment values as fallback, without editing the configuration or restarting the bot.
2026-09-15 14:50:41 +02:00
BlackAngelTV 26d7cce05f feat(fws): implement the version, status and changelog subcommands
Status reports each dependency separately so a Gitea outage never hides a database or webhook problem.
2026-09-15 14:50:41 +02:00
BlackAngelTV 76d0bf9250 feat(gitea): add embeds, modals and the issue and pull request commands
Creating an issue or a pull request needs a title and a description, which do not fit in a slash command option, so the branches chosen as options are kept in memory for a few minutes until the modal is submitted.
2026-09-15 14:50:40 +02:00
BlackAngelTV 66be463ba3 feat(core): add shared constants, interaction components and Gitea client helpers
Moderation, tickets, polls and Gitea events reuse the same labels, colours and buttons; normalising list responses in the client keeps both commands and webhooks free of version quirks.
2026-09-15 14:50:34 +02:00
BlackAngelTV 03a217c775 feat(database): add repositories for tickets, moderation, polls and notifications
Keep every SQL statement out of the command layer so each feature can be built and tested without a Discord dependency.
2026-09-15 14:50:34 +02:00
55 changed files with 4549 additions and 301 deletions

No files matched your search

+6
View File
@@ -42,6 +42,12 @@ CHANNEL_NOTIF_ERRORS_ID=
# Category under which private ticket channels are created (M6) # Category under which private ticket channels are created (M6)
CATEGORY_TICKETS_ID= CATEGORY_TICKETS_ID=
# --- Salons vocaux temporaires (M14) ----------------------------------------
# Salon vocal « rejoindre pour créer » : y entrer crée un salon temporaire
CHANNEL_VOICE_TRIGGER_ID=
# Catégorie d'accueil des salons vocaux créés (facultatif)
CATEGORY_VOICE_ID=
# --- Gitea (M5-T01) ---------------------------------------------------------- # --- Gitea (M5-T01) ----------------------------------------------------------
GITEA_URL=https://gitea.nocode-var.tech GITEA_URL=https://gitea.nocode-var.tech
# Token with least privilege (read:repository, write:issue). Never log it. # Token with least privilege (read:repository, write:issue). Never log it.
+359 -178
View File
@@ -1,221 +1,402 @@
# Documentation fonctionnelle — FWS-Bot # FWS-Bot
> Documentation de référence du bot Discord de l'organisation open source FWS. > Bot Discord de l'organisation open source **FWS** — assistance communautaire, tickets, modération, intégration Gitea et statistiques pour **FWS Arch** (fork d'Arch Linux avec surcouche conviviale).
## 1. Contexte de l'organisation Statut : **fonctionnel**. Les 18 commandes sont implémentées (assistance, tickets privés, modération, Gitea, sondages, statistiques, gestionnaire de salons vocaux), tout comme l'accueil des membres et la diffusion des webhooks Gitea.
**FWS** est une organisation open source multi-projets. Chaque projet peut choisir librement sa stack technique, sans restriction de langage. ---
Le projet principal est **FWS Arch**, un fork d'Arch Linux avec une surcouche conviviale qui simplifie l'installation et l'utilisation quotidienne. ## 1. Stack technique
FWS-Bot est le bot Discord du serveur communautaire FWS. Il s'adresse aux utilisateurs de FWS Arch, aux développeurs et au staff. Choix assumés : **une seule dépendance runtime** (discord.js), aucun module natif à compiler, outil de test intégré à Node.
## 2. Objectifs du bot | Techno | Version | Rôle |
FWS-Bot a pour objectifs de :
- centraliser les informations relatives à FWS et FWS Arch ;
- faciliter l'assistance aux utilisateurs ;
- permettre la création d'issues et de pull requests Gitea depuis Discord ;
- diffuser l'activité du projet ;
- organiser les tickets privés ;
- fournir des outils de modération ;
- présenter des statistiques Discord, Gitea et FWS ;
- conserver des logs utiles au suivi et à la sécurité.
Les commandes utilisent le préfixe slash `/` et privilégient les embeds Discord modernes, accompagnés de boutons, menus, liens et captures lorsque cela est pertinent.
## 3. Utilisateurs et permissions
### Owner
Accès complet : configuration, rôles, intégrations, commandes de développement, modération, tickets, notifications, statistiques et logs.
### Dev
Accès aux commandes permettant de configurer les informations et les fonctions qui touchent directement à FWS Arch et à son développement. Les Dev peuvent également utiliser les fonctions Gitea autorisées.
### Staff
Accès aux fonctions de modération, de support et de gestion des tickets, selon les permissions Discord configurées.
### User / Membre
Accès aux commandes d'information, aux ressources publiques, aux statistiques publiques et aux commandes fun. Un membre peut également ouvrir un ticket lorsque le serveur l'autorise.
## 4. Commandes fonctionnelles
Les noms suivants constituent une organisation fonctionnelle recommandée. Ils peuvent être adaptés aux noms réellement enregistrés dans Discord.
### Informations FWS
| Commande | Accès | Résultat |
| --- | --- | --- | | --- | --- | --- |
| `/fws info` | Tous | Présente FWS, FWS Arch, les objectifs et les liens officiels. | | **Node.js** | ≥ 22.13.0 (ESM) | Runtime. Requis pour `node:sqlite`, `process.loadEnvFile`, `--watch` |
| `/fws version` | Tous | Affiche la version actuelle de FWS Arch. | | **discord.js** | ^14.21.0 | API Discord : commandes slash, embeds, boutons, intents |
| `/fws status` | Tous | Présente l'état connu des services et projets. | | **`node:sqlite`** | module natif | Base SQLite (WAL, foreign keys) — pas de `better-sqlite3` ni compilation |
| `/fws links` | Tous | Affiche les ressources Discord, Gitea, dépôt et documentation. | | **`fetch` natif** | — | Client REST Gitea (avec `AbortSignal.timeout`) |
| `/fws changelog` | Tous | Présente les changements d'une version ou de la dernière release. | | **`node:http`** | — | Serveur de webhooks Gitea (sans Express) |
| `/help` | Tous | Affiche les commandes accessibles selon le rôle de l'utilisateur. | | **`node:crypto`** | — | Signature HMAC-SHA256 des webhooks |
| **`node:test`** | — | Tests unitaires intégrés (`node --test`) |
| **ESLint** | ^9.30.0 (flat config) | Lint |
| **Prettier** | ^3.6.2 | Format |
### Issues et pull requests ## 2. Prérequis
| Commande | Accès | Résultat | - Node.js ≥ 22.13 (`node -v` pour vérifier) et npm
- Une application Discord (gratuite) avec un token de bot
- (Optionnel) une instance Gitea pour les issues/PR et les webhooks
## 3. Démarrage rapide avec un token de test
### 3.1 Créer l'application Discord
1. Ouvre le [Discord Developer Portal](https://discord.com/developers/applications) → **New Application**.
2. Onglet **Bot** → **Reset Token** → copie le token : c'est ton `DISCORD_TOKEN` (ne le partage jamais, ne le committe jamais).
3. Toujours dans **Bot** → **Privileged Gateway Intents** → active **Server Members Intent** (requis pour l'accueil des nouveaux membres ; `Message Content` n'est pas nécessaire).
4. Onglet **General Information** → copie l'**Application ID** : c'est ton `DISCORD_CLIENT_ID`.
### 3.2 Inviter le bot sur un serveur de test
Remplace `CLIENT_ID` par ton Application ID :
```text
https://discord.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot+applications.commands&permissions=1099812662294
```
Cette URL pré-coche les permissions utilisées par les commandes : Voir les salons, Envoyer des messages, Gérer les messages, Intégrer des liens, Lire l'historique, Expulser, Bannir, Gérer les rôles, Modérer les membres (timeout), ainsi que celles des salons vocaux : Gérer les salons, Se connecter, Parler, Rendre muet, Rendre sourd, Déplacer les membres. Tu peux aussi passer par **OAuth2 → URL Generator** avec les scopes `bot` + `applications.commands`.
Crée (ou utilise) un serveur de test dont tu es propriétaire : c'est lui qui donne le niveau **Owner** au bot.
### 3.3 Récupérer les IDs Discord
Sur Discord : **Paramètres → Avancés → Mode développeur** activé, puis clic droit sur un serveur / salon / rôle → **Copier l'identifiant**.
| Variable | Où le trouver |
| --- | --- |
| `DISCORD_GUILD_ID` | Clic droit sur le serveur de test |
| `ROLE_OWNER_ID`, `ROLE_DEV_ID`, `ROLE_STAFF_ID`, `ROLE_MEMBER_ID` | Paramètres du serveur → Rôles (crée-les d'abord) |
| `CHANNEL_WELCOME_ID`, `CHANNEL_LOGS_ID`, etc. | Clic droit sur chaque salon |
> Si les rôles ne sont pas configurés, tout le monde est considéré **User** (sauf le propriétaire du serveur = Owner).
### 3.4 Lancer le bot
```bash
# 1. Dépendances
npm install
# 2. Configuration : copie .env.example vers .env puis remplis-le
# Minimum requis : DISCORD_TOKEN, DISCORD_CLIENT_ID, DISCORD_GUILD_ID
cp .env.example .env
# 3. Créer la base SQLite et appliquer les migrations
npm run db:init
# 4. Enregistrer les commandes slash sur le serveur (instantané, par guild)
npm run deploy:commands
# 5. Démarrer avec rechargement automatique
npm run dev
```
Dans les logs tu dois voir `Connected as <NomDuBot>`. Tape `/help` sur le serveur : tu dois voir la liste des commandes accessibles selon ton rôle.
Sans `.env`, le bot refuse de démarrer (`assertRequiredEnv` vérifie token, client ID et guild ID).
## 4. Configuration — toutes les variables (`.env`)
Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre parenthèses.
### Runtime
| Variable | Défaut | Description |
| --- | --- | --- | | --- | --- | --- |
| `/issue create` | Selon configuration | Crée une issue Gitea depuis un formulaire Discord. | | `NODE_ENV` | `development` | `development` \| `production` \| `test` |
| `/issue view` | Tous | Affiche le titre, l'auteur, le statut, les détails et le lien d'une issue. | | `LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` |
| `/issue list` | Tous | Liste les issues ouvertes, récentes ou filtrées. | | `LOG_DIR` | `./logs` | Dossier des logs JSON journaliers |
| `/pr create` | Dev, Owner | Crée une pull request Gitea depuis Discord. | | `LOG_RETENTION_DAYS` | `30` | Durée de conservation (purge des `event_logs`) |
| `/pr view` | Tous | Affiche les informations et le lien d'une pull request. |
| `/pr list` | Tous | Liste les pull requests ouvertes ou récentes. |
| `/gitea activity` | Tous | Affiche les commits, issues, PR et événements récents. |
| `/gitea release` | Tous | Affiche les releases disponibles de FWS Arch. |
Les créations peuvent être effectuées depuis Discord et doivent produire un lien vers l'élément Gitea créé. Les permissions sont vérifiées avant toute écriture. ### Application Discord
### Tickets et support | Variable | Description |
| --- | --- |
| `DISCORD_TOKEN` | **Requis.** Token du bot (Developer Portal → Bot) |
| `DISCORD_CLIENT_ID` | **Requis.** Application ID |
| `DISCORD_GUILD_ID` | **Requis.** Serveur d'enregistrement des commandes slash |
| Commande | Accès | Résultat | ### Rôles FWS (IDs de rôles Discord)
| --- | --- | --- |
| `/ticket create` | Membre | Crée un espace privé selon la catégorie choisie. |
| `/ticket close` | Auteur, Staff, Owner | Ferme le ticket et journalise sa clôture. |
| `/ticket claim` | Staff, Owner | Indique quel membre du staff prend le ticket en charge. |
| `/ticket add` | Staff, Owner | Ajoute une personne autorisée au périmètre du ticket. |
Les tickets sont privés par défaut. Leur scope dépend de leur catégorie : support utilisateur, bug, question de développement, signalement ou demande interne. | Variable | Niveau correspondant |
| --- | --- |
| `ROLE_OWNER_ID` | Owner — accès complet |
| `ROLE_DEV_ID` | Dev — configuration FWS Arch, écritures Gitea |
| `ROLE_STAFF_ID` | Staff — modération, support, tickets |
| `ROLE_MEMBER_ID` | Rôle initial attribué aux nouveaux membres |
### Modération ### Salons Discord (IDs)
| Commande | Accès | Résultat | | Variable | Usage |
| --- | --- | --- | | --- | --- |
| `/warn` | Staff, Owner | Avertit un membre et enregistre l'action. | | `CHANNEL_WELCOME_ID` | Messages de bienvenue |
| `/mute` | Staff, Owner | Restreint temporairement les interactions d'un membre. | | `CHANNEL_RULES_ID` | Règlement (lien envoyé aux nouveaux) |
| `/kick` | Staff, Owner | Retire un membre du serveur. | | `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS |
| `/ban` | Staff autorisé, Owner | Bannit un membre selon les règles de modération. | | `CHANNEL_LOGS_ID` | Logs fonctionnels |
| `/clear` | Staff, Owner | Supprime un nombre contrôlé de messages. | | `CHANNEL_MOD_LOGS_ID` | Logs de modération |
| `/mod logs` | Staff, Owner | Consulte les actions de modération disponibles. | | `CHANNEL_TICKETS_LOGS_ID` | Journal d'ouverture/fermeture des tickets |
| `/role set` | Dev autorisé, Staff autorisé, Owner | Attribue ou retire un rôle selon la configuration. | | `CHANNEL_NOTIF_ISSUES_ID` | Notifications issues |
| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Notifications pull requests |
Le bot doit empêcher les actions sur des rôles supérieurs et effectuer les contrôles de permissions côté serveur. | `CHANNEL_NOTIF_COMMITS_ID` | Notifications commits |
| `CHANNEL_NOTIF_RELEASES_ID` | Notifications releases |
### Communauté et statistiques | `CHANNEL_NOTIF_ERRORS_ID` | Erreurs et incidents |
| `CATEGORY_TICKETS_ID` | Catégorie où sont créés les salons de tickets privés |
| Commande | Accès | Résultat | | `CHANNEL_VOICE_TRIGGER_ID` | Salon vocal déclencheur : y entrer crée un salon temporaire |
| --- | --- | --- | | `CATEGORY_VOICE_ID` | Catégorie d'accueil des salons vocaux créés (facultatif) |
| `/poll create` | Staff, Dev, Owner | Crée un sondage avec choix et durée. |
| `/poll close` | Créateur autorisé, Staff, Owner | Ferme un sondage et affiche les résultats. |
| `/stats discord` | Tous | Affiche les statistiques publiques du serveur Discord. |
| `/stats gitea` | Tous | Affiche l'activité et les indicateurs Gitea. |
| `/stats fws` | Tous | Affiche les indicateurs disponibles de FWS/FWS Arch. |
| `/fun` | Membres | Affiche les commandes de divertissement. |
## 5. Automatisations
### Bienvenue et rôles
À l'arrivée d'un membre, FWS-Bot peut envoyer un message de bienvenue, présenter FWS Arch, fournir les règles et liens utiles, attribuer un rôle initial et enregistrer l'événement.
Les changements de rôles doivent respecter la hiérarchie Discord et être journalisés lorsqu'ils sont sensibles.
### Notifications
Les notifications couvrent notamment :
- nouvelles issues et changements de statut ;
- nouvelles pull requests et changements de statut ;
- commits ;
- releases ;
- annonces FWS ;
- erreurs et incidents techniques ;
- événements communautaires configurés.
Chaque catégorie de notification doit pouvoir être associée à un canal dédié et à un niveau de détail adapté.
### Sondages
Les sondages utilisent les composants Discord disponibles. Le bot contrôle les votes, respecte la durée définie et publie les résultats à la clôture.
### Statistiques
Les statistiques peuvent provenir de trois domaines :
- **Discord** : membres, activité et évolution de la communauté ;
- **Gitea** : issues, PR, commits, contributeurs et releases ;
- **FWS Arch** : versions, activité ou indicateurs fournis par les services du projet.
## 6. Intégrations et stockage
### Gitea ### Gitea
Gitea est utilisé pour consulter et créer les issues et pull requests, suivre les commits et releases, et transmettre les notifications de développement vers Discord. | Variable | Défaut | Description |
| --- | --- | --- |
| `GITEA_URL` | — | URL de l'instance (sans `/` final) |
| `GITEA_TOKEN` | — | Token à moindre privilège (`read:repository`, `write:issue`). Jamais loggé |
| `GITEA_OWNER` | — | Propriétaire du dépôt (ex. `FWS`) |
| `GITEA_REPO` | — | Dépôt ciblé (ex. `FWS-Arch`) |
| `GITEA_TIMEOUT_MS` | `10000` | Timeout des requêtes |
| `GITEA_MAX_RETRIES` | `2` | Tentatives sur erreurs transitoires (429, 5xx, timeout) |
Les embeds peuvent afficher le titre, l'auteur, le statut, la date, un résumé et un lien direct. Les tokens d'accès ne doivent jamais apparaître dans Discord ni dans les logs. ### Webhooks Gitea
### SQLite | Variable | Défaut | Description |
| --- | --- | --- |
| `WEBHOOK_ENABLED` | `false` | Démarre le serveur HTTP de réception |
| `WEBHOOK_HOST` | `0.0.0.0` | Interface d'écoute |
| `WEBHOOK_PORT` | `3000` | Port d'écoute |
| `WEBHOOK_PATH` | `/webhooks/gitea` | Chemin à configurer dans Gitea |
| `GITEA_WEBHOOK_SECRET` | — | Secret partagé (HMAC-SHA256), défini dans Gitea → Webhooks |
SQLite stocke les données locales nécessaires au bot, par exemple les paramètres des serveurs, les catégories de tickets, les associations de canaux, les sondages et les événements journalisés. ### SQLite et liens
La base doit être protégée, sauvegardée et exclue du dépôt si elle contient des données réelles. | Variable | Défaut | Description |
| --- | --- | --- |
| `DATABASE_PATH` | `./data/fws-bot.sqlite` | Fichier de base (exclu de git) |
| `BACKUP_DIR` | `./data/backups` | Dossier de sauvegarde |
| `FWS_WEBSITE_URL`, `FWS_DOCS_URL`, `FWS_DISCORD_INVITE_URL`, `FWS_ARCH_REPO_URL` | — | Liens officiels affichés par `/fws info` et `/fws links` (les boutons vides sont omis) |
## 7. Embeds, liens et captures ## 5. Commandes slash
Les réponses doivent utiliser une identité visuelle cohérente : 18 commandes sont enregistrées. Chaque commande a un **niveau d'accès FWS** vérifié côté serveur avant exécution, et les commandes de modération vérifient en plus les **permissions Discord** (`DefaultMemberPermissions`).
- titres courts ; ### Niveaux d'accès
- champs structurés ;
- couleurs par catégorie ;
- boutons vers Gitea et la documentation ;
- footer FWS-Bot ;
- messages d'erreur compréhensibles.
Les captures doivent être placées dans un dossier dédié, par exemple `assets/screenshots/`, puis référencées ainsi : Résolus depuis les rôles configurés dans `.env` (du plus haut au plus bas) :
```md | Niveau | Qui |
![Présentation de FWS-Bot](../assets/screenshots/fws-info.png) | --- | --- |
| `OWNER` (3) | Rôle Owner, ou propriétaire du serveur |
| `DEV` (2) | Rôle Dev |
| `STAFF` (1) | Rôle Staff |
| `USER` (0) | Tous les membres |
### Générales et FWS
| Commande | Options | Accès | État | Description |
| --- | --- | --- | --- | --- |
| `/help` | — | User | ✅ | Liste les commandes accessibles selon ton rôle (réponse éphémère) |
| `/fws info` | — | User | ✅ | Présente FWS et FWS Arch (texte surchargeable via `guild_settings`) + liens officiels |
| `/fws links` | — | User | ✅ | Ressources : site, docs, dépôt, Gitea, Discord |
| `/fws version` | — | User | ✅ | Dernière release Gitea (tag, date, auteur) + bouton vers les notes |
| `/fws status` | — | User | ✅ | État des services : API Gitea, webhooks, SQLite, latence Discord, uptime |
| `/fws changelog` | `version` (optionnel) | User | ✅ | Notes de version (dernière par défaut, message clair si le tag n'existe pas) |
### Gitea — issues et pull requests
| Commande | Options | Accès | État | Description |
| --- | --- | --- | --- | --- |
| `/issue create` | — (modale : titre + description) | User (configurable) | ✅ | Crée une issue Gitea et renvoie son lien |
| `/issue view` | `number` | User | ✅ | Titre, auteur, état, labels, lien d'une issue |
| `/issue list` | — | User | ✅ | Issues ouvertes (15 dernières) |
| `/pr create` | `head`, `base` + modale (titre, description) | **Dev** | ✅ | Crée une pull request Gitea |
| `/pr view` | `number` | User | ✅ | Titre, auteur, état, branches, lien d'une PR |
| `/pr list` | — | User | ✅ | PR ouvertes (15 dernières) |
| `/gitea activity` | — | User | ✅ | Derniers commits + issues et PR ouvertes |
| `/gitea release` | — | User | ✅ | Releases de FWS Arch (5 dernières) |
> Le client Gitea (`src/services/gitea/gitea-client.js`) : REST avec token, timeout, retry exponentiel sur erreurs transitoires. Les formulaires (`/issue create`, `/pr create`) passent par une **modale** ; les options de branches y sont conservées en mémoire quelques minutes (`pending-actions.js`). Toute panne (token absent, 404, 5xx) devient un message éphémère explicite, jamais une erreur brute.
### Tickets de support
Les tickets sont des salons privés créés sous `CATEGORY_TICKETS_ID`. Un seul ticket ouvert par membre et par catégorie (contrainte SQL).
| Commande | Options | Accès | État | Description |
| --- | --- | --- | --- | --- |
| `/ticket create` | `category` (obligatoire) | User (selon la catégorie) | ✅ | Crée un salon privé sous `CATEGORY_TICKETS_ID` |
| `/ticket close` | `reason` (optionnel, 500 car.) | Auteur, Staff | ✅ | Ferme, journalise puis supprime le salon (10 s) — aussi via le bouton **Fermer** |
| `/ticket claim` | — | **Staff** | ✅ | Prend le ticket en charge (bouton **Prendre en charge**) |
| `/ticket add` | `user` | **Staff** | ✅ | Ajoute un participant au salon privé |
Catégories disponibles et qui y a accès :
| Catégorie | Visible par |
| --- | --- |
| Support utilisateur | Staff, Owner |
| Bug | Staff, Dev, Owner |
| Question de développement | Dev, Owner |
| Signalement | Staff, Owner |
| Demande interne | Owner |
### Salons vocaux temporaires
Rejoindre le salon déclencheur (`CHANNEL_VOICE_TRIGGER_ID`, ou `/voice setup`) crée un salon vocal privé, déplace le membre dedans et lui en donne la propriété : il le gère ensuite depuis le **panneau de contrôle** publié dans le chat du salon (boutons *Renommer*, *Limiter*, *Verrouiller*, *Réclamer*, *Supprimer* et menus *Autoriser*, *Exclure*, *Transférer*) ou avec `/voice`. Le nombre de salons simultanés est **illimité**.
| Commande | Options | Accès | Description |
| --- | --- | --- | --- |
| `/voice setup` | `trigger`, `category`, `template`, `limit`, `panel` | **Staff** | Configure le salon déclencheur, la catégorie d'accueil, le modèle de nom et la limite par défaut |
| `/voice config` | — | User | Configuration actuelle : déclencheur, catégorie, modèle, limite, salons actifs |
| `/voice panel` | — | **Staff** | Republie le panneau d'explication dans le salon déclencheur |
| `/voice name` | `name` (100 car.) | Propriétaire | Renomme le salon |
| `/voice limit` | `limit` (0–99, 0 = illimité) | Propriétaire | Nombre de places |
| `/voice lock` · `/voice unlock` | — | Propriétaire | Refuse · autorise l'accès de tout le monde |
| `/voice permit` | `user` | Propriétaire | Autorise un membre à rejoindre le salon |
| `/voice reject` | `user` | Propriétaire | Interdit l'accès (et l'éjecte s'il y est déjà) |
| `/voice kick` | `user` | Propriétaire | Éjecte un membre du salon |
| `/voice transfer` | `user` | Propriétaire | Transfère la propriété (le nouveau doit être dans le salon) |
| `/voice claim` | — | Membre du salon | Récupère un salon dont le propriétaire est parti |
| `/voice delete` | `channel` (staff) | Propriétaire, Staff | Supprime immédiatement le salon |
| `/voice info` | `channel` (staff) | User | Propriétaire, état, limite, membres, ancienneté |
> Modèle de nom : `{user}` est remplacé par le pseudo du membre (défaut `🔊 Salon de {user}`). Le staff peut toujours agir sur n'importe quel salon temporaire. Le propriétaire reçoit `Gérer le salon` + `Déplacer des membres` sur son seul salon.
### Modération
Chaque commande vérifie le niveau FWS **et** la permission Discord correspondante. Le bot refuse d'agir sur un membre dont le plus haut rôle est égal ou supérieur à celui de l'auteur (`canActOn`), et n'agit jamais sur le propriétaire du serveur.
| Commande | Options | Permission Discord | État | Description |
| --- | --- | --- | --- | --- |
| `/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 |
| `/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) |
| `/mod logs` | `user` (filtre) | Modérer les membres | ✅ | Historique lu depuis `moderation_actions` (15 dernières, éphémère) |
| `/role set` | `user`, `role`, `action` (`add`/`remove`) | Gérer les rôles | ✅ | Attribue ou retire un rôle (double hiérarchie vérifiée) |
| `/notify set` | `type`, `channel` | Gérer le serveur | ✅ | Salon de notification propre à ce serveur (SQLite) |
| `/notify remove` | `type` | Gérer le serveur | ✅ | Revenir au salon par défaut (variables d'environnement) |
| `/notify list` | — | Gérer le serveur | ✅ | Configuration actuelle de chaque type |
> Chaque action réussie est enregistrée dans `moderation_actions` **et** publiée dans `CHANNEL_MOD_LOGS_ID` (cible, modérateur, raison, durée).
### Communauté et statistiques
| Commande | Options | Accès | État | Description |
| --- | --- | --- | --- | --- |
| `/poll create` | `question`, `choices` (« ; » séparés, 2–10), `minutes` (1–10080) | **Staff** | ✅ | Sondage voté par boutons, résultats en direct |
| `/poll close` | `id` | **Staff** | ✅ | Clôture, affiche le résultat gagnant et fige le message |
| `/stats discord` | — | User | ✅ | Membres, salons, rôles, boosts, âge du serveur, latence |
| `/stats gitea` | — | User | ✅ | Commits récents, issues et PR ouvertes, dernière release |
| `/stats fws` | — | User | ✅ | Indicateurs locaux (tickets, sondages, modération) + version FWS Arch |
| `/fun coinflip` | — | User | ✅ | Pile ou face |
| `/fun dice` | `sides` (2–1000, 6 par défaut) | User | ✅ | Lancer de dé |
| `/fun 8ball` | `question` | User | ✅ | Boule magique (12 réponses) |
| `/fun choose` | `options` (« ; » séparés, 2–10) | User | ✅ | Choix aléatoire argumenté |
Légende : ✅ fonctionnel · les erreurs attendues sont renvoyées en message éphémère (`UserFacingError`), les autres sont loggées et remplacées par un message générique.
## 6. Automatisations
- **Accueil** (`src/events/guild-member-add.js`) : attribution du rôle `ROLE_MEMBER_ID` (ignorée si le rôle est au-dessus de celui du bot), embed de bienvenue dans `CHANNEL_WELCOME_ID` avec renvoi vers `CHANNEL_RULES_ID`, et message privé contenant les liens officiels (silencieux si les MP sont fermés).
- **Départs** (`src/events/guild-member-remove.js`) : embed dans `CHANNEL_LOGS_ID` (repli sur `CHANNEL_MOD_LOGS_ID`) avec effectif, ancienneté et âge du compte.
- **Notifications** (`src/services/notifications/notification-service.js`) : routage par type — override par serveur en SQLite (`notification_channels`, configuré via `/notify set`), sinon la variable d'environnement correspondante. Un type sans salon est simplement ignoré (log en `debug`).
- **Webhooks Gitea** : serveur HTTP natif (`WEBHOOK_ENABLED=true`). Vérifie la signature **HMAC-SHA256** (`x-gitea-signature`) en temps constant, rejette les corps > 1 Mo et les JSON invalides, déduplique les redeliveries via `webhook_deliveries`, puis publie les embeds via le service de notifications : `issues` → issues, `pull_request` → PR, `push` → commits, `create`/`delete` → références, `release` → releases.
- **Sondages** (`src/services/polls/poll-service.js`) : un vote par membre et par sondage (modifiable, un clic change le vote), message rafraîchi à chaque vote, et un ordonnanceur ferme automatiquement les sondages arrivés à échéance (vérification toutes les 30 s) même après un redémarrage.
- **Salons vocaux** (`src/events/voice-state-update.js`) : entrer dans le salon déclencheur crée un salon temporaire et y déplace le membre (ou le renvoie dans celui qu'il possède déjà) ; un salon vide est supprimé après 5 s de grâce, ce qui laisse le temps de changer de salon sans le perdre ; au démarrage, `sweepVoiceChannels()` oublie les salons disparus et nettoie ceux que le redémarrage a laissés vides.
## 7. Architecture
Détails complets : [`docs/architecture.md`](docs/architecture.md).
```text
src/
├── index.js # Point d'entrée : env, DB, client, loaders, webhooks, shutdown propre
├── config/ # env.js (lecture/validation .env) · constants.js (couleurs, niveaux, catégories)
├── core/ # client.js · command-loader.js · event-loader.js
│ # permissions.js (niveaux + hiérarchie) · logger.js · errors.js
├── commands/<catégorie>/ # fws, gitea, tickets, moderation, community, general
├── events/ # interaction-create (commandes, boutons, modales), ready, member add/remove,
│ # voice state (salons vocaux), errors, shard
├── services/
│ ├── gitea/ # gitea-client.js (REST + retry) · gitea-embeds.js · gitea-modals.js · pending-actions.js
│ ├── members/ # member-service.js (accueil, rôle initial, départs)
│ ├── moderation/ # moderation-service.js (hiérarchie, sanctions, journal)
│ ├── notifications/ # notification-service.js (routage) · gitea-notifications.js (mapping webhooks)
│ ├── polls/ # poll-service.js (création, votes, clôture, ordonnanceur)
│ ├── tickets/ # ticket-service.js (salons privés, cycle de vie)
│ └── voice/ # voice-service.js (salons vocaux temporaires, panneau, permissions)
├── database/ # index.js (connexion + migrations SQL) · migrations/ · repositories/
├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch)
├── ui/ # embeds.js (identité visuelle) · buttons.js (liens, tickets, sondages)
└── utils/ # retry.js (backoff exponentiel) · cooldown.js
``` ```
## 8. Sécurité, limites et erreurs Chargement automatique : toute commande dans `src/commands/**` et tout événement dans `src/events/*` sont pris en compte au démarrage.
FWS-Bot doit respecter les limites et délais des API Discord et Gitea. Une erreur API ou un timeout doit : **Contrat d'une commande** (`access` vérifié dans `interaction-create.js`, une `UserFacingError` est affichée telle quelle, toute autre erreur est loggée et remplacée par un message générique) :
1. informer l'utilisateur sans exposer de détail sensible ; ```js
2. être enregistré dans les logs techniques ; export const access = ACCESS_LEVELS.STAFF; // niveau minimum
3. éviter les répétitions immédiates et les doublons ; export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optionnel, par sous-commande
4. utiliser une nouvelle tentative contrôlée uniquement si elle est prévue. export const data = new SlashCommandBuilder() /* ... */;
export async function execute(interaction) {}
```
Les entrées utilisateur doivent être validées. Les permissions doivent être vérifiées côté serveur. Les secrets, fichiers `.env*`, bases de données réelles et artefacts générés ne doivent jamais être commités. **Intents utilisés** : `Guilds`, `GuildMembers` *(privilégié — à activer dans le portail)*, `GuildModeration`, `GuildMessages`, `GuildVoiceStates`. `MessageContent` n'est volontairement pas demandé.
## 9. Conventions de contribution FWS ## 8. Base de données (SQLite)
- Messages de commit en anglais au format Conventional Commits : `<type>(<scope>): <description>`. - Moteur : `node:sqlite` (`DatabaseSync`), mode **WAL**, foreign keys activées.
- Types autorisés : `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`. - Migrations : fichiers SQL numérotés dans `src/database/migrations/`, appliqués en transaction et tracés dans `schema_migrations` (`npm run db:init`).
- Branches au format `type/description`. - Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `moderation_actions`, `polls`, `poll_votes`, `voice_channels` (propriétaire, verrouillage, limite), `event_logs`, `webhook_deliveries`.
- Fichiers en kebab-case. - Accès données : un repository par domaine (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-repository.js`) — les requêtes SQL ne sortent jamais de cette couche.
- Identifiants de code en anglais. - Les migrations `002-ticket-and-poll-details.sql` (traçabilité de prise en charge `claimed_at` et de fermeture `close_reason`) et `003-voice-channels.sql` (salons vocaux temporaires) complètent le schéma initial.
- Commentaires en anglais et uniquement lorsqu'ils expliquent un choix non évident. - La base contient des données réelles : elle est **exclue de git** (`.gitignore`) et doit être sauvegardée (`BACKUP_DIR`).
- Tests nommés avec des descriptions `describe` et `it` en anglais.
- Bugs et demandes suivis via les issues et le tableau Kanban.
- Une PR de correction doit référencer l'issue concernée, par exemple `Fixes #123`.
- Ne pas fermer ou modifier une issue sans demande explicite.
Les instructions complètes destinées aux agents sont disponibles dans `AGENTS.md`. ## 9. Logs
## 10. Ressources - Format **JSON**, une ligne par entrée, fichier par jour : `logs/AAAA-MM-JJ.log` + console.
- Niveaux filtrés par `LOG_LEVEL` ; erreurs et warnings sur stderr.
- **Masquage des secrets** : token Discord, token Gitea et secret webhook sont remplacés par `***` dans chaque ligne loggée.
- Rétention fonctionnelle : `LOG_RETENTION_DAYS` (purge des `event_logs`).
## 10. Scripts npm
| Script | Rôle |
| --- | --- |
| `npm start` | Démarre le bot (`node src/index.js`) |
| `npm run dev` | Démarre avec rechargement automatique (`node --watch`) |
| `npm run deploy:commands` | Enregistre les commandes slash sur le serveur `DISCORD_GUILD_ID` (à relancer après ajout/modification d'une commande) |
| `npm run db:init` | Crée la base SQLite et applique les migrations |
| `npm run lint` / `npm run lint:fix` | ESLint (vérifier / corriger) |
| `npm run format` / `npm run format:check` | Prettier (formater / vérifier) |
| `npm test` | Tests unitaires `node:test` : `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `database` |
En cas de souci : `npm run deploy:commands` après chaque changement de commandes, vérifie que l'intent **Server Members** est activé, et que le bot a bien les permissions listées en 3.2 sur ses salons cibles.
## 11. Sécurité
- Permissions vérifiées **côté serveur** (niveau FWS + permissions Discord + hiérarchie des rôles) : jamais confiance au client.
- Aucune action possible sur un rôle/membre positionné au-dessus de l'auteur.
- Secrets jamais committés (`.env` ignoré) ni loggés en clair (masquage automatique).
- Webhooks Gitea : signature HMAC-SHA256 obligatoire, comparaison à temps constant, corps limité à 1 Mo, anti-doublon sur l'ID de delivery.
- Tokens à moindre privilège ; rate limits respectés (timeout + retry contrôlé sur erreurs transitoires uniquement).
- Entrées utilisateur validées (`setMinValue`/`setMaxValue`/`setMaxLength` sur toutes les options).
## 12. Contribution
- Commits en anglais, **Conventional Commits** : `<type>(<scope>): <description>` — types : `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`.
- Branches `type/description` (ex. `feat/ticket-service`), fichiers en kebab-case, identifiants en anglais.
- Avant de proposer : `npm run lint`, `npm run format:check` et `npm test` doivent passer.
- Bugs et demandes suivis en issues (tableau Kanban) ; une PR de correctif référence l'issue (`Fixes #123`).
- Instructions complètes pour les agents IA : [`AGENTS.md`](AGENTS.md).
## 13. Checklist de mise en production
- [ ] Enregistrer les commandes slash sur le serveur FWS (`npm run deploy:commands`)
- [ ] Créer et configurer les rôles Owner, Dev, Staff, User (IDs dans `.env`)
- [ ] Définir les salons : bienvenue, tickets, notifications, logs
- [ ] Configurer les salons vocaux (`/voice setup`) et vérifier création/suppression automatique
- [ ] Activer l'intent **Server Members** dans le portail développeur
- [ ] Configurer Gitea : token à moindre privilège + webhook avec secret
- [ ] Protéger et sauvegarder la base SQLite
- [ ] Tester les parcours critiques : ticket de bout en bout, avertissement, sondage, webhook Gitea
- [ ] Tester les limites API et les chemins d'erreur
- [ ] Vérifier les embeds sur ordinateur et mobile
- [ ] Renseigner les liens officiels et les captures (`assets/screenshots/`)
## 14. Ressources
- Organisation FWS : `[lien à ajouter]` - Organisation FWS : `[lien à ajouter]`
- Serveur Discord FWS : `[lien à ajouter]` - Serveur Discord FWS : `[lien à ajouter]`
- Dépôt FWS Arch : `[lien à ajouter]` - Dépôt FWS Arch : `[lien à ajouter]`
- Instance Gitea : `[lien à ajouter]` - Instance Gitea : `[lien à ajouter]`
- Documentation FWS : `[lien à ajouter]` - Documentation FWS : `[lien à ajouter]`
- Documentation technique : [`docs/architecture.md`](docs/architecture.md)
## 11. Checklist
- [ ] Enregistrer les commandes slash sur le serveur FWS.
- [ ] Configurer les rôles Owner, Dev, Staff et User.
- [ ] Définir les canaux de bienvenue, tickets, notifications et logs.
- [ ] Configurer Gitea avec les permissions minimales.
- [ ] Protéger et sauvegarder SQLite.
- [ ] Tester les limites API et les erreurs.
- [ ] Vérifier les embeds sur ordinateur et mobile.
- [ ] Ajouter les liens et captures définitifs.
- [ ] Vérifier les tests, le typecheck et le lint lorsqu'ils existent.
+100 -5
View File
@@ -1,12 +1,107 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import { parseChoices } from '../../services/polls/poll-service.js';
import { baseEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder().setName('fun').setDescription('Commandes de divertissement'); const EIGHT_BALL_ANSWERS = Object.freeze([
'Oui, sans aucun doute.',
'Compte là-dessus et bois de l’eau.',
'Les signes disent que oui.',
'Impossible de le prédire pour le moment.',
'Concentre-toi et redemande.',
'Ma réponse est non.',
'Très probablement.',
'Mes sources disent non.',
'La réponse est floue, réessaie.',
'Absolument !',
'Pas dans un avenir proche.',
'Oui, mais fais attention à toi.',
]);
// TODO(M10-T07): add fun subcommands. const pick = (list) => list[Math.floor(Math.random() * list.length)];
export const data = new SlashCommandBuilder()
.setName('fun')
.setDescription('Commandes de divertissement')
.addSubcommand((sub) => sub.setName('coinflip').setDescription('Pile ou face'))
.addSubcommand((sub) =>
sub
.setName('dice')
.setDescription('Lancer un dé')
.addIntegerOption((option) =>
option
.setName('sides')
.setDescription('Nombre de faces (6 par défaut)')
.setMinValue(2)
.setMaxValue(1000),
),
)
.addSubcommand((sub) =>
sub
.setName('8ball')
.setDescription('Poser une question à la boule magique')
.addStringOption((option) =>
option.setName('question').setDescription('Ta question').setRequired(true).setMaxLength(300),
),
)
.addSubcommand((sub) =>
sub
.setName('choose')
.setDescription('Choisir au hasard parmi plusieurs options')
.addStringOption((option) =>
option.setName('options').setDescription('Options séparées par ";" (2 à 10)').setRequired(true),
),
);
/** Lightweight, stateless fun commands (M10-T07). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/fun')] }); const subcommand = interaction.options.getSubcommand();
if (subcommand === 'coinflip') {
const result = pick(['Pile', 'Face']);
await interaction.reply({
embeds: [baseEmbed(COLORS.info).setTitle('Pile ou face').setDescription(`🪙 ${result} !`)],
});
return;
}
if (subcommand === 'dice') {
const sides = interaction.options.getInteger('sides') ?? 6;
const roll = 1 + Math.floor(Math.random() * sides);
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle(`Lancer de dé (d${sides})`)
.setDescription(`🎲 Tu obtiens **${roll}** !`),
],
});
return;
}
if (subcommand === '8ball') {
const question = interaction.options.getString('question', true);
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle('🎱 Boule magique')
.addFields(
{ name: 'Question', value: question },
{ name: 'Réponse', value: pick(EIGHT_BALL_ANSWERS) },
),
],
});
return;
}
const options = parseChoices(interaction.options.getString('options', true));
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle('Choix aléatoire')
.addFields({ name: 'Options', value: options.map((option) => `• ${option}`).join('\n') })
.setDescription(`Je choisis : **${pick(options)}**`),
],
});
} }
+19 -4
View File
@@ -1,6 +1,7 @@
import { SlashCommandBuilder } from 'discord.js'; import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import { buildPollEmbed, closePollById, createPoll } from '../../services/polls/poll-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
@@ -28,7 +29,21 @@ export const data = new SlashCommandBuilder()
.addIntegerOption((option) => option.setName('id').setDescription('ID du sondage').setRequired(true)), .addIntegerOption((option) => option.setName('id').setDescription('ID du sondage').setRequired(true)),
); );
// TODO(M10-T01..T06): implement with polls / poll_votes tables. /** Polls are published in the current channel and voted with buttons (M10). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed(`/poll ${interaction.options.getSubcommand()}`)] }); if (interaction.options.getSubcommand() === 'close') {
const poll = await closePollById(interaction.client, interaction.options.getInteger('id', true));
await interaction.reply({ embeds: [buildPollEmbed(poll)] });
return;
}
const question = interaction.options.getString('question', true);
const choicesInput = interaction.options.getString('choices', true);
const minutes = interaction.options.getInteger('minutes');
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const pollId = await createPoll(interaction, { question, choicesInput, minutes });
await interaction.editReply({
embeds: [successEmbed(`Sondage **#${pollId}** publié dans <#${interaction.channelId}>.`)],
});
} }
+102 -5
View File
@@ -1,6 +1,13 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import { createLogger } from '../../core/logger.js';
import { countByAction } from '../../database/repositories/moderation-repository.js';
import { countPolls } from '../../database/repositories/poll-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { baseEmbed, errorEmbed } from '../../ui/embeds.js';
const log = createLogger('stats');
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
@@ -11,7 +18,97 @@ export const data = new SlashCommandBuilder()
.addSubcommand((sub) => sub.setName('gitea').setDescription('Activité et indicateurs Gitea')) .addSubcommand((sub) => sub.setName('gitea').setDescription('Activité et indicateurs Gitea'))
.addSubcommand((sub) => sub.setName('fws').setDescription('Indicateurs FWS / FWS Arch')); .addSubcommand((sub) => sub.setName('fws').setDescription('Indicateurs FWS / FWS Arch'));
// TODO(M11-T02..T04): implement per data source. const discordStatsEmbed = (interaction) => {
export async function execute(interaction) { const guild = interaction.guild;
await interaction.reply({ embeds: [notImplementedEmbed(`/stats ${interaction.options.getSubcommand()}`)] }); return baseEmbed()
.setTitle(`Statistiques — ${guild.name}`)
.setThumbnail(guild.iconURL({ size: 128 }))
.addFields(
{ name: 'Membres', value: String(guild.memberCount), inline: true },
{ name: 'Salons', value: String(guild.channels.cache.size), inline: true },
{ name: 'Rôles', value: String(guild.roles.cache.size), inline: true },
{ name: 'Boosts', value: String(guild.premiumSubscriptionCount ?? 0), inline: true },
{ name: 'Créé', value: `<t:${Math.floor(guild.createdTimestamp / 1000)}:R>`, inline: true },
{ name: 'Latence', value: `${Math.round(interaction.client.ws.ping)} ms`, inline: true },
);
};
async function giteaStatsEmbed() {
const [issues, pulls, commits, releases] = await Promise.all([
gitea.listIssues('state=open&type=issues&limit=50'),
gitea.listPullRequests('state=open&limit=50'),
gitea.listCommits(5),
gitea.listReleases(1),
]);
const latestCommits = asList(commits)
.slice(0, 5)
.map((commit) => `\`${commit.sha?.slice(0, 7)}\` ${commit.commit?.message?.split('\n')[0] ?? ''}`)
.join('\n');
const release = asList(releases)[0];
const embed = baseEmbed(COLORS.gitea)
.setTitle('Activité Gitea')
.setURL(repositoryUrl())
.setDescription(latestCommits || 'Aucun commit récent.')
.addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
);
if (release)
embed.addFields({ name: 'Dernière release', value: release.tag_name ?? 'inconnue', inline: true });
return embed;
}
/** Community activity stored locally, independent from Gitea availability (M11). */
function fwsStatsEmbed(interaction) {
const actions = countByAction(interaction.guildId);
const total = actions.reduce((sum, row) => sum + row.count, 0);
return baseEmbed(COLORS.gitea)
.setTitle('Indicateurs FWS')
.addFields(
{ name: 'Tickets ouverts', value: String(countOpenTickets(interaction.guildId)), inline: true },
{ name: 'Sondages créés', value: String(countPolls(interaction.guildId)), inline: true },
{ name: 'Actions de modération', value: String(total), inline: true },
{ name: 'Dépôt', value: repositoryUrl() || 'Non configuré' },
)
.setFooter({ text: 'Statistiques locales · FWS-Bot' });
}
/** `/stats` never fails because of Gitea: the API errors are caught (M11-T03). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
await interaction.deferReply();
if (subcommand === 'discord') {
await interaction.editReply({ embeds: [discordStatsEmbed(interaction)] });
return;
}
if (subcommand === 'fws') {
try {
const releases = asList(await gitea.listReleases(1));
const embed = fwsStatsEmbed(interaction);
if (releases[0])
embed.addFields({ name: 'Version FWS Arch', value: releases[0].tag_name ?? 'inconnue' });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
log.warn('Gitea unavailable while building /stats fws', error);
await interaction.editReply({ embeds: [fwsStatsEmbed(interaction)] });
}
return;
}
try {
await interaction.editReply({ embeds: [await giteaStatsEmbed()] });
} catch (error) {
log.error('Could not read Gitea stats', error);
await interaction.editReply({
embeds: [
errorEmbed('Les statistiques Gitea sont indisponibles. Vérifie `GITEA_URL` et `GITEA_TOKEN`.'),
],
});
}
} }
+189 -28
View File
@@ -1,8 +1,16 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { getSetting } from '../../database/repositories/settings-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { asList, gitea, isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { releaseEmbed } from '../../services/gitea/gitea-embeds.js';
import { replyGiteaFailure } from '../../services/gitea/gitea-modals.js';
import { linkButtons } from '../../ui/buttons.js'; import { linkButtons } from '../../ui/buttons.js';
import { baseEmbed, notImplementedEmbed } from '../../ui/embeds.js'; import { baseEmbed, errorEmbed, infoEmbed } from '../../ui/embeds.js';
const log = createLogger('fws');
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
@@ -28,30 +36,183 @@ const officialLinks = () => [
{ label: 'Discord', url: env.links.discordInvite }, { label: 'Discord', url: env.links.discordInvite },
]; ];
const handlers = { /** Guild settings are stored as JSON in SQLite; a failure falls back to the default (M4-T07). */
// TODO(M4-T01): content should come from guild_settings (M4-T07). function readSetting(guildId, key, fallback = null) {
info: (interaction) => try {
interaction.reply({ return getSetting(guildId, key, fallback);
embeds: [ } catch (error) {
baseEmbed() log.debug(`Could not read setting ${key}`, error);
.setTitle('FWS & FWS Arch') return fallback;
.setDescription( }
'FWS est une organisation open source multi-projets.\n' + }
"**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale.",
), const DEFAULT_PRESENTATION =
], 'FWS est une organisation open source multi-projets.\n' +
components: linkButtons(officialLinks()), "**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale.";
}),
links: (interaction) => async function latestRelease() {
interaction.reply({ try {
embeds: [baseEmbed().setTitle('Liens officiels FWS')], return await gitea.getLatestRelease();
components: linkButtons(officialLinks()), } catch {
}), return asList(await gitea.listReleases(1))[0] ?? null;
version: (interaction) => interaction.reply({ embeds: [notImplementedEmbed('/fws version')] }), }
status: (interaction) => interaction.reply({ embeds: [notImplementedEmbed('/fws status')] }), }
changelog: (interaction) => interaction.reply({ embeds: [notImplementedEmbed('/fws changelog')] }),
}; async function showInfo(interaction) {
const configured = readSetting(interaction.guildId, 'fws.info', DEFAULT_PRESENTATION);
export async function execute(interaction) { const description = typeof configured === 'string' && configured ? configured : DEFAULT_PRESENTATION;
await handlers[interaction.options.getSubcommand()](interaction); await interaction.reply({
embeds: [baseEmbed().setTitle('FWS & FWS Arch').setDescription(description)],
components: linkButtons(officialLinks()),
});
}
async function showVersion(interaction) {
const fallback = readSetting(interaction.guildId, 'fws.version', null);
if (!isGiteaConfigured()) {
await interaction.reply({
embeds: [
fallback
? infoEmbed('Version FWS Arch', `Version publiée : **${fallback}**`)
: errorEmbed('Gitea n’est pas configuré : impossible de lire la dernière version.'),
],
});
return;
}
await interaction.deferReply();
try {
const release = await latestRelease();
if (!release) {
await interaction.editReply({
embeds: [
fallback
? infoEmbed('Version FWS Arch', `Version publiée : **${fallback}**`)
: infoEmbed('Version FWS Arch', 'Aucune release publiée pour le moment.'),
],
});
return;
}
await interaction.editReply({
embeds: [releaseEmbed(release, { withNotes: false })],
components: release.html_url ? linkButtons([{ label: 'Notes de version', url: release.html_url }]) : [],
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
async function showStatus(interaction) {
await interaction.deferReply();
const giteaConfigured = isGiteaConfigured();
const giteaReachable = giteaConfigured
? await gitea
.listReleases(1)
.then(() => true)
.catch(() => false)
: false;
let openTickets = null;
try {
openTickets = countOpenTickets(interaction.guildId);
} catch (error) {
log.warn('Database unavailable while building /fws status', error);
}
const uptime = Math.floor(process.uptime());
const embed = baseEmbed(COLORS.info)
.setTitle('État des services')
.addFields(
{
name: 'API Gitea',
value: !giteaConfigured
? '⚙️ Non configurée'
: giteaReachable
? `✅ En ligne — ${repositoryUrl()}`
: '❌ Injoignable',
inline: false,
},
{
name: 'Webhooks Gitea',
value: env.webhook.enabled ? '✅ Actifs' : '⚙️ Désactivés (`WEBHOOK_ENABLED=false`)',
inline: false,
},
{
name: 'Base SQLite',
value:
openTickets === null ? '❌ Indisponible' : `✅ Accessible — ${openTickets} ticket(s) ouvert(s)`,
inline: false,
},
{
name: 'Discord',
value: `✅ Connecté — ${Math.round(interaction.client.ws.ping)} ms`,
inline: false,
},
{ name: 'Disponibilité du bot', value: `<t:${Math.floor((Date.now() - uptime * 1000) / 1000)}:R>` },
);
await interaction.editReply({ embeds: [embed] });
}
async function showChangelog(interaction) {
const version = interaction.options.getString('version');
if (!isGiteaConfigured()) {
await interaction.reply({
embeds: [errorEmbed('Gitea n’est pas configuré : le changelog est indisponible.')],
});
return;
}
await interaction.deferReply();
try {
const release = version ? await gitea.getReleaseByTag(version) : await latestRelease();
if (!release) {
await interaction.editReply({
embeds: [infoEmbed('Changelog', `Aucune release trouvée pour **${version}**.`)],
});
return;
}
await interaction.editReply({
embeds: [releaseEmbed(release)],
components: release.html_url ? linkButtons([{ label: 'Ouvrir sur Gitea', url: release.html_url }]) : [],
});
} catch (error) {
if (version) {
log.warn(`Release ${version} not found`, error);
await interaction.editReply({
embeds: [infoEmbed('Changelog', `La version **${version}** n’existe pas dans les releases Gitea.`)],
});
return;
}
await replyGiteaFailure(interaction, error);
}
}
/** Static presentation plus live data from Gitea (M4). */
export async function execute(interaction) {
switch (interaction.options.getSubcommand()) {
case 'info':
await showInfo(interaction);
return;
case 'links':
await interaction.reply({
embeds: [baseEmbed().setTitle('Liens officiels FWS')],
components: linkButtons(officialLinks()),
});
return;
case 'version':
await showVersion(interaction);
return;
case 'status':
await showStatus(interaction);
return;
case 'changelog':
await showChangelog(interaction);
return;
default:
return;
}
} }
+61 -4
View File
@@ -1,6 +1,8 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { replyGiteaFailure, assertGiteaConfigured } from '../../services/gitea/gitea-modals.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
@@ -10,7 +12,62 @@ export const data = new SlashCommandBuilder()
.addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents')) .addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents'))
.addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles')); .addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles'));
// TODO(M5-T06 / M5-T07): implement with services/gitea/gitea-client.js. const commitLines = (commits) =>
asList(commits)
.slice(0, 5)
.map((commit) => {
const message = commit.commit?.message?.split('\n')[0] ?? '(sans message)';
return `\`${commit.sha?.slice(0, 7)}\` ${message} — *${commit.commit?.author?.name ?? 'inconnu'}*`;
})
.join('\n');
/** Read-only summaries of the repository (M5-T06 / M5-T07). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed(`/gitea ${interaction.options.getSubcommand()}`)] }); assertGiteaConfigured();
await interaction.deferReply();
try {
if (interaction.options.getSubcommand() === 'release') {
const releases = asList(await gitea.listReleases(5));
if (releases.length === 0) {
await interaction.editReply({ embeds: [successEmbed('Aucune release publiée pour le moment.')] });
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('Releases FWS Arch')
.setURL(repositoryUrl())
.setDescription(
releases
.map((release) => {
const date = release.published_at
? `<t:${Math.floor(new Date(release.published_at).getTime() / 1000)}:D>`
: 'date inconnue';
const tag = release.html_url ? `[${release.tag_name}](${release.html_url})` : release.tag_name;
return `${release.prerelease ? '🧪' : '📦'} **${tag}** — ${release.name || 'sans titre'} · ${date}`;
})
.join('\n'),
);
await interaction.editReply({ embeds: [embed] });
return;
}
const [issues, pulls, commits] = await Promise.all([
gitea.listIssues('state=open&type=issues&limit=50'),
gitea.listPullRequests('state=open&limit=50'),
gitea.listCommits(5),
]);
const embed = baseEmbed(COLORS.gitea)
.setTitle('Activité récente')
.setURL(repositoryUrl())
.setDescription(commitLines(commits) || 'Aucun commit récent.')
.addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
);
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
} }
+48 -4
View File
@@ -1,6 +1,14 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import { UserFacingError } from '../../core/errors.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { issueEmbed } from '../../services/gitea/gitea-embeds.js';
import {
assertGiteaConfigured,
openIssueModal,
replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
@@ -21,7 +29,43 @@ export const data = new SlashCommandBuilder()
) )
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les issues ouvertes')); .addSubcommand((sub) => sub.setName('list').setDescription('Lister les issues ouvertes'));
// TODO(M5-T02 / M5-T03): implement with services/gitea/gitea-client.js. /** Issues can be browsed and created straight from Discord (M5-T02 / M5-T03). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed(`/issue ${interaction.options.getSubcommand()}`)] }); const subcommand = interaction.options.getSubcommand();
if (subcommand === 'create') {
await openIssueModal(interaction);
return;
}
assertGiteaConfigured();
await interaction.deferReply();
try {
if (subcommand === 'view') {
const issue = await gitea.getIssue(interaction.options.getInteger('number', true));
if (!issue?.number) throw new UserFacingError('Cette issue est introuvable sur Gitea.');
await interaction.editReply({ embeds: [issueEmbed(issue)] });
return;
}
const issues = asList(await gitea.listIssues('state=open&type=issues&limit=15'));
if (issues.length === 0) {
await interaction.editReply({ embeds: [successEmbed('Aucune issue ouverte. 🎉')] });
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('Issues ouvertes')
.setURL(`${repositoryUrl()}/issues`)
.setDescription(
issues
.map((issue) => `**#${issue.number}** ${issue.title} — *${issue.user?.login ?? 'inconnu'}*`)
.join('\n'),
)
.setFooter({ text: `${issues.length} issue(s) affichée(s)` });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
} }
+52 -4
View File
@@ -1,6 +1,14 @@
import { SlashCommandBuilder } from 'discord.js'; import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import { UserFacingError } from '../../core/errors.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { pullRequestEmbed } from '../../services/gitea/gitea-embeds.js';
import {
assertGiteaConfigured,
openPullRequestModal,
replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; export const subcommandAccess = { create: ACCESS_LEVELS.DEV };
@@ -25,7 +33,47 @@ export const data = new SlashCommandBuilder()
) )
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les pull requests ouvertes')); .addSubcommand((sub) => sub.setName('list').setDescription('Lister les pull requests ouvertes'));
// TODO(M5-T04 / M5-T05): implement with services/gitea/gitea-client.js. /** The title and description are collected through a modal (M5-T04 / M5-T05). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed(`/pr ${interaction.options.getSubcommand()}`)] }); const subcommand = interaction.options.getSubcommand();
if (subcommand === 'create') {
await openPullRequestModal(interaction);
return;
}
assertGiteaConfigured();
await interaction.deferReply();
try {
if (subcommand === 'view') {
const pull = await gitea.getPullRequest(interaction.options.getInteger('number', true));
if (!pull?.number) throw new UserFacingError('Cette pull request est introuvable sur Gitea.');
await interaction.editReply({ embeds: [pullRequestEmbed(pull)] });
return;
}
const pulls = asList(await gitea.listPullRequests('state=open&limit=15'));
if (pulls.length === 0) {
await interaction.editReply({ embeds: [successEmbed('Aucune pull request ouverte.')] });
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('Pull requests ouvertes')
.setURL(`${repositoryUrl()}/pulls`)
.setDescription(
pulls
.map(
(pull) =>
`**#${pull.number}** ${pull.title} — ${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'} ` +
`(*${pull.user?.login ?? 'inconnu'}*)`,
)
.join('\n'),
)
.setFooter({ text: `${pulls.length} PR affichée(s)` });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
} }
+32 -4
View File
@@ -1,6 +1,11 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import {
assertModerationTarget,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
@@ -18,7 +23,30 @@ export const data = new SlashCommandBuilder()
.setMaxValue(7), .setMaxValue(7),
); );
// TODO(M8-T04): ban after canActOn() check and log the sensitive action (M8-T09). /** Bans the user, whether or not they are still on the server (M8-T04 / M8-T09). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/ban')] }); const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
const deleteDays = interaction.options.getInteger('delete_days') ?? 0;
const member = await interaction.guild.members.fetch(user.id).catch(() => null);
if (member) {
assertModerationTarget(interaction, member);
await member
.send({
embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })],
})
.catch(() => {});
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await interaction.guild.bans.create(user.id, {
reason: reason ?? `Banni par ${interaction.user.tag}`,
deleteMessageSeconds: deleteDays * 86_400,
});
await logModerationAction(interaction, { action: 'ban', targetId: user.id, reason });
await interaction.editReply({
embeds: [successEmbed(`**${user.tag}** a été banni du serveur.`)],
});
} }
+26 -4
View File
@@ -1,6 +1,8 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import { UserFacingError } from '../../core/errors.js';
import { logModerationAction } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
@@ -17,7 +19,27 @@ export const data = new SlashCommandBuilder()
.setMaxValue(100), .setMaxValue(100),
); );
// TODO(M8-T05): channel.bulkDelete(amount, true) and log the action. /** Bulk deletes messages in the current channel and logs it (M8-T05). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/clear')] }); const amount = interaction.options.getInteger('amount', true);
if (!interaction.channel?.isTextBased() || !interaction.channel.bulkDelete) {
throw new UserFacingError('La suppression groupée n’est pas possible dans ce salon.');
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const deleted = await interaction.channel.bulkDelete(amount, true);
await logModerationAction(interaction, {
action: 'clear',
targetId: null,
reason: `${deleted.size} message(s) supprimé(s) dans #${interaction.channel.name}`,
});
await interaction.editReply({
embeds: [
successEmbed(
`${deleted.size} message(s) supprimé(s) dans <#${interaction.channelId}>.` +
(deleted.size < amount ? '\n_Les messages de plus de 14 jours sont conservés par Discord._' : ''),
),
],
});
} }
+27 -4
View File
@@ -1,6 +1,12 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import {
assertModerationTarget,
fetchTargetMember,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
@@ -11,7 +17,24 @@ export const data = new SlashCommandBuilder()
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)) .addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500)); .addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500));
// TODO(M8-T03): kick after canActOn() check and log the action. /** Expels the member after the hierarchy checks (M8-T03 / M8-T06). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/kick')] }); const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await target
.send({
embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })],
})
.catch(() => {});
await target.kick(reason ?? `Expulsé par ${interaction.user.tag}`);
await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason });
await interaction.editReply({
embeds: [successEmbed(`**${target.user.tag}** a été expulsé du serveur.`)],
});
} }
+38 -6
View File
@@ -1,9 +1,13 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS, COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import { listActions } from '../../database/repositories/moderation-repository.js';
import { formatDuration } from '../../services/moderation/moderation-service.js';
import { baseEmbed, infoEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
const HISTORY_LIMIT = 15;
export const data = new SlashCommandBuilder() export const data = new SlashCommandBuilder()
.setName('mod') .setName('mod')
.setDescription('Outils de modération') .setDescription('Outils de modération')
@@ -15,7 +19,35 @@ export const data = new SlashCommandBuilder()
.addUserOption((option) => option.setName('user').setDescription('Filtrer par membre')), .addUserOption((option) => option.setName('user').setDescription('Filtrer par membre')),
); );
// TODO(M8-T06): read from moderation_actions. function formatEntry(row) {
export async function execute(interaction) { const meta = MODERATION_ACTIONS[row.action];
await interaction.reply({ embeds: [notImplementedEmbed('/mod logs')] }); 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` +
`↳ par <@${row.moderator_id}> · ${row.reason || 'sans raison'}`
);
}
/** Reads the moderation history from SQLite (M8-T06). */
export async function execute(interaction) {
const user = interaction.options.getUser('user');
const actions = listActions({
guildId: interaction.guildId,
targetId: user?.id ?? null,
limit: HISTORY_LIMIT,
});
const embed =
actions.length === 0
? infoEmbed(
'Historique de modération',
user ? `Aucune action enregistrée contre ${user}.` : 'Aucune action enregistrée sur ce serveur.',
)
: baseEmbed(COLORS.moderation)
.setTitle(user ? `Historique de ${user.tag}` : 'Dernières actions de modération')
.setDescription(actions.map(formatEntry).join('\n\n'))
.setFooter({ text: `${actions.length} dernière(s) action(s)` });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
} }
+38 -4
View File
@@ -1,6 +1,13 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import {
assertModerationTarget,
fetchTargetMember,
formatDuration,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
@@ -19,7 +26,34 @@ export const data = new SlashCommandBuilder()
) )
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500)); .addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500));
// TODO(M8-T02 / M8-T07): use member.timeout() after canActOn() check. /** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/mute')] }); const user = interaction.options.getUser('user', true);
const minutes = interaction.options.getInteger('minutes', true);
const reason = interaction.options.getString('reason');
const durationMs = minutes * 60_000;
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await target.timeout(durationMs, reason ?? `Exclusion temporaire de ${minutes} minutes`);
await logModerationAction(interaction, {
action: 'mute',
targetId: target.id,
reason,
durationMs,
});
await target
.send({
embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })],
})
.catch(() => {});
await interaction.editReply({
embeds: [
successEmbed(`**${target.user.tag}** est réduit au silence pendant **${formatDuration(durationMs)}**.`),
],
});
} }
+97
View File
@@ -0,0 +1,97 @@
import { ChannelType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, NOTIFICATION_TYPES } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
listNotificationChannels,
removeNotificationChannel,
setNotificationChannel,
} from '../../database/repositories/notification-repository.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const TYPE_CHOICES = NOTIFICATION_TYPES.map((type) => ({ name: type, value: type }));
export const data = new SlashCommandBuilder()
.setName('notify')
.setDescription('Configuration des salons de notification')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addSubcommand((sub) =>
sub
.setName('set')
.setDescription('Associer un salon à un type de notification')
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type de notification')
.setRequired(true)
.addChoices(...TYPE_CHOICES),
)
.addChannelOption((option) =>
option
.setName('channel')
.setDescription('Salon de destination')
.setRequired(true)
.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement),
),
)
.addSubcommand((sub) =>
sub
.setName('remove')
.setDescription('Revenir au salon par défaut de la configuration')
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type de notification')
.setRequired(true)
.addChoices(...TYPE_CHOICES),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Afficher la configuration actuelle'));
/** Per-guild notification routing stored in SQLite (M9-T01). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'set') {
const type = interaction.options.getString('type', true);
const channel = interaction.options.getChannel('channel', true);
setNotificationChannel({ guildId: interaction.guildId, type, channelId: channel.id });
await interaction.reply({
embeds: [successEmbed(`Les notifications **${type}** seront envoyées dans <#${channel.id}>.`)],
flags: MessageFlags.Ephemeral,
});
return;
}
if (subcommand === 'remove') {
const type = interaction.options.getString('type', true);
const removed = removeNotificationChannel(interaction.guildId, type);
if (!removed) throw new UserFacingError(`Aucun salon personnalisé n’est configuré pour **${type}**.`);
await interaction.reply({
embeds: [successEmbed(`Les notifications **${type}** repassent à la configuration par défaut.`)],
flags: MessageFlags.Ephemeral,
});
return;
}
const overrides = new Map(
listNotificationChannels(interaction.guildId).map((row) => [row.type, row.channel_id]),
);
const lines = NOTIFICATION_TYPES.map((type) => {
const channelId = overrides.get(type);
return channelId
? `\`${type}\` → <#${channelId}> _(personnalisé)_`
: `\`${type}\` → _configuration par défaut_`;
});
await interaction.reply({
embeds: [
baseEmbed()
.setTitle('Salons de notification')
.setDescription(lines.join('\n'))
.setFooter({ text: `Serveur ${interaction.guildId}` }),
],
flags: MessageFlags.Ephemeral,
});
}
+50 -4
View File
@@ -1,6 +1,8 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import { UserFacingError } from '../../core/errors.js';
import { fetchTargetMember, logModerationAction } from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
@@ -23,7 +25,51 @@ export const data = new SlashCommandBuilder()
), ),
); );
// TODO(M7-T05 / M7-T06): enforce role hierarchy (M3-T05) and log the change. /** Adds or removes a role after checking both hierarchies (M7-T05 / M3-T05). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/role set')] }); const user = interaction.options.getUser('user', true);
const role = interaction.options.getRole('role', true);
const action = interaction.options.getString('action', true);
const adding = action === 'add';
if (role.id === interaction.guild.roles.everyone.id) {
throw new UserFacingError('Le rôle @everyone ne peut pas être attribué.');
}
if (role.managed) {
throw new UserFacingError('Ce rôle est géré par une intégration et ne peut pas être modifié.');
}
const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(role) <= 0) {
throw new UserFacingError('Mon rôle est trop bas pour gérer ce rôle.');
}
const target = await fetchTargetMember(interaction, user.id);
const hasRole = target.roles.cache.has(role.id);
if (adding && hasRole) throw new UserFacingError(`**${target.user.tag}** possède déjà le rôle ${role}.`);
if (!adding && !hasRole)
throw new UserFacingError(`**${target.user.tag}** ne possède pas le rôle ${role}.`);
const isGuildOwner = interaction.guild.ownerId === interaction.user.id;
if (!isGuildOwner && interaction.member.roles.highest.comparePositionTo(role) <= 0) {
throw new UserFacingError('Tu ne peux pas gérer un rôle au-dessus ou égal au tien.');
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
if (adding) {
await target.roles.add(role, `Ajouté par ${interaction.user.tag}`);
} else {
await target.roles.remove(role, `Retiré par ${interaction.user.tag}`);
}
await logModerationAction(interaction, {
action: 'role',
targetId: target.id,
reason: `${adding ? 'Ajout' : 'Retrait'} du rôle ${role.name} (${role.id})`,
});
await interaction.editReply({
embeds: [
successEmbed(`Le rôle ${role} a été ${adding ? 'ajouté à' : 'retiré de'} **${target.user.tag}**.`),
],
});
} }
+34 -4
View File
@@ -1,6 +1,13 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js'; import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import { countActions } from '../../database/repositories/moderation-repository.js';
import {
assertModerationTarget,
fetchTargetMember,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF; export const access = ACCESS_LEVELS.STAFF;
@@ -13,7 +20,30 @@ export const data = new SlashCommandBuilder()
option.setName('reason').setDescription('Raison').setRequired(true).setMaxLength(500), option.setName('reason').setDescription('Raison').setRequired(true).setMaxLength(500),
); );
// TODO(M8-T01): record in moderation_actions and log (M8-T06). /** Records the warning, notifies the member and logs it (M8-T01 / M8-T06). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/warn')] }); const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason', true);
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await logModerationAction(interaction, { action: 'warn', targetId: target.id, reason });
const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' });
await target
.send({
embeds: [
targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({
name: 'Avertissements',
value: String(total),
}),
],
})
.catch(() => {});
await interaction.editReply({
embeds: [successEmbed(`**${target.user.tag}** a été averti (${total} avertissement(s) au total).`)],
});
} }
+31 -6
View File
@@ -1,6 +1,12 @@
import { SlashCommandBuilder } from 'discord.js'; import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js'; import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js'; import {
addParticipant,
claimTicket,
closeTicket,
createTicket,
} from '../../services/tickets/ticket-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER; export const access = ACCESS_LEVELS.USER;
// `close` is also allowed for the ticket author: checked in the ticket service. // `close` is also allowed for the ticket author: checked in the ticket service.
@@ -35,9 +41,28 @@ export const data = new SlashCommandBuilder()
.addUserOption((option) => option.setName('user').setDescription('Membre à ajouter').setRequired(true)), .addUserOption((option) => option.setName('user').setDescription('Membre à ajouter').setRequired(true)),
); );
// TODO(M6-T03..T09): implement with a ticket service backed by the tickets table. /** Ticket lifecycle: each subcommand acts on a private channel (M6-T03..T09). */
export async function execute(interaction) { export async function execute(interaction) {
await interaction.reply({ switch (interaction.options.getSubcommand()) {
embeds: [notImplementedEmbed(`/ticket ${interaction.options.getSubcommand()}`)], case 'create': {
}); const categoryId = interaction.options.getString('category', true);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const channel = await createTicket(interaction, categoryId);
await interaction.editReply({
embeds: [successEmbed(`Ton ticket est ouvert : <#${channel.id}>`)],
});
return;
}
case 'close':
await closeTicket(interaction, interaction.options.getString('reason'));
return;
case 'claim':
await claimTicket(interaction);
return;
case 'add':
await addParticipant(interaction, interaction.options.getUser('user', true).id);
return;
default:
return;
}
} }
+248
View File
@@ -0,0 +1,248 @@
import { ChannelType, MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
activeChannelCount,
claimOwnership,
getVoiceSettings,
kickUser,
NAME_MAX,
permitUser,
postSetupPanel,
rejectUser,
removeChannel,
renameChannel,
saveVoiceSettings,
setChannelLimit,
showInfo,
toggleLock,
transferOwnership,
} from '../../services/voice/voice-service.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = { setup: ACCESS_LEVELS.STAFF, panel: ACCESS_LEVELS.STAFF };
const voiceChannelOption = (option) => option.addChannelTypes(ChannelType.GuildVoice);
export const data = new SlashCommandBuilder()
.setName('voice')
.setDescription('Gestion des salons vocaux temporaires')
.addSubcommand((sub) =>
sub
.setName('setup')
.setDescription('Configurer le salon déclencheur et les salons créés')
.addChannelOption((option) =>
voiceChannelOption(
option
.setName('trigger')
.setDescription('Salon vocal à rejoindre pour créer un salon')
.setRequired(true),
),
)
.addChannelOption((option) =>
option
.setName('category')
.setDescription('Catégorie d’accueil des salons créés')
.addChannelTypes(ChannelType.GuildCategory),
)
.addStringOption((option) =>
option
.setName('template')
.setDescription('Modèle du nom, avec {user} (ex. « 🔊 Salon de {user} »)')
.setMaxLength(NAME_MAX),
)
.addIntegerOption((option) =>
option
.setName('limit')
.setDescription('Places par défaut (0 = illimité)')
.setMinValue(0)
.setMaxValue(99),
)
.addBooleanOption((option) =>
option.setName('panel').setDescription('Publier le panneau d’explication dans le salon déclencheur'),
),
)
.addSubcommand((sub) => sub.setName('config').setDescription('Afficher la configuration actuelle'))
.addSubcommand((sub) =>
sub.setName('panel').setDescription('Republier le panneau d’explication dans le salon déclencheur'),
)
.addSubcommand((sub) =>
sub
.setName('name')
.setDescription('Renommer ton salon')
.addStringOption((option) =>
option.setName('name').setDescription('Nouveau nom').setRequired(true).setMaxLength(NAME_MAX),
),
)
.addSubcommand((sub) =>
sub
.setName('limit')
.setDescription('Limiter le nombre de places (0 = illimité)')
.addIntegerOption((option) =>
option
.setName('limit')
.setDescription('Nombre de places')
.setRequired(true)
.setMinValue(0)
.setMaxValue(99),
),
)
.addSubcommand((sub) => sub.setName('lock').setDescription('Verrouiller ton salon'))
.addSubcommand((sub) => sub.setName('unlock').setDescription('Déverrouiller ton salon'))
.addSubcommand((sub) =>
sub
.setName('permit')
.setDescription('Autoriser un membre à rejoindre ton salon')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('reject')
.setDescription('Interdire l’accès à un membre')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('kick')
.setDescription('Exclure un membre du salon')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('transfer')
.setDescription('Transférer la propriété du salon')
.addUserOption((option) =>
option.setName('user').setDescription('Nouveau propriétaire').setRequired(true),
),
)
.addSubcommand((sub) => sub.setName('claim').setDescription('Récupérer un salon abandonné'))
.addSubcommand((sub) =>
sub
.setName('delete')
.setDescription('Supprimer un salon temporaire')
.addChannelOption((option) =>
voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')),
),
)
.addSubcommand((sub) =>
sub
.setName('info')
.setDescription('Détails du salon temporaire')
.addChannelOption((option) =>
voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')),
),
);
function configEmbed(guildId) {
const settings = getVoiceSettings(guildId);
return baseEmbed(COLORS.primary)
.setTitle('Salons vocaux temporaires')
.addFields(
{
name: 'Salon déclencheur',
value: settings.triggerId ? `<#${settings.triggerId}>` : '❌ Non configuré',
inline: true,
},
{
name: 'Catégorie',
value: settings.categoryId ? `<#${settings.categoryId}>` : 'Aucune',
inline: true,
},
{ name: 'Modèle du nom', value: `\`${settings.template}\``, inline: true },
{
name: 'Limite par défaut',
value: settings.defaultLimit ? `${settings.defaultLimit} places` : 'Illimitée',
inline: true,
},
{ name: 'Salons actifs', value: String(activeChannelCount(guildId)), inline: true },
);
}
async function runSetup(interaction) {
const trigger = interaction.options.getChannel('trigger', true);
if (trigger.type !== ChannelType.GuildVoice) {
throw new UserFacingError('Le salon déclencheur doit être un salon **vocal**.');
}
const category = interaction.options.getChannel('category');
const template = interaction.options.getString('template');
const limit = interaction.options.getInteger('limit');
if (category && category.type !== ChannelType.GuildCategory) {
throw new UserFacingError('La catégorie d’accueil doit être une **catégorie**.');
}
if (trigger.id === category?.id) {
throw new UserFacingError('Le salon déclencheur ne peut pas être sa propre catégorie d’accueil.');
}
saveVoiceSettings(
interaction.guildId,
{
trigger: trigger.id,
...(category && { category: category.id }),
...(template && { template }),
...(limit !== null && { limit }),
},
interaction.user.id,
);
await interaction.reply({
embeds: [successEmbed(`Salon déclencheur : <#${trigger.id}>`)],
flags: MessageFlags.Ephemeral,
});
const wantsPanel = interaction.options.getBoolean('panel') ?? true;
if (wantsPanel) await postSetupPanel(interaction).catch(() => {});
}
/** Every subcommand acts on the caller's temporary channel, checked by the service (M14-T06). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
const channel = interaction.options.getChannel('channel');
switch (subcommand) {
case 'setup':
await runSetup(interaction);
return;
case 'panel':
await postSetupPanel(interaction);
return;
case 'config':
await interaction.reply({ embeds: [configEmbed(interaction.guildId)], flags: MessageFlags.Ephemeral });
return;
case 'name':
await renameChannel(interaction, interaction.options.getString('name', true));
return;
case 'limit':
await setChannelLimit(interaction, interaction.options.getInteger('limit', true));
return;
case 'lock':
case 'unlock':
await toggleLock(interaction, { locked: subcommand === 'lock' });
return;
case 'permit':
await permitUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'reject':
await rejectUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'kick':
await kickUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'transfer':
await transferOwnership(interaction, interaction.options.getUser('user', true).id);
return;
case 'claim':
await claimOwnership(interaction);
return;
case 'delete':
await removeChannel(interaction, { channelId: channel?.id ?? null });
return;
case 'info':
await showInfo(interaction, { channelId: channel?.id ?? null });
return;
default:
return;
}
}
+20
View File
@@ -20,6 +20,16 @@ export const ACCESS_LEVELS = Object.freeze({
OWNER: 3, OWNER: 3,
}); });
/** Moderation actions: Discord label, embed color and stored duration (M8). */
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 },
});
/** Ticket categories and who can see them (M0-T05 / M6-T01). */ /** Ticket categories and who can see them (M0-T05 / M6-T01). */
export const TICKET_CATEGORIES = Object.freeze([ export const TICKET_CATEGORIES = Object.freeze([
{ id: 'support', label: 'Support utilisateur', scope: ['staff', 'owner'] }, { id: 'support', label: 'Support utilisateur', scope: ['staff', 'owner'] },
@@ -29,6 +39,16 @@ export const TICKET_CATEGORIES = Object.freeze([
{ id: 'internal', label: 'Demande interne', scope: ['owner'] }, { id: 'internal', label: 'Demande interne', scope: ['owner'] },
]); ]);
/** Gitea webhook event -> notification type (M9-T03). */
export const GITEA_EVENT_TYPES = Object.freeze({
issues: 'issues',
pull_request: 'pull_request',
push: 'push',
create: 'push',
delete: 'push',
release: 'release',
});
export const NOTIFICATION_TYPES = Object.freeze([ export const NOTIFICATION_TYPES = Object.freeze([
'issues', 'issues',
'pull_requests', 'pull_requests',
+2
View File
@@ -43,6 +43,8 @@ export const env = Object.freeze({
notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'), notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'),
notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'), notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'),
ticketCategory: read('CATEGORY_TICKETS_ID'), ticketCategory: read('CATEGORY_TICKETS_ID'),
voiceTrigger: read('CHANNEL_VOICE_TRIGGER_ID'),
voiceCategory: read('CATEGORY_VOICE_ID'),
}, },
gitea: { gitea: {
+2
View File
@@ -6,6 +6,7 @@ import { Client, Collection, GatewayIntentBits, Partials } from 'discord.js';
* - GuildMembers (privileged): welcome, departures, role assignment * - GuildMembers (privileged): welcome, departures, role assignment
* - GuildModeration: ban/kick audit events * - GuildModeration: ban/kick audit events
* - GuildMessages: /clear and ticket channels * - GuildMessages: /clear and ticket channels
* - GuildVoiceStates: temporary voice channels (M14)
* MessageContent is intentionally not requested. * MessageContent is intentionally not requested.
*/ */
export function createClient() { export function createClient() {
@@ -15,6 +16,7 @@ export function createClient() {
GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildModeration, GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildVoiceStates,
], ],
partials: [Partials.GuildMember], partials: [Partials.GuildMember],
}); });
@@ -0,0 +1,7 @@
-- Claim and close details of a ticket (M6-T05 / M6-T06)
ALTER TABLE tickets ADD COLUMN claimed_at TEXT;
ALTER TABLE tickets ADD COLUMN close_reason TEXT;
-- Faster lookups for the poll scheduler and the result rendering (M10)
CREATE INDEX IF NOT EXISTS idx_polls_due ON polls (status, ends_at);
CREATE INDEX IF NOT EXISTS idx_poll_votes_choice ON poll_votes (poll_id, choice_index);
@@ -0,0 +1,14 @@
-- Temporary voice channels created by joining the trigger channel (M14)
CREATE TABLE IF NOT EXISTS voice_channels (
channel_id TEXT PRIMARY KEY,
guild_id TEXT NOT NULL,
owner_id TEXT NOT NULL,
trigger_id TEXT,
name TEXT NOT NULL,
locked INTEGER NOT NULL DEFAULT 0,
user_limit INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_voice_channels_guild ON voice_channels (guild_id);
CREATE INDEX IF NOT EXISTS idx_voice_channels_owner ON voice_channels (guild_id, owner_id);
@@ -0,0 +1,50 @@
import { getDatabase } from '../index.js';
export function recordAction({
guildId,
action,
moderatorId,
targetId = null,
reason = null,
durationMs = null,
}) {
getDatabase()
.prepare(
`INSERT INTO moderation_actions (guild_id, action, target_id, moderator_id, reason, duration_ms)
VALUES (?, ?, ?, ?, ?, ?)`,
)
.run(guildId, action, targetId, moderatorId, reason, durationMs);
}
export function listActions({ guildId, targetId = null, action = null, limit = 20 }) {
const clauses = ['guild_id = ?'];
const params = [guildId];
if (targetId) {
clauses.push('target_id = ?');
params.push(targetId);
}
if (action) {
clauses.push('action = ?');
params.push(action);
}
params.push(limit);
return getDatabase()
.prepare(`SELECT * FROM moderation_actions WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
.all(...params);
}
export function countActions({ guildId, targetId, action }) {
const row = getDatabase()
.prepare(
'SELECT COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? AND target_id = ? AND action = ?',
)
.get(guildId, targetId, action);
return row.count;
}
export function countByAction(guildId) {
return getDatabase()
.prepare('SELECT action, COUNT(*) AS count FROM moderation_actions WHERE guild_id = ? GROUP BY action')
.all(guildId);
}
@@ -0,0 +1,34 @@
import { getDatabase } from '../index.js';
/** Per-guild override of a notification channel (M9-T01). */
export function setNotificationChannel({ guildId, type, channelId, detailLevel = 'normal' }) {
getDatabase()
.prepare(
`INSERT INTO notification_channels (guild_id, type, channel_id, detail_level)
VALUES (?, ?, ?, ?)
ON CONFLICT (guild_id, type) DO UPDATE SET
channel_id = excluded.channel_id,
detail_level = excluded.detail_level`,
)
.run(guildId, type, channelId, detailLevel);
}
export function getNotificationChannel(guildId, type) {
return (
getDatabase()
.prepare('SELECT * FROM notification_channels WHERE guild_id = ? AND type = ?')
.get(guildId, type) ?? null
);
}
export function listNotificationChannels(guildId) {
return getDatabase()
.prepare('SELECT * FROM notification_channels WHERE guild_id = ? ORDER BY type')
.all(guildId);
}
export function removeNotificationChannel(guildId, type) {
return getDatabase()
.prepare('DELETE FROM notification_channels WHERE guild_id = ? AND type = ?')
.run(guildId, type).changes;
}
@@ -0,0 +1,97 @@
import { getDatabase } from '../index.js';
export function createPoll({ guildId, channelId, creatorId, question, choices, endsAt = null }) {
const { lastInsertRowid } = getDatabase()
.prepare(
`INSERT INTO polls (guild_id, channel_id, creator_id, question, choices, ends_at)
VALUES (?, ?, ?, ?, ?, ?)`,
)
.run(guildId, channelId, creatorId, question, JSON.stringify(choices), endsAt);
return Number(lastInsertRowid);
}
export function attachPollMessage(id, messageId) {
getDatabase().prepare('UPDATE polls SET message_id = ? WHERE id = ?').run(messageId, id);
}
export function getPoll(id) {
return getDatabase().prepare('SELECT * FROM polls WHERE id = ?').get(id) ?? null;
}
export function getPollByMessage(messageId) {
return getDatabase().prepare('SELECT * FROM polls WHERE message_id = ?').get(messageId) ?? null;
}
export function listPolls({ guildId, status = null, limit = 10 }) {
const clauses = ['guild_id = ?'];
const params = [guildId];
if (status) {
clauses.push('status = ?');
params.push(status);
}
params.push(limit);
return getDatabase()
.prepare(`SELECT * FROM polls WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
.all(...params);
}
/** Polls whose end date is reached and that are still open (M10-T05). */
export function listDuePolls(limit = 10) {
return getDatabase()
.prepare(
`SELECT * FROM polls
WHERE status = 'open' AND ends_at IS NOT NULL AND ends_at <= datetime('now')
ORDER BY ends_at ASC LIMIT ?`,
)
.all(limit);
}
export function listOpenPolls(limit = 25) {
return getDatabase()
.prepare("SELECT * FROM polls WHERE status = 'open' ORDER BY id ASC LIMIT ?")
.all(limit);
}
export function listVotes(pollId) {
return getDatabase().prepare('SELECT user_id, choice_index FROM poll_votes WHERE poll_id = ?').all(pollId);
}
/** Counts votes per choice index: `[{ choice_index, count }]`. */
export function countVotes(pollId) {
return getDatabase()
.prepare('SELECT choice_index, COUNT(*) AS count FROM poll_votes WHERE poll_id = ? GROUP BY choice_index')
.all(pollId);
}
/**
* Creates or updates a vote. Returns 'created', 'changed' or 'unchanged' (M10-T04).
*/
export function castVote(pollId, userId, choiceIndex) {
const database = getDatabase();
const previous = database
.prepare('SELECT choice_index FROM poll_votes WHERE poll_id = ? AND user_id = ?')
.get(pollId, userId);
if (previous && previous.choice_index === choiceIndex) return 'unchanged';
database
.prepare(
`INSERT INTO poll_votes (poll_id, user_id, choice_index) VALUES (?, ?, ?)
ON CONFLICT (poll_id, user_id) DO UPDATE SET choice_index = excluded.choice_index,
voted_at = datetime('now')`,
)
.run(pollId, userId, choiceIndex);
return previous ? 'changed' : 'created';
}
export function closePoll(id) {
return getDatabase().prepare("UPDATE polls SET status = 'closed' WHERE id = ? AND status = 'open'").run(id)
.changes;
}
export function countPolls(guildId) {
const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM polls WHERE guild_id = ?').get(guildId);
return row.count;
}
@@ -7,6 +7,18 @@ export function getSetting(guildId, key, fallback = null) {
return row ? JSON.parse(row.value) : fallback; return row ? JSON.parse(row.value) : fallback;
} }
/**
* Reads a setting without throwing when the database is not ready (tests, early startup).
* Never use it when a missing database should be an error.
*/
export function resolveSetting(guildId, key, fallback = null) {
try {
return getSetting(guildId, key, fallback);
} catch {
return fallback;
}
}
export function setSetting(guildId, key, value, updatedBy = null) { export function setSetting(guildId, key, value, updatedBy = null) {
getDatabase() getDatabase()
.prepare( .prepare(
@@ -0,0 +1,71 @@
import { getDatabase } from '../index.js';
export function createTicket({ guildId, channelId, categoryId, authorId }) {
const { lastInsertRowid } = getDatabase()
.prepare('INSERT INTO tickets (guild_id, channel_id, category_id, author_id) VALUES (?, ?, ?, ?)')
.run(guildId, channelId, categoryId, authorId);
return Number(lastInsertRowid);
}
export function getTicket(id) {
return getDatabase().prepare('SELECT * FROM tickets WHERE id = ?').get(id) ?? null;
}
export function getTicketByChannel(channelId) {
return getDatabase().prepare('SELECT * FROM tickets WHERE channel_id = ?').get(channelId) ?? null;
}
/** Returns the open ticket of an author for a category, if any (M6-T08). */
export function getOpenTicket({ guildId, authorId, categoryId }) {
return (
getDatabase()
.prepare(
`SELECT * FROM tickets
WHERE guild_id = ? AND author_id = ? AND category_id = ? AND status = 'open'`,
)
.get(guildId, authorId, categoryId) ?? null
);
}
export function listTickets({ guildId, status = null, authorId = null, limit = 20 }) {
const clauses = ['guild_id = ?'];
const params = [guildId];
if (status) {
clauses.push('status = ?');
params.push(status);
}
if (authorId) {
clauses.push('author_id = ?');
params.push(authorId);
}
params.push(limit);
return getDatabase()
.prepare(`SELECT * FROM tickets WHERE ${clauses.join(' AND ')} ORDER BY id DESC LIMIT ?`)
.all(...params);
}
export function claimTicket(id, userId) {
return getDatabase()
.prepare(
"UPDATE tickets SET claimed_by = ?, claimed_at = datetime('now') WHERE id = ? AND status = 'open'",
)
.run(userId, id).changes;
}
export function closeTicket(id, { closedBy, reason = null }) {
return getDatabase()
.prepare(
`UPDATE tickets
SET status = 'closed', closed_at = datetime('now'), closed_by = ?, close_reason = ?
WHERE id = ? AND status = 'open'`,
)
.run(closedBy, reason, id).changes;
}
export function countOpenTickets(guildId) {
const row = getDatabase()
.prepare("SELECT COUNT(*) AS count FROM tickets WHERE guild_id = ? AND status = 'open'")
.get(guildId);
return row.count;
}
@@ -0,0 +1,64 @@
import { getDatabase } from '../index.js';
export function addVoiceChannel({ channelId, guildId, ownerId, triggerId = null, name, userLimit = 0 }) {
getDatabase()
.prepare(
`INSERT INTO voice_channels (channel_id, guild_id, owner_id, trigger_id, name, user_limit)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (channel_id) DO UPDATE SET
owner_id = excluded.owner_id,
name = excluded.name`,
)
.run(channelId, guildId, ownerId, triggerId, name, userLimit);
}
export function getVoiceChannel(channelId) {
return getDatabase().prepare('SELECT * FROM voice_channels WHERE channel_id = ?').get(channelId) ?? null;
}
export function listVoiceChannels(guildId) {
return getDatabase()
.prepare('SELECT * FROM voice_channels WHERE guild_id = ? ORDER BY created_at ASC')
.all(guildId);
}
/** Channels still owned by a member, used to move them back instead of creating another (M14-T03). */
export function listOwnedVoiceChannels(guildId, ownerId) {
return getDatabase()
.prepare('SELECT * FROM voice_channels WHERE guild_id = ? AND owner_id = ? ORDER BY created_at ASC')
.all(guildId, ownerId);
}
export function setVoiceOwner(channelId, ownerId) {
return getDatabase()
.prepare('UPDATE voice_channels SET owner_id = ? WHERE channel_id = ?')
.run(ownerId, channelId).changes;
}
export function setVoiceName(channelId, name) {
return getDatabase().prepare('UPDATE voice_channels SET name = ? WHERE channel_id = ?').run(name, channelId)
.changes;
}
export function setVoiceLocked(channelId, locked) {
return getDatabase()
.prepare('UPDATE voice_channels SET locked = ? WHERE channel_id = ?')
.run(locked ? 1 : 0, channelId).changes;
}
export function setVoiceLimit(channelId, userLimit) {
return getDatabase()
.prepare('UPDATE voice_channels SET user_limit = ? WHERE channel_id = ?')
.run(userLimit, channelId).changes;
}
export function removeVoiceChannel(channelId) {
return getDatabase().prepare('DELETE FROM voice_channels WHERE channel_id = ?').run(channelId).changes;
}
export function countVoiceChannels(guildId) {
const row = getDatabase()
.prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE guild_id = ?')
.get(guildId);
return row.count;
}
+4
View File
@@ -1,5 +1,7 @@
import { ActivityType, Events } from 'discord.js'; import { ActivityType, Events } from 'discord.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
import { startPollScheduler } from '../services/polls/poll-service.js';
import { sweepVoiceChannels } from '../services/voice/voice-service.js';
const log = createLogger('discord'); const log = createLogger('discord');
@@ -8,6 +10,8 @@ export const once = true;
export async function execute(client) { export async function execute(client) {
client.user.setActivity('FWS Arch', { type: ActivityType.Watching }); client.user.setActivity('FWS Arch', { type: ActivityType.Watching });
startPollScheduler(client);
await sweepVoiceChannels(client);
log.info(`Connected as ${client.user.tag}`, { log.info(`Connected as ${client.user.tag}`, {
guilds: client.guilds.cache.size, guilds: client.guilds.cache.size,
commands: client.commands.size, commands: client.commands.size,
+11 -2
View File
@@ -1,11 +1,20 @@
import { Events } from 'discord.js'; import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
import {
assignMemberRole,
sendWelcome,
sendWelcomeDirectMessage,
} from '../services/members/member-service.js';
const log = createLogger('members'); const log = createLogger('members');
export const name = Events.GuildMemberAdd; export const name = Events.GuildMemberAdd;
// TODO(M7-T01..T04): welcome message, rules and resources, initial role. /** Welcome message, resources and default role (M7-T01..T04). */
export async function execute(_client, member) { export async function execute(client, member) {
log.info('Member joined', { userId: member.id, guildId: member.guild.id }); log.info('Member joined', { userId: member.id, guildId: member.guild.id });
await assignMemberRole(member);
await sendWelcome(client, member);
await sendWelcomeDirectMessage(member);
} }
+4 -2
View File
@@ -1,11 +1,13 @@
import { Events } from 'discord.js'; import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
import { announceDeparture } from '../services/members/member-service.js';
const log = createLogger('members'); const log = createLogger('members');
export const name = Events.GuildMemberRemove; export const name = Events.GuildMemberRemove;
// TODO(M7-T04): log departures in the configured channel. /** Announces and records departures (M7-T04). */
export async function execute(_client, member) { export async function execute(client, member) {
log.info('Member left', { userId: member.id, guildId: member.guild.id }); log.info('Member left', { userId: member.id, guildId: member.guild.id });
await announceDeparture(client, member);
} }
+47 -12
View File
@@ -2,12 +2,25 @@ import { Events, MessageFlags } from 'discord.js';
import { PermissionDeniedError, UserFacingError } from '../core/errors.js'; import { PermissionDeniedError, UserFacingError } from '../core/errors.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
import { hasAccess } from '../core/permissions.js'; import { hasAccess } from '../core/permissions.js';
import { handleGiteaModal } from '../services/gitea/gitea-modals.js';
import { handlePollComponent } from '../services/polls/poll-service.js';
import { handleTicketComponent } from '../services/tickets/ticket-service.js';
import { handleVoiceComponent, handleVoiceModal } from '../services/voice/voice-service.js';
import { errorEmbed } from '../ui/embeds.js'; import { errorEmbed } from '../ui/embeds.js';
const log = createLogger('interactions'); const log = createLogger('interactions');
export const name = Events.InteractionCreate; export const name = Events.InteractionCreate;
/** Custom id prefix -> handlers for the message components and the modals. */
const routes = [
{ prefix: 'ticket:', component: handleTicketComponent },
{ prefix: 'poll:', component: handlePollComponent },
{ prefix: 'voice:', component: handleVoiceComponent, modal: handleVoiceModal },
{ prefix: 'issue:', modal: handleGiteaModal },
{ prefix: 'pr:', modal: handleGiteaModal },
];
async function replyError(interaction, message) { async function replyError(interaction, message) {
const payload = { embeds: [errorEmbed(message)], flags: MessageFlags.Ephemeral }; const payload = { embeds: [errorEmbed(message)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) { if (interaction.deferred || interaction.replied) {
@@ -17,31 +30,53 @@ async function replyError(interaction, message) {
} }
} }
export async function execute(client, interaction) { async function runChatInputCommand(interaction) {
if (!interaction.isChatInputCommand() && !interaction.isAutocomplete()) return; const command = interaction.client.commands.get(interaction.commandName);
const command = client.commands.get(interaction.commandName);
if (!command) return; if (!command) return;
if (interaction.isAutocomplete()) { const subcommand = interaction.options.getSubcommand(false);
await command.autocomplete?.(interaction); const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access;
if (!hasAccess(interaction.member, requiredLevel)) {
throw new PermissionDeniedError();
}
await command.execute(interaction);
}
async function runRoute(interaction, kind) {
const route = routes.find(
({ prefix, [kind]: handler }) => handler && interaction.customId.startsWith(prefix),
);
if (!route) {
log.debug(`Ignored ${kind} ${interaction.customId}`);
return; return;
} }
await route[kind](interaction);
}
export async function execute(_client, interaction) {
try { try {
const subcommand = interaction.options.getSubcommand(false); if (interaction.isAutocomplete()) {
const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access; await interaction.client.commands.get(interaction.commandName)?.autocomplete?.(interaction);
if (!hasAccess(interaction.member, requiredLevel)) { return;
throw new PermissionDeniedError();
} }
await command.execute(interaction); if (interaction.isButton() || interaction.isAnySelectMenu()) {
await runRoute(interaction, 'component');
return;
}
if (interaction.isModalSubmit()) {
await runRoute(interaction, 'modal');
return;
}
if (!interaction.isChatInputCommand()) return;
await runChatInputCommand(interaction);
} catch (error) { } catch (error) {
if (error instanceof UserFacingError) { if (error instanceof UserFacingError) {
await replyError(interaction, error.message); await replyError(interaction, error.message);
return; return;
} }
log.error(`Command failed: /${interaction.commandName}`, error); log.error(`Interaction failed: ${interaction.commandName ?? interaction.customId ?? 'unknown'}`, error);
await replyError(interaction, 'Une erreur inattendue est survenue. Réessaie plus tard.').catch(() => {}); await replyError(interaction, 'Une erreur inattendue est survenue. Réessaie plus tard.').catch(() => {});
} }
} }
+33
View File
@@ -0,0 +1,33 @@
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
import { cleanupVoiceChannel, createFromTrigger, getVoiceSettings } from '../services/voice/voice-service.js';
const log = createLogger('voice');
export const name = Events.VoiceStateUpdate;
/**
* Joining the trigger channel creates a private channel and moves the member in;
* leaving a temporary channel deletes it once the last member is gone (M14-T02 / M14-T04).
*/
export async function execute(_client, oldState, newState) {
const member = newState.member ?? oldState.member;
if (!member || member.user.bot) return;
try {
const joinedId =
newState.channelId && newState.channelId !== oldState.channelId ? newState.channelId : null;
if (joinedId) {
const settings = getVoiceSettings(newState.guild.id);
if (settings.triggerId && joinedId === settings.triggerId) {
await createFromTrigger(member);
}
}
if (oldState.channelId && oldState.channelId !== newState.channelId) {
await cleanupVoiceChannel(oldState.guild, oldState.channelId);
}
} catch (error) {
log.error('Voice state handling failed', error);
}
}
+18
View File
@@ -34,6 +34,22 @@ export async function giteaRequest(endpoint, { method = 'GET', body } = {}) {
); );
} }
/** True when both the Gitea URL and token are configured (M5-T01). */
export function isGiteaConfigured() {
return Boolean(env.gitea.url && env.gitea.token);
}
/** Gitea returns either a bare array or a `{ data: [...] }` wrapper depending on the version. */
export function asList(payload) {
if (Array.isArray(payload)) return payload;
return Array.isArray(payload?.data) ? payload.data : [];
}
/** Human readable URL of the configured repository, used in embeds. */
export function repositoryUrl() {
return env.gitea.url ? `${env.gitea.url}/${env.gitea.owner}/${env.gitea.repo}` : '';
}
const repoPath = () => `/repos/${env.gitea.owner}/${env.gitea.repo}`; const repoPath = () => `/repos/${env.gitea.owner}/${env.gitea.repo}`;
export const gitea = { export const gitea = {
@@ -48,4 +64,6 @@ export const gitea = {
listCommits: (limit = 10) => giteaRequest(`${repoPath()}/commits?limit=${limit}`), listCommits: (limit = 10) => giteaRequest(`${repoPath()}/commits?limit=${limit}`),
listReleases: (limit = 5) => giteaRequest(`${repoPath()}/releases?limit=${limit}`), listReleases: (limit = 5) => giteaRequest(`${repoPath()}/releases?limit=${limit}`),
getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`), getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`),
getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`),
listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`),
}; };
+96
View File
@@ -0,0 +1,96 @@
import { COLORS } from '../../config/constants.js';
import { baseEmbed } from '../../ui/embeds.js';
const DESCRIPTION_MAX = 1500;
/** Truncates free text coming from the API before it reaches Discord. */
export function truncate(text, max = DESCRIPTION_MAX) {
const value = String(text ?? '').trim();
if (!value) return '';
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
}
const authorOf = (source) =>
source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'inconnu';
/** Shared header of an issue, used by `/issue` and the webhooks (M5-T02 / M9-T04). */
export function issueEmbed(issue) {
const embed = baseEmbed(COLORS.gitea)
.setTitle(`#${issue.number} ${issue.title}`)
.setDescription(truncate(issue.body) || 'Pas de description.')
.addFields(
{ name: 'Auteur', value: authorOf(issue), inline: true },
{ name: 'État', value: issue.state === 'closed' ? 'Fermée' : 'Ouverte', inline: true },
{ name: 'Commentaires', value: String(issue.comments ?? 0), inline: true },
);
if (issue.html_url) embed.setURL(issue.html_url);
const labels = (issue.labels ?? []).map((label) => label.name).filter(Boolean);
if (labels.length > 0) embed.addFields({ name: 'Labels', value: labels.join(', ') });
return embed;
}
/** Shared header of a pull request (M5-T04 / M9-T05). */
export function pullRequestEmbed(pull) {
const state = pull.merged ? 'Fusionnée' : pull.state === 'closed' ? 'Fermée' : 'Ouverte';
const embed = baseEmbed(COLORS.gitea)
.setTitle(`PR #${pull.number} ${pull.title}`)
.setDescription(truncate(pull.body) || 'Pas de description.')
.addFields(
{ name: 'Auteur', value: authorOf(pull), inline: true },
{ name: 'État', value: state, inline: true },
{ name: 'Branches', value: `${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'}`, inline: true },
);
if (pull.html_url) embed.setURL(pull.html_url);
return embed;
}
/** Release notes, shared by `/fws version`, `/fws changelog` and the webhooks. */
export function releaseEmbed(release, { withNotes = true } = {}) {
const embed = baseEmbed(COLORS.gitea)
.setTitle(`${release.name || release.tag_name}`)
.addFields(
{ name: 'Tag', value: release.tag_name ?? 'inconnu', inline: true },
{ name: 'Publiée par', value: authorOf(release), inline: true },
{ name: 'Pré-version', value: release.prerelease ? 'Oui' : 'Non', inline: true },
);
if (release.html_url) embed.setURL(release.html_url);
if (release.published_at) {
const timestamp = Math.floor(new Date(release.published_at).getTime() / 1000);
embed.addFields({ name: 'Date', value: `<t:${timestamp}:f>`, inline: true });
}
if (withNotes && release.body) embed.setDescription(truncate(release.body, 3900));
return embed;
}
/** Push notification: the last commits of a branch (M9-T06). */
export function pushEmbed(payload, maxCommits = 5) {
const commits = payload.commits ?? [];
const branch = (payload.ref ?? '').replace('refs/heads/', '');
const lines = commits
.slice(0, maxCommits)
.map((commit) => `\`${String(commit.id).slice(0, 7)}\` ${truncate(commit.message?.split('\n')[0], 90)}`);
const remaining = commits.length - lines.length;
const embed = baseEmbed(COLORS.gitea)
.setTitle(`Push sur ${branch || 'le dépôt'}`)
.setDescription(lines.join('\n') || 'Aucun commit dans cet événement.')
.addFields(
{ name: 'Auteur', value: authorOf(payload), inline: true },
{ name: 'Commits', value: String(commits.length), inline: true },
);
if (remaining > 0) embed.addFields({ name: 'Et', value: `${remaining} autre(s) commit(s)` });
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed;
}
/** Git references created or deleted (`create` / `delete` events). */
export function refEmbed(payload, action) {
const ref = payload.ref ?? 'inconnu';
const refType = payload.ref_type ?? 'ref';
const embed = baseEmbed(COLORS.gitea)
.setTitle(`${action === 'deleted' ? 'Suppression' : 'Création'} de ${refType} : ${ref}`)
.setDescription(`${authorOf(payload)} a ${action === 'deleted' ? 'supprimé' : 'créé'} \`${ref}\`.`);
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed;
}
+148
View File
@@ -0,0 +1,148 @@
import { ActionRowBuilder, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
import { ExternalApiError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { linkButtons } from '../../ui/buttons.js';
import { errorEmbed } from '../../ui/embeds.js';
import { issueEmbed, pullRequestEmbed } from './gitea-embeds.js';
import { gitea, isGiteaConfigured } from './gitea-client.js';
import { consume, remember } from './pending-actions.js';
const log = createLogger('gitea');
const PR_CONTEXT_TTL_MS = 10 * 60_000;
/** Fails fast with an actionable message when Gitea is not configured (M5-T01). */
export function assertGiteaConfigured() {
if (!isGiteaConfigured()) {
throw new UserFacingError('Gitea n’est pas configuré : renseigne `GITEA_URL` et `GITEA_TOKEN`.');
}
}
function modal(id, title, fields) {
return new ModalBuilder()
.setCustomId(id)
.setTitle(title)
.addComponents(
fields.map((field) =>
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId(field.id)
.setLabel(field.label)
.setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short)
.setMaxLength(field.maxLength)
.setRequired(field.required ?? true),
),
),
);
}
/** `/issue create` collects the title and description through a modal (M5-T03). */
export async function openIssueModal(interaction) {
assertGiteaConfigured();
await interaction.showModal(
modal('issue:create', 'Nouvelle issue Gitea', [
{ id: 'title', label: 'Titre', maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000 },
]),
);
}
/** `/pr create` keeps the branch options and asks for the title through a modal. */
export async function openPullRequestModal(interaction) {
assertGiteaConfigured();
const head = interaction.options.getString('head', true);
const base = interaction.options.getString('base', true);
remember(`pr:${interaction.user.id}`, { head, base }, { ttlMs: PR_CONTEXT_TTL_MS });
await interaction.showModal(
modal('pr:create', 'Nouvelle pull request', [
{ id: 'title', label: `Titre (${head} → ${base})`, maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000, required: false },
]),
);
}
/** Turns an API failure into a message the user can act on (M5-T08). */
export async function replyGiteaFailure(interaction, error) {
log.error('Gitea request failed', error);
const detail =
error instanceof ExternalApiError && /not configured/.test(error.message)
? 'Gitea n’est pas configuré.'
: 'Gitea est momentanément indisponible. Réessaie dans quelques instants.';
const payload = { embeds: [errorEmbed(detail)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) {
await interaction.followUp(payload).catch(() => {});
} else {
await interaction.reply(payload).catch(() => {});
}
}
export async function submitIssueModal(interaction) {
assertGiteaConfigured();
await interaction.deferReply();
try {
const issue = await gitea.createIssue({
title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`,
});
logEvent({
guildId: interaction.guildId,
type: 'gitea.issue.created',
actorId: interaction.user.id,
payload: { number: issue.number },
});
await interaction.editReply({
embeds: [issueEmbed(issue)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: issue.html_url }]),
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
export async function submitPullRequestModal(interaction) {
assertGiteaConfigured();
const context = consume(`pr:${interaction.user.id}`);
if (!context) {
throw new UserFacingError('Session expirée : relance `/pr create` pour choisir à nouveau les branches.');
}
await interaction.deferReply();
try {
const pull = await gitea.createPullRequest({
title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`.trim(),
head: context.head,
base: context.base,
});
logEvent({
guildId: interaction.guildId,
type: 'gitea.pull_request.created',
actorId: interaction.user.id,
payload: { number: pull.number, head: context.head, base: context.base },
});
await interaction.editReply({
embeds: [pullRequestEmbed(pull)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: pull.html_url }]),
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
/** Routes the modal submissions opened by `/issue` and `/pr` (M5-T09). */
export async function handleGiteaModal(interaction) {
switch (interaction.customId) {
case 'issue:create':
await submitIssueModal(interaction);
return;
case 'pr:create':
await submitPullRequestModal(interaction);
return;
default:
log.debug(`Ignored unknown modal ${interaction.customId}`);
}
}
+32
View File
@@ -0,0 +1,32 @@
/**
* In-memory store for the short-lived context of a modal flow, e.g. the branches
* of `/pr create` which are typed as options but sent with the modal (M5-T04).
* Entries expire on their own and disappear on restart.
*/
const DEFAULT_TTL_MS = 5 * 60_000;
const entries = new Map();
export function remember(key, value, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) {
entries.set(key, { value, expiresAt: now + ttlMs });
return value;
}
/** Returns the stored value and forgets it, or null when missing or expired. */
export function consume(key, { now = Date.now() } = {}) {
const entry = entries.get(key);
if (!entry) return null;
entries.delete(key);
return entry.expiresAt > now ? entry.value : null;
}
export function purgeExpired(now = Date.now()) {
for (const [key, entry] of entries) {
if (entry.expiresAt <= now) entries.delete(key);
}
return entries.size;
}
export function pendingCount() {
return entries.size;
}
+115
View File
@@ -0,0 +1,115 @@
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 { baseEmbed } from '../../ui/embeds.js';
const log = createLogger('members');
const DEFAULT_WELCOME = 'Bienvenue sur le serveur **FWS** !';
async function sendTo(channel) {
return channel?.isSendable() ? channel : null;
}
/** Sends the welcome embed in `CHANNEL_WELCOME_ID` (M7-T01 / M7-T02). */
export async function sendWelcome(client, member) {
if (!env.channels.welcome) {
log.debug('No welcome channel configured');
return;
}
const channel = await sendTo(await client.channels.fetch(env.channels.welcome).catch(() => null));
if (!channel) {
log.warn('Welcome channel unavailable', { channelId: env.channels.welcome });
return;
}
const embed = baseEmbed(COLORS.primary)
.setTitle('Nouveau membre !')
.setDescription(`${member} rejoint le serveur. ${DEFAULT_WELCOME}`)
.addFields({ name: 'Membres', value: String(member.guild.memberCount), inline: true })
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
if (env.channels.rules) {
embed.addFields({ name: 'Règlement', value: `À lire dans <#${env.channels.rules}>` });
}
await channel.send({ content: `${member}`, embeds: [embed] });
logEvent({ guildId: member.guild.id, type: 'member.welcome', payload: { userId: member.id } });
}
/** Gives the default member role (M7-T03). */
export async function assignMemberRole(member) {
const roleId = env.roles.member;
if (!roleId || member.roles.cache.has(roleId)) return;
const role = await member.guild.roles.fetch(roleId).catch(() => null);
if (!role) {
log.warn('Default member role not found', { roleId });
return;
}
if (member.guild.members.me?.roles.highest.comparePositionTo(role) <= 0) {
log.warn('Member role is above the bot role, skipping', { roleId });
return;
}
await member.roles.add(role, 'Rôle par défaut à l’arrivée').catch((error) => {
log.warn('Could not assign the member role', error);
});
}
/** Welcomes the member in a direct message with the server resources (M7-T02). */
export async function sendWelcomeDirectMessage(member) {
const links = [
env.links.website && `[Site officiel](${env.links.website})`,
env.links.docs && `[Documentation](${env.links.docs})`,
env.links.archRepo && `[Dépôt FWS Arch](${env.links.archRepo})`,
].filter(Boolean);
const embed = baseEmbed(COLORS.primary)
.setTitle(`Bienvenue sur ${member.guild.name} !`)
.setDescription(
'Merci de rejoindre la communauté FWS. Prends un instant pour lire le règlement, ' +
'puis présente-toi si tu le souhaites.',
);
if (links.length > 0) embed.addFields({ name: 'Ressources', value: links.join('\n') });
await member.send({ embeds: [embed] }).catch(() => {
log.debug('Welcome DM could not be delivered', { userId: member.id });
});
}
/** Logs a departure in the log channel (M7-T04). */
export async function announceDeparture(client, member) {
const channelId = env.channels.logs || env.channels.modLogs;
if (!channelId) return;
const channel = await sendTo(await client.channels.fetch(channelId).catch(() => null));
if (!channel) return;
const joinedAt = member.joinedTimestamp;
const embed = baseEmbed(COLORS.warning)
.setTitle('Départ d’un membre')
.setDescription(`${member.user.tag} a quitté le serveur.`)
.addFields(
{ name: 'Membres', value: String(member.guild.memberCount), inline: true },
{
name: 'Compte créé',
value: `<t:${Math.floor(member.user.createdTimestamp / 1000)}:R>`,
inline: true,
},
)
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
if (joinedAt) {
embed.addFields({ name: 'Arrivé', value: `<t:${Math.floor(joinedAt / 1000)}:R>`, inline: true });
}
await channel.send({ embeds: [embed] });
logEvent({
guildId: member.guild.id,
type: 'member.left',
payload: { userId: member.id, joinedAt: joinedAt ?? null },
});
}
@@ -0,0 +1,118 @@
import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { UserFacingError } from '../../core/errors.js';
import { canActOn } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { recordAction } from '../../database/repositories/moderation-repository.js';
import { baseEmbed } from '../../ui/embeds.js';
/**
* Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08).
* @param {import('discord.js').ChatInputCommandInteraction} interaction
* @param {import('discord.js').GuildMember} target
*/
export function assertModerationTarget(interaction, target) {
if (!target) throw new UserFacingError('Ce membre n’est pas présent sur le serveur.');
if (target.id === interaction.user.id) {
throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi-même.');
}
if (!canActOn(interaction.member, target)) {
throw new UserFacingError('Tu ne peux pas agir sur ce membre : son rôle est égal ou supérieur au tien.');
}
const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(target.roles.highest) <= 0) {
throw new UserFacingError(`Mon rôle est trop bas pour agir sur ${target.user.tag}.`);
}
}
/**
* Records the action in SQLite and mirrors it in the moderation log channel (M8-T06).
* Call it only once the Discord action has succeeded.
*/
export async function logModerationAction(
interaction,
{ action, targetId, reason = null, durationMs = null },
) {
recordAction({
guildId: interaction.guildId,
action,
moderatorId: interaction.user.id,
targetId,
reason,
durationMs,
});
logEvent({
guildId: interaction.guildId,
type: `moderation.${action}`,
actorId: interaction.user.id,
payload: { targetId, reason, durationMs },
});
const meta = MODERATION_ACTIONS[action];
await sendModerationLog(interaction.client, interaction.guild, {
action,
color: meta?.color ?? COLORS.moderation,
targetId,
moderatorId: interaction.user.id,
reason,
durationMs,
});
}
/** Posts an entry in `CHANNEL_MOD_LOGS_ID`, if configured (M8-T06). */
export async function sendModerationLog(
client,
guild,
{ action, targetId, moderatorId, reason, durationMs },
) {
if (!env.channels.modLogs) return;
const channel = await client.channels.fetch(env.channels.modLogs).catch(() => null);
if (!channel?.isSendable()) return;
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color)
.setTitle(`Modération — ${meta?.label ?? action}`)
.addFields(
{ name: 'Cible', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true },
{ name: 'Modérateur', value: `<@${moderatorId}>`, inline: true },
{ name: 'Raison', value: reason || 'Non précisée' },
);
if (durationMs) {
embed.addFields({ name: 'Durée', value: formatDuration(durationMs), inline: true });
}
if (guild) embed.setFooter({ text: `${guild.name} · ${guild.id}` });
await channel.send({ embeds: [embed] }).catch(() => {});
}
/** Direct message sent to the member who is being moderated (M8-T07). */
export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) {
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color)
.setTitle(`Sanction sur ${guildName}`)
.setDescription(`Action : **${meta?.label ?? action}**`)
.addFields({ name: 'Raison', value: reason || 'Non précisée' });
if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) });
return embed;
}
/** Human readable duration for embeds: `2 h 30 min`. */
export function formatDuration(durationMs) {
const minutes = Math.round(durationMs / 60_000);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
if (hours < 24) return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`;
const days = Math.floor(hours / 24);
const remainingHours = hours % 24;
return remainingHours === 0 ? `${days} j` : `${days} j ${remainingHours} h`;
}
/** Fetches the member targeted by a command, with a clear error if absent. */
export async function fetchTargetMember(interaction, userId) {
const member = await interaction.guild.members.fetch(userId).catch(() => null);
if (!member) throw new UserFacingError('Ce membre n’est pas présent sur le serveur.');
return member;
}
@@ -0,0 +1,31 @@
import { GITEA_EVENT_TYPES } from '../../config/constants.js';
import { issueEmbed, pullRequestEmbed, pushEmbed, releaseEmbed, refEmbed } from '../gitea/gitea-embeds.js';
/**
* Maps a raw Gitea webhook to `{ type, embed }`, or returns null when the event
* should not be published (M9-T03).
*/
export function buildGiteaNotification(event, payload) {
const type = GITEA_EVENT_TYPES[event];
if (!type) return null;
switch (event) {
case 'issues':
return { type, embed: issueEmbed(payload.issue ?? payload) };
case 'pull_request':
return { type, embed: pullRequestEmbed(payload.pull_request ?? payload) };
case 'push':
if (!payload.commits?.length) return null;
return { type, embed: pushEmbed(payload) };
case 'create':
case 'delete':
return {
type,
embed: refEmbed(payload, payload.ref_type && event === 'delete' ? 'deleted' : 'created'),
};
case 'release':
return { type, embed: releaseEmbed(payload.release ?? payload) };
default:
return null;
}
}
@@ -1,18 +1,31 @@
import { env } from '../../config/env.js'; import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js'; import { createLogger } from '../../core/logger.js';
import { getNotificationChannel } from '../../database/repositories/notification-repository.js';
import { errorEmbed } from '../../ui/embeds.js';
const log = createLogger('notifications'); const log = createLogger('notifications');
/** Fallback routing from the environment when the guild has no override (M9-T01). */
const defaultChannels = { const defaultChannels = {
issues: env.channels.notifIssues, issues: env.channels.notifIssues,
pull_request: env.channels.notifPullRequests, pull_request: env.channels.notifPullRequests,
push: env.channels.notifCommits, push: env.channels.notifCommits,
release: env.channels.notifReleases, release: env.channels.notifReleases,
errors: env.channels.notifErrors, errors: env.channels.notifErrors,
announcements: env.channels.announcements,
community: env.channels.logs,
}; };
// TODO(M9-T01): resolve channels from notification_channels in SQLite first. /** SQLite override first, then the environment default (M9-T01). */
export function resolveChannelId(type) { export function resolveChannelId(type, guildId = env.discord.guildId) {
try {
if (guildId) {
const override = getNotificationChannel(guildId, type);
if (override?.channel_id) return override.channel_id;
}
} catch {
// The database is unavailable (tests, early startup): use the environment.
}
return defaultChannels[type] ?? null; return defaultChannels[type] ?? null;
} }
@@ -21,13 +34,26 @@ export async function notify(client, type, payload) {
const channelId = resolveChannelId(type); const channelId = resolveChannelId(type);
if (!channelId) { if (!channelId) {
log.debug(`No channel configured for notification type ${type}`); log.debug(`No channel configured for notification type ${type}`);
return; return null;
} }
const channel = await client.channels.fetch(channelId).catch(() => null); const channel = await client.channels.fetch(channelId).catch(() => null);
if (!channel?.isSendable()) { if (!channel?.isSendable()) {
log.warn(`Notification channel unavailable for ${type}`, { channelId }); log.warn(`Notification channel unavailable for ${type}`, { channelId });
return; return null;
} }
await channel.send(payload); return channel.send(payload);
}
/** Reports an unexpected failure in the technical channel (M9-T07). */
export async function notifyError(client, error, context = 'application') {
log.error(`Notification error (${context})`, error);
return notify(client, 'errors', {
embeds: [
errorEmbed(`Une erreur est survenue dans **${context}**.`).addFields({
name: 'Détail',
value: `\`${String(error?.message ?? error).slice(0, 500)}\``,
}),
],
});
} }
+211
View File
@@ -0,0 +1,211 @@
import { MessageFlags } from 'discord.js';
import { COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
attachPollMessage,
castVote,
closePoll,
countVotes,
createPoll as createPollRow,
getPoll,
listDuePolls,
} from '../../database/repositories/poll-repository.js';
import { POLL_CHOICES_MAX, pollButtons } from '../../ui/buttons.js';
import { baseEmbed } from '../../ui/embeds.js';
const log = createLogger('polls');
const CHOICES_MIN = 2;
const BAR_LENGTH = 12;
const SCHEDULER_INTERVAL_MS = 30_000;
/** Splits the `choices` option on `;` and validates the count (M10-T01). */
export function parseChoices(input, { min = CHOICES_MIN, max = POLL_CHOICES_MAX } = {}) {
const choices = String(input)
.split(';')
.map((choice) => choice.trim())
.filter(Boolean);
if (choices.length < min || choices.length > max) {
throw new UserFacingError(`Un sondage doit proposer entre ${min} et ${max} choix séparés par « ; ».`);
}
if (new Set(choices.map((choice) => choice.toLowerCase())).size !== choices.length) {
throw new UserFacingError('Les choix d’un sondage doivent être différents.');
}
return choices;
}
/** SQLite stores datetimes as UTC `YYYY-MM-DD HH:MM:SS`. */
export function toSqliteDate(date) {
return date.toISOString().slice(0, 19).replace('T', ' ');
}
function renderBar(ratio) {
const filled = Math.round(ratio * BAR_LENGTH);
return `${'█'.repeat(filled)}${'░'.repeat(BAR_LENGTH - filled)}`;
}
/** Results embed, shared by creation, voting and closing (M10-T06). */
export function buildPollEmbed(poll, counts = countVotes(poll.id)) {
const choices = JSON.parse(poll.choices);
const countFor = (index) => counts.find((row) => row.choice_index === index)?.count ?? 0;
const total = choices.reduce((sum, _choice, index) => sum + countFor(index), 0);
const lines = choices.map((choice, index) => {
const count = countFor(index);
const percent = total === 0 ? 0 : Math.round((count / total) * 100);
return `**${index + 1}. ${choice}**\n\`${renderBar(total === 0 ? 0 : count / total)}\` ${count} (${percent} %)`;
});
const embed = baseEmbed(COLORS.info)
.setTitle(`Sondage #${poll.id} — ${poll.question}`)
.setDescription(lines.join('\n\n'))
.addFields(
{ name: 'Votes', value: String(total), inline: true },
{ name: 'Créé par', value: `<@${poll.creator_id}>`, inline: true },
{ name: 'Statut', value: poll.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
);
if (poll.ends_at) {
const timestamp = Math.floor(new Date(`${poll.ends_at.replace(' ', 'T')}Z`).getTime() / 1000);
embed.addFields({ name: 'Fin', value: `<t:${timestamp}:R>`, inline: true });
}
if (poll.status === 'closed') {
embed.setColor(COLORS.success);
const best = choices.reduce(
(winner, _choice, index) => (countFor(index) > countFor(winner) ? index : winner),
0,
);
const top = countFor(best);
embed.addFields({
name: 'Résultat',
value: total === 0 || top === 0 ? 'Aucun vote' : `**${choices[best]}** (${top} vote(s))`,
});
}
return embed;
}
export function buildPollComponents(poll) {
return poll.status === 'open' ? pollButtons(poll.id, JSON.parse(poll.choices)) : [];
}
/** Creates the poll message and records it (M10-T01 / M10-T02). */
export async function createPoll(interaction, { question, choicesInput, minutes = null }) {
const choices = parseChoices(choicesInput);
const endsAt = minutes ? toSqliteDate(new Date(Date.now() + minutes * 60_000)) : null;
const pollId = createPollRow({
guildId: interaction.guildId,
channelId: interaction.channelId,
creatorId: interaction.user.id,
question,
choices,
endsAt,
});
const poll = getPoll(pollId);
const message = await interaction.channel.send({
embeds: [buildPollEmbed(poll, [])],
components: buildPollComponents(poll),
});
attachPollMessage(pollId, message.id);
logEvent({
guildId: interaction.guildId,
type: 'poll.created',
actorId: interaction.user.id,
payload: { pollId, choices: choices.length },
});
return pollId;
}
async function fetchPollMessage(interaction, poll) {
if (!poll.message_id) return null;
return interaction.channel.messages.fetch(poll.message_id).catch(() => null);
}
/** Closes a poll and freezes its results (M10-T05). */
export async function closePollById(client, pollId) {
const poll = getPoll(pollId);
if (!poll) throw new UserFacingError(`Le sondage **#${pollId}** n’existe pas.`);
if (poll.status === 'closed') throw new UserFacingError(`Le sondage **#${pollId}** est déjà fermé.`);
closePoll(pollId);
const closed = { ...poll, status: 'closed' };
const channel = await client.channels.fetch(poll.channel_id).catch(() => null);
const message = channel?.isSendable()
? await channel.messages.fetch(poll.message_id).catch(() => null)
: null;
await message?.edit({ embeds: [buildPollEmbed(closed)], components: [] });
logEvent({
guildId: poll.guild_id,
type: 'poll.closed',
payload: { pollId },
});
return closed;
}
/** Registers a vote and refreshes the poll message (M10-T03 / M10-T04). */
export async function handlePollComponent(interaction) {
const [, rawId, rawIndex] = interaction.customId.split(':');
const poll = getPoll(Number(rawId));
if (!poll || poll.status !== 'open') {
throw new UserFacingError('Ce sondage est fermé.');
}
const choices = JSON.parse(poll.choices);
const index = Number(rawIndex);
if (!Number.isInteger(index) || index < 0 || index >= choices.length) {
throw new UserFacingError('Choix inconnu.');
}
const result = castVote(poll.id, interaction.user.id, index);
if (result === 'unchanged') {
await interaction.reply({
content: `Tu as déjà voté pour **${choices[index]}**.`,
flags: MessageFlags.Ephemeral,
});
return;
}
const message = await fetchPollMessage(interaction, poll);
await message?.edit({ embeds: [buildPollEmbed(poll)], components: buildPollComponents(poll) });
await interaction.reply({
content:
result === 'changed'
? `Ton vote a été changé pour **${choices[index]}**.`
: `Vote enregistré pour **${choices[index]}**.`,
flags: MessageFlags.Ephemeral,
});
}
/** Polls expire on their own even without activity (M10-T05). */
export function startPollScheduler(client) {
const timer = setInterval(async () => {
let due = [];
try {
due = listDuePolls();
} catch (error) {
log.warn('Could not read the polls to close', error);
return;
}
for (const poll of due) {
try {
await closePollById(client, poll.id);
log.info(`Closed poll #${poll.id} at its end date`);
} catch (error) {
log.error(`Could not close poll #${poll.id}`, error);
}
}
}, SCHEDULER_INTERVAL_MS);
timer.unref();
return timer;
}
+277
View File
@@ -0,0 +1,277 @@
import { ChannelType, PermissionFlagsBits } from 'discord.js';
import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { PermissionDeniedError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { getAccessLevel } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
claimTicket as claimTicketRow,
closeTicket as closeTicketRow,
createTicket as createTicketRow,
getTicketByChannel,
} from '../../database/repositories/ticket-repository.js';
import { ticketButtons } from '../../ui/buttons.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
const log = createLogger('tickets');
/** Ticket scope names to the FWS access level they require. */
const SCOPE_LEVELS = {
staff: ACCESS_LEVELS.STAFF,
dev: ACCESS_LEVELS.DEV,
owner: ACCESS_LEVELS.OWNER,
};
export function findCategory(categoryId) {
return TICKET_CATEGORIES.find((category) => category.id === categoryId) ?? null;
}
/** A member may open a ticket only for a category their access level covers (M6-T02). */
export function canUseCategory(member, category) {
const level = getAccessLevel(member);
return category.scope.some((scope) => level >= SCOPE_LEVELS[scope]);
}
/** Static info about a ticket, used by the embeds below. */
function ticketEmbed(ticket, category) {
const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne';
return baseEmbed(COLORS.ticket)
.setTitle(`Ticket ${category.label} #${ticket.id}`)
.setDescription(
`<@${ticket.author_id}> décris ici ta demande avec le plus de détails possible : ` +
'contexte, étapes de reproduction, messages d’erreur.',
)
.addFields(
{ name: 'Catégorie', value: category.label, inline: true },
{ name: 'Statut', value: ticket.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
{ name: 'Pris en charge par', value: claimed, inline: true },
);
}
function channelName(categoryId, username) {
const slug = username
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 40);
return `ticket-${categoryId}-${slug || 'membre'}`.slice(0, 100);
}
/** Permission overwrites: the author, the staff roles of the scope and the bot (M6-T04). */
function buildOverwrites(guild, client, category, authorId) {
const allow = [
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.SendMessages,
PermissionFlagsBits.ReadMessageHistory,
PermissionFlagsBits.AttachFiles,
];
const overwrites = [
{ id: guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel] },
{ id: authorId, allow },
{ id: client.user.id, allow: [...allow, PermissionFlagsBits.ManageChannels] },
];
for (const scope of category.scope) {
const roleId = env.roles[scope];
if (roleId) overwrites.push({ id: roleId, allow });
}
return overwrites;
}
async function fetchTicketLogChannel(client) {
if (!env.channels.ticketLogs) return null;
const channel = await client.channels.fetch(env.channels.ticketLogs).catch(() => null);
return channel?.isSendable() ? channel : null;
}
async function logTicket(client, embed) {
const channel = await fetchTicketLogChannel(client);
await channel?.send({ embeds: [embed] });
}
/** Opens a private channel for the ticket (M6-T03). */
export async function createTicket(interaction, categoryId) {
const category = findCategory(categoryId);
if (!category) throw new UserFacingError('Catégorie de ticket inconnue.');
if (!canUseCategory(interaction.member, category)) {
throw new UserFacingError(`Tu n’as pas accès à la catégorie **${category.label}**.`);
}
if (!env.channels.ticketCategory) {
throw new UserFacingError('Le salon parent des tickets n’est pas configuré (`CATEGORY_TICKETS_ID`).');
}
const guild = interaction.guild;
const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null);
if (parent?.type !== ChannelType.GuildCategory) {
throw new UserFacingError('`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord.');
}
const channel = await guild.channels.create({
name: channelName(category.id, interaction.user.username),
type: ChannelType.GuildText,
parent: parent.id,
topic: `Ticket ${category.label} — ${interaction.user.tag}`,
permissionOverwrites: buildOverwrites(guild, interaction.client, category, interaction.user.id),
reason: `Ticket ${category.label} ouvert par ${interaction.user.tag}`,
});
let ticket;
try {
ticket = {
id: createTicketRow({
guildId: guild.id,
channelId: channel.id,
categoryId: category.id,
authorId: interaction.user.id,
}),
guild_id: guild.id,
channel_id: channel.id,
category_id: category.id,
author_id: interaction.user.id,
claimed_by: null,
status: 'open',
};
} catch (error) {
// The unique index rejects a second open ticket for the same author and category.
await channel.delete('Ticket en doublon').catch(() => {});
log.warn('Duplicate ticket rejected', error);
throw new UserFacingError('Tu as déjà un ticket ouvert dans cette catégorie.');
}
await channel.send({
content: `<@${ticket.author_id}>`,
embeds: [ticketEmbed(ticket, category)],
components: ticketButtons(),
});
logEvent({
guildId: guild.id,
type: 'ticket.created',
actorId: ticket.author_id,
payload: { ticketId: ticket.id, categoryId: category.id },
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('Ticket ouvert')
.setDescription(`<#${channel.id}> — ${category.label}`)
.addFields({ name: 'Auteur', value: `<@${ticket.author_id}>`, inline: true }),
);
return channel;
}
/** Resolves the ticket of the current channel, or throws a user facing error. */
export async function getChannelTicket(interaction) {
const ticket = getTicketByChannel(interaction.channelId);
if (!ticket) {
throw new UserFacingError('Cette action doit être lancée depuis un salon de ticket.');
}
if (ticket.status !== 'open') {
throw new UserFacingError('Ce ticket est déjà fermé.');
}
return ticket;
}
export async function claimTicket(interaction) {
const ticket = await getChannelTicket(interaction);
if (ticket.claimed_by === interaction.user.id) {
throw new UserFacingError('Tu as déjà pris ce ticket en charge.');
}
claimTicketRow(ticket.id, interaction.user.id);
logEvent({
guildId: ticket.guild_id,
type: 'ticket.claimed',
actorId: interaction.user.id,
payload: { ticketId: ticket.id },
});
await interaction.reply({
embeds: [successEmbed(`<@${interaction.user.id}> prend ce ticket en charge.`)],
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('Ticket pris en charge')
.setDescription(`#${ticket.id} — <#${ticket.channel_id}>`)
.addFields({ name: 'Staff', value: `<@${interaction.user.id}>`, inline: true }),
);
}
/** Closes the ticket: the author or any staff member may do it (M6-T06 / M6-T07). */
export async function closeTicket(interaction, reason = null) {
const ticket = await getChannelTicket(interaction);
const isStaff = getAccessLevel(interaction.member) >= ACCESS_LEVELS.STAFF;
if (interaction.user.id !== ticket.author_id && !isStaff) {
throw new PermissionDeniedError('Seul l’auteur du ticket ou le staff peut le fermer.');
}
closeTicketRow(ticket.id, { closedBy: interaction.user.id, reason });
logEvent({
guildId: ticket.guild_id,
type: 'ticket.closed',
actorId: interaction.user.id,
payload: { ticketId: ticket.id, reason },
});
await interaction.reply({
embeds: [
successEmbed(`Ticket fermé par <@${interaction.user.id}>. Le salon sera supprimé dans 10 secondes.`),
],
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('Ticket fermé')
.setDescription(`#${ticket.id} — ${findCategory(ticket.category_id)?.label ?? ticket.category_id}`)
.addFields(
{ name: 'Auteur', value: `<@${ticket.author_id}>`, inline: true },
{ name: 'Fermé par', value: `<@${interaction.user.id}>`, inline: true },
{ name: 'Raison', value: reason || 'Non précisée' },
),
);
const channel = interaction.channel;
setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref();
}
/** Grants a staff member access to the ticket channel (M6-T07). */
export async function addParticipant(interaction, userId) {
const ticket = await getChannelTicket(interaction);
if (userId === ticket.author_id || userId === ticket.claimed_by) {
throw new UserFacingError('Ce membre participe déjà au ticket.');
}
await interaction.channel.permissionOverwrites.edit(userId, {
ViewChannel: true,
SendMessages: true,
ReadMessageHistory: true,
});
logEvent({
guildId: ticket.guild_id,
type: 'ticket.participant.added',
actorId: interaction.user.id,
payload: { ticketId: ticket.id, userId },
});
await interaction.reply({ embeds: [successEmbed(`<@${userId}> a été ajouté au ticket.`)] });
}
/** Routes the buttons posted in ticket channels. */
export async function handleTicketComponent(interaction) {
switch (interaction.customId) {
case 'ticket:claim':
await claimTicket(interaction);
return;
case 'ticket:close':
await closeTicket(interaction);
return;
default:
log.debug(`Ignored unknown ticket component ${interaction.customId}`);
}
}
+715
View File
@@ -0,0 +1,715 @@
import {
ActionRowBuilder,
ChannelType,
MessageFlags,
ModalBuilder,
PermissionFlagsBits,
TextInputBuilder,
TextInputStyle,
} from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { PermissionDeniedError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { getAccessLevel } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { resolveSetting, setSetting } from '../../database/repositories/settings-repository.js';
import {
addVoiceChannel,
countVoiceChannels,
getVoiceChannel,
listOwnedVoiceChannels,
listVoiceChannels,
removeVoiceChannel,
setVoiceLimit,
setVoiceLocked,
setVoiceName,
setVoiceOwner,
} from '../../database/repositories/voice-repository.js';
import { voicePanelComponents } from '../../ui/buttons.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
const log = createLogger('voice');
export const DEFAULT_TEMPLATE = '🔊 Salon de {user}';
/** Discord caps the user limit of a voice channel at 99 (0 means unlimited). */
export const LIMIT_MAX = 99;
export const NAME_MAX = 100;
/** Delay before an empty temporary channel is deleted, so a quick move does not destroy it. */
const EMPTY_GRACE_MS = 5_000;
/** Creation in flight per member, to never create two channels for the same person (M14-T02). */
const pendingCreations = new Set();
/** Channel id -> panel message id, so buttons can be refreshed after a change (M14-T05). */
const panelMessages = new Map();
const VIEW = PermissionFlagsBits.ViewChannel;
const CONNECT = PermissionFlagsBits.Connect;
const SPEAK = PermissionFlagsBits.Speak;
const MEMBER_ALLOW = [VIEW, CONNECT, SPEAK];
const OWNER_ALLOW = [...MEMBER_ALLOW, PermissionFlagsBits.ManageChannels, PermissionFlagsBits.MoveMembers];
/** Named form required by `permissionOverwrites.edit()` (permission bits are not keys). */
const OWNER_OVERWRITE = Object.freeze({
ViewChannel: true,
Connect: true,
Speak: true,
ManageChannels: true,
MoveMembers: true,
});
/** Strips control characters without a control-character regex, then collapses spaces. */
const clean = (value) =>
[...String(value ?? '')]
.map((char) => {
const code = char.codePointAt(0);
return code <= 31 || code === 127 ? ' ' : char;
})
.join('')
.replace(/\s+/g, ' ')
.trim();
/** Channel names are normalised and truncated before they reach Discord (M14-T08). */
export function sanitizeChannelName(value) {
const name = clean(value);
if (!name) throw new UserFacingError('Le nom du salon ne peut pas être vide.');
return name.slice(0, NAME_MAX);
}
/** `🔊 Salon de {user}` -> the name of the channel created for a member. */
export function buildChannelName(template, member) {
const replaced = String(template || DEFAULT_TEMPLATE).replaceAll(
'{user}',
member.displayName ?? member.user?.username ?? '',
);
return clean(replaced).slice(0, NAME_MAX) || '🔊 Salon vocal';
}
/** `0` means unlimited; anything outside 0..99 is rejected or ignored (M14-T06). */
export function clampLimit(value, { strict = false } = {}) {
const limit = Number(value);
if (!Number.isInteger(limit) || limit < 0 || limit > LIMIT_MAX) {
if (strict) {
throw new UserFacingError(`La limite doit être un entier entre 0 (illimité) et ${LIMIT_MAX}.`);
}
return 0;
}
return limit;
}
/** Per-guild voice configuration, falling back to the environment (M14-T01). */
export function getVoiceSettings(guildId) {
return {
triggerId: resolveSetting(guildId, 'voice.trigger', env.channels.voiceTrigger),
categoryId: resolveSetting(guildId, 'voice.category', env.channels.voiceCategory),
template: resolveSetting(guildId, 'voice.template', DEFAULT_TEMPLATE) || DEFAULT_TEMPLATE,
defaultLimit: clampLimit(resolveSetting(guildId, 'voice.limit', 0)),
};
}
export function saveVoiceSettings(guildId, patch, updatedBy = null) {
const keys = {
trigger: 'voice.trigger',
category: 'voice.category',
template: 'voice.template',
limit: 'voice.limit',
};
for (const [name, key] of Object.entries(keys)) {
if (patch[name] !== undefined) setSetting(guildId, key, patch[name], updatedBy);
}
}
export function isStaff(member, roles = env.roles) {
return getAccessLevel(member, roles) >= ACCESS_LEVELS.STAFF;
}
export function isManagedChannel(channelId) {
return Boolean(getVoiceChannel(channelId));
}
/** Embed shown in the panel and by `/voice info` (M14-T05). */
export function voicePanelEmbed(channel, row) {
const ownerId = row?.owner_id ?? null;
return baseEmbed(COLORS.primary)
.setTitle(`Gestion de ${channel.name}`)
.setDescription(
'Les boutons ci-dessous agissent sur ce salon uniquement. Les commandes `/voice` offrent les mêmes options.',
)
.addFields(
{ name: 'Propriétaire', value: ownerId ? `<@${ownerId}>` : 'Personne', inline: true },
{ name: 'Statut', value: row?.locked ? '🔒 Verrouillé' : '🔓 Ouvert', inline: true },
{ name: 'Limite', value: row?.user_limit ? `${row.user_limit} places` : 'Illimitée', inline: true },
{
name: 'Membres',
value: row?.user_limit ? `${channel.members.size} / ${row.user_limit}` : String(channel.members.size),
inline: true,
},
);
}
export function voiceInfoEmbed(channel, row) {
const embed = baseEmbed(COLORS.primary)
.setTitle(channel.name)
.addFields(
{ name: 'Propriétaire', value: row?.owner_id ? `<@${row.owner_id}>` : 'Personne', inline: true },
{ name: 'Statut', value: row?.locked ? '🔒 Verrouillé' : '🔓 Ouvert', inline: true },
{ name: 'Limite', value: row?.user_limit ? `${row.user_limit} places` : 'Illimitée', inline: true },
{
name: 'Membres',
value:
channel.members.size === 0
? 'Aucun'
: channel.members
.first(10)
.map((member) => `<@${member.id}>`)
.join(', '),
},
)
.addFields({ name: 'Créé', value: `<t:${Math.floor(channel.createdTimestamp / 1000)}:R>`, inline: true });
if (row?.trigger_id) embed.setFooter({ text: `Salon temporaire · déclencheur ${row.trigger_id}` });
return embed;
}
/** Posts the control panel in the text chat of the voice channel (M14-T05). */
async function postPanel(channel, row) {
if (!channel.isSendable?.()) return;
const message = await channel
.send({
embeds: [voicePanelEmbed(channel, row)],
components: voicePanelComponents({ locked: Boolean(row.locked) }),
})
.catch((error) => {
log.warn('Could not post the voice panel', error);
return null;
});
if (message) panelMessages.set(channel.id, message.id);
}
/** Refreshes the panel buttons after a change, best effort (M14-T05). */
export async function refreshPanel(channel) {
const messageId = panelMessages.get(channel.id);
const row = getVoiceChannel(channel.id);
if (!messageId || !row || !channel.isSendable?.()) return;
const message = await channel.messages.fetch(messageId).catch(() => null);
await message
?.edit({
embeds: [voicePanelEmbed(channel, row)],
components: voicePanelComponents({ locked: Boolean(row.locked) }),
})
.catch(() => {});
}
async function findReusableChannel(guild, ownerId) {
for (const row of listOwnedVoiceChannels(guild.id, ownerId)) {
const channel = guild.channels.cache.get(row.channel_id);
if (!channel) {
removeVoiceChannel(row.channel_id);
panelMessages.delete(row.channel_id);
continue;
}
const full = channel.userLimit > 0 && channel.members.size >= channel.userLimit;
if (!full) return { channel, row };
}
return null;
}
function buildOverwrites(guild, client, ownerId) {
return [
{ id: guild.roles.everyone.id, allow: MEMBER_ALLOW },
{ id: ownerId, allow: OWNER_ALLOW },
{ id: client.user.id, allow: OWNER_ALLOW },
];
}
/**
* Called when a member joins the trigger channel: creates their channel (or moves them
* back into the one they already own) and hands it over (M14-T02 / M14-T03).
*/
export async function createFromTrigger(member) {
const settings = getVoiceSettings(member.guild.id);
if (!settings.triggerId || pendingCreations.has(member.id)) return null;
const reusable = await findReusableChannel(member.guild, member.id);
if (reusable) {
await member.voice
.setChannel(reusable.channel, 'Retour dans son salon vocal temporaire')
.catch((error) => log.warn('Could not move the member back into their channel', error));
return reusable.channel;
}
pendingCreations.add(member.id);
try {
const parent = settings.categoryId
? await member.guild.channels.fetch(settings.categoryId).catch(() => null)
: null;
const channel = await member.guild.channels.create({
name: buildChannelName(settings.template, member),
type: ChannelType.GuildVoice,
userLimit: settings.defaultLimit,
...(parent?.type === ChannelType.GuildCategory && { parent: parent.id }),
reason: `Salon vocal temporaire de ${member.user.tag}`,
permissionOverwrites: buildOverwrites(member.guild, member.client, member.id),
});
addVoiceChannel({
channelId: channel.id,
guildId: member.guild.id,
ownerId: member.id,
triggerId: settings.triggerId,
name: channel.name,
userLimit: settings.defaultLimit,
});
await member.voice
.setChannel(channel, 'Salon vocal temporaire créé')
.catch((error) => log.warn('Could not move the member into their new channel', error));
await postPanel(channel, getVoiceChannel(channel.id));
logEvent({
guildId: member.guild.id,
type: 'voice.created',
actorId: member.id,
payload: { channelId: channel.id, ownerId: member.id },
});
return channel;
} finally {
pendingCreations.delete(member.id);
}
}
/** Deletes a temporary channel and forgets it. */
export async function deleteVoiceChannel(channel, reason = 'Salon vocal temporaire supprimé') {
removeVoiceChannel(channel.id);
panelMessages.delete(channel.id);
return channel.delete(reason).catch((error) => log.warn('Could not delete the voice channel', error));
}
/**
* Deletes an empty temporary channel after a short grace period, so that a member
* moving between channels does not lose their channel (M14-T04).
*/
export async function cleanupVoiceChannel(guild, channelId) {
const row = getVoiceChannel(channelId);
if (!row) return;
const channel =
guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null));
if (!channel) {
removeVoiceChannel(channelId);
return;
}
if (channel.members.size > 0) return;
setTimeout(async () => {
try {
const fresh =
guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null));
if (!fresh || fresh.members.size > 0) return;
await deleteVoiceChannel(fresh, 'Salon vocal temporaire vide').catch(() => {});
logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId } });
} catch (error) {
log.warn('Could not clean up an empty voice channel', error);
}
}, EMPTY_GRACE_MS).unref();
}
/** Startup sweep: forget deleted channels, remove the ones left empty by a restart (M14-T07). */
export async function sweepVoiceChannels(client) {
for (const guild of client.guilds.cache.values()) {
let rows = [];
try {
rows = listVoiceChannels(guild.id);
} catch (error) {
log.warn('Could not read the stored voice channels', error);
continue;
}
for (const row of rows) {
const channel =
guild.channels.cache.get(row.channel_id) ??
(await guild.channels.fetch(row.channel_id).catch(() => null));
if (!channel) {
removeVoiceChannel(row.channel_id);
panelMessages.delete(row.channel_id);
continue;
}
if (channel.members.size === 0) {
await deleteVoiceChannel(channel, 'Salon vocal temporaire vide après redémarrage');
}
}
}
}
export function activeChannelCount(guildId) {
return countVoiceChannels(guildId);
}
/** Channel of the interaction itself, when it is a temporary voice channel (panel buttons and modals). */
function managedChannelOf(interaction) {
return interaction.channelId && isManagedChannel(interaction.channelId) ? interaction.channelId : null;
}
/**
* Resolves the temporary channel an action applies to: the explicit option first, then the
* channel the interaction happened in (panel, modal), then the voice channel of the caller (M14-T05).
*/
export async function resolveManagedChannel(interaction, { channelId = null } = {}) {
const id = channelId ?? managedChannelOf(interaction) ?? interaction.member?.voice?.channelId ?? null;
const row = id ? getVoiceChannel(id) : null;
if (!row) {
throw new UserFacingError(
'Rejoins ton salon vocal temporaire pour le gérer, ou précise l’option `channel`.',
);
}
if (channelId && channelId !== interaction.member?.voice?.channelId && !isStaff(interaction.member)) {
// An explicit channel is a staff convenience only: a member manages their own channel.
throw new PermissionDeniedError('Seul le staff peut cibler le salon d’un autre membre.');
}
const channel = await interaction.guild.channels.fetch(row.channel_id).catch(() => null);
if (!channel) {
removeVoiceChannel(row.channel_id);
throw new UserFacingError('Ce salon vocal n’existe plus.');
}
return { channel, row };
}
/** Only the owner may manage a channel; staff can always step in (M14-T06). */
export function assertVoiceOwner(interaction, row, action = 'gérer ce salon') {
if (row.owner_id === interaction.user.id || isStaff(interaction.member)) return;
throw new PermissionDeniedError(`Seul le propriétaire du salon (ou le staff) peut ${action}.`);
}
const ephemeral = (payload) => ({ ...payload, flags: MessageFlags.Ephemeral });
export async function renameChannel(interaction, name) {
const { channel, row } = await resolveManagedChannel(interaction);
assertVoiceOwner(interaction, row, 'renommer le salon');
const sanitized = sanitizeChannelName(name);
await channel.setName(sanitized, `Renommé par ${interaction.user.tag}`);
setVoiceName(channel.id, sanitized);
await refreshPanel(channel);
await interaction.reply(ephemeral({ embeds: [successEmbed(`Salon renommé en **${sanitized}**.`)] }));
}
export async function setChannelLimit(interaction, limit) {
const { channel, row } = await resolveManagedChannel(interaction);
assertVoiceOwner(interaction, row, 'changer la limite');
const value = clampLimit(limit, { strict: true });
await channel.setUserLimit(value, `Limite modifiée par ${interaction.user.tag}`);
setVoiceLimit(channel.id, value);
await refreshPanel(channel);
await interaction.reply(
ephemeral({
embeds: [
successEmbed(
value === 0 ? 'Le salon redevient **sans limite** de places.' : `Limite : **${value} places**.`,
),
],
}),
);
}
export async function toggleLock(interaction, { locked = null } = {}) {
const { channel, row } = await resolveManagedChannel(interaction);
assertVoiceOwner(interaction, row, 'verrouiller le salon');
const next = locked === null ? !row.locked : Boolean(locked);
if (next === Boolean(row.locked)) {
throw new UserFacingError(next ? 'Le salon est déjà verrouillé.' : 'Le salon est déjà déverrouillé.');
}
await channel.permissionOverwrites.edit(
interaction.guild.roles.everyone.id,
{ Connect: next ? false : null },
{ reason: `${next ? 'Verrouillé' : 'Déverrouillé'} par ${interaction.user.tag}` },
);
setVoiceLocked(channel.id, next);
await refreshPanel(channel);
await interaction.reply(
ephemeral({
embeds: [
successEmbed(
next
? '🔒 Salon verrouillé : seuls les membres autorisés peuvent le rejoindre.'
: '🔓 Salon déverrouillé : tout le monde peut rejoindre.',
),
],
}),
);
}
export async function permitUser(interaction, userId) {
const { channel, row } = await resolveManagedChannel(interaction);
assertVoiceOwner(interaction, row, 'autoriser un membre');
await channel.permissionOverwrites.edit(
userId,
{ ViewChannel: true, Connect: true },
{
reason: `Autorisé par ${interaction.user.tag}`,
},
);
await interaction.reply(ephemeral({ embeds: [successEmbed(`<@${userId}> peut rejoindre le salon.`)] }));
}
export async function rejectUser(interaction, userId) {
const { channel, row } = await resolveManagedChannel(interaction);
assertVoiceOwner(interaction, row, 'refuser un membre');
await channel.permissionOverwrites.edit(
userId,
{ ViewChannel: false, Connect: false },
{
reason: `Refusé par ${interaction.user.tag}`,
},
);
const member = channel.members.get(userId);
await member?.voice.disconnect(`Refusé par ${interaction.user.tag}`).catch(() => {});
await interaction.reply(
ephemeral({ embeds: [successEmbed(`<@${userId}> ne peut plus rejoindre le salon.`)] }),
);
}
export async function kickUser(interaction, userId) {
const { channel, row } = await resolveManagedChannel(interaction);
assertVoiceOwner(interaction, row, 'exclure un membre');
const member = channel.members.get(userId);
if (!member) throw new UserFacingError('Ce membre n’est pas dans le salon.');
if (member.id === row.owner_id) throw new UserFacingError('Le propriétaire ne peut pas être exclu.');
await member.voice.disconnect(`Exclu par ${interaction.user.tag}`);
await interaction.reply(ephemeral({ embeds: [successEmbed(`<@${userId}> a été exclu du salon.`)] }));
}
export async function transferOwnership(interaction, userId) {
const { channel, row } = await resolveManagedChannel(interaction);
assertVoiceOwner(interaction, row, 'transférer le salon');
const member = channel.members.get(userId);
if (!member) throw new UserFacingError('Le nouveau propriétaire doit déjà être dans le salon.');
if (member.id === row.owner_id) throw new UserFacingError('Ce membre est déjà propriétaire du salon.');
await channel.permissionOverwrites
.edit(row.owner_id, { ManageChannels: null, MoveMembers: null }, { reason: 'Nouveau propriétaire' })
.catch(() => {});
await channel.permissionOverwrites.edit(member.id, OWNER_OVERWRITE, {
reason: `Salon transféré par ${interaction.user.tag}`,
});
setVoiceOwner(channel.id, member.id);
await refreshPanel(channel);
logEvent({
guildId: interaction.guildId,
type: 'voice.transferred',
actorId: interaction.user.id,
payload: { channelId: channel.id, ownerId: member.id },
});
await interaction.reply(
ephemeral({
embeds: [successEmbed(`<@${member.id}> est désormais propriétaire de **${channel.name}**.`)],
}),
);
}
/** A member may take over a channel whose owner is gone (M14-T03). */
export async function claimOwnership(interaction) {
const { channel, row } = await resolveManagedChannel(interaction);
if (row.owner_id === interaction.user.id) {
throw new UserFacingError('Tu es déjà propriétaire de ce salon.');
}
if (channel.members.has(row.owner_id)) {
throw new UserFacingError('Le propriétaire est toujours dans le salon.');
}
if (!channel.members.has(interaction.user.id)) {
throw new UserFacingError('Rejoins d’abord le salon pour en réclamer la propriété.');
}
await channel.permissionOverwrites.edit(interaction.user.id, OWNER_OVERWRITE, {
reason: `Salon réclamé par ${interaction.user.tag}`,
});
setVoiceOwner(channel.id, interaction.user.id);
await refreshPanel(channel);
logEvent({
guildId: interaction.guildId,
type: 'voice.claimed',
actorId: interaction.user.id,
payload: { channelId: channel.id },
});
await interaction.reply(ephemeral({ embeds: [successEmbed('Tu es désormais propriétaire de ce salon.')] }));
}
export async function removeChannel(interaction, { channelId = null } = {}) {
const { channel, row } = await resolveManagedChannel(interaction, { channelId });
assertVoiceOwner(interaction, row, 'supprimer le salon');
await interaction.reply(
ephemeral({ embeds: [successEmbed(`Le salon **${channel.name}** va être supprimé.`)] }),
);
logEvent({
guildId: interaction.guildId,
type: 'voice.deleted',
actorId: interaction.user.id,
payload: { channelId: channel.id },
});
setTimeout(
() => deleteVoiceChannel(channel, `Supprimé par ${interaction.user.tag}`).catch(() => {}),
3_000,
).unref();
}
export async function showInfo(interaction, { channelId = null } = {}) {
const { channel, row } = await resolveManagedChannel(interaction, { channelId });
await interaction.reply(ephemeral({ embeds: [voiceInfoEmbed(channel, row)] }));
}
/** Posts the "join to create" panel in the trigger channel (M14-T01). */
export async function postSetupPanel(interaction) {
const settings = getVoiceSettings(interaction.guildId);
if (!settings.triggerId) {
throw new UserFacingError('Aucun salon vocal déclencheur n’est configuré : lance `/voice setup`.');
}
const trigger = await interaction.guild.channels.fetch(settings.triggerId).catch(() => null);
if (!trigger?.isVoiceBased?.()) {
throw new UserFacingError('Le salon déclencheur configuré n’est pas un salon vocal.');
}
const embed = baseEmbed(COLORS.primary)
.setTitle('🎧 Salons vocaux temporaires')
.setDescription(
`Rejoins ${trigger} pour obtenir ton propre salon vocal.\n\n` +
'Tu en deviens le propriétaire : renomme-le, limite le nombre de places, verrouille-le, ' +
'autorise ou exclus des membres, ou transfère-le — depuis les boutons du salon ou les commandes `/voice`.',
)
.addFields({ name: 'Limite par défaut', value: settings.defaultLimit || 'Illimitée', inline: true });
if (!trigger.isSendable()) {
throw new UserFacingError('Je n’ai pas la permission d’écrire dans le salon déclencheur.');
}
await trigger.send({ embeds: [embed] });
await interaction.reply(ephemeral({ embeds: [successEmbed('Panneau publié dans le salon déclencheur.')] }));
}
/** Button and select menu routing (M14-T05). */
export async function handleVoiceComponent(interaction) {
const action = interaction.customId.split(':')[1];
if (interaction.isUserSelectMenu()) {
const userId = interaction.values[0];
switch (action) {
case 'permit':
await permitUser(interaction, userId);
return;
case 'kick':
await kickUser(interaction, userId);
return;
case 'transfer':
await transferOwnership(interaction, userId);
return;
default:
log.debug(`Ignored voice select ${interaction.customId}`);
return;
}
}
switch (action) {
case 'rename':
await openRenameModal(interaction);
return;
case 'limit':
await openLimitModal(interaction);
return;
case 'lock':
await toggleLock(interaction);
return;
case 'claim':
await claimOwnership(interaction);
return;
case 'info':
await showInfo(interaction);
return;
case 'delete':
await removeChannel(interaction);
return;
default:
log.debug(`Ignored voice component ${interaction.customId}`);
}
}
async function openRenameModal(interaction) {
const { channel, row } = await resolveManagedChannel(interaction);
assertVoiceOwner(interaction, row, 'renommer le salon');
await interaction.showModal(
new ModalBuilder()
.setCustomId('voice:rename:modal')
.setTitle('Renommer le salon')
.addComponents(
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('name')
.setLabel('Nouveau nom')
.setStyle(TextInputStyle.Short)
.setMaxLength(NAME_MAX)
.setValue(channel.name.slice(0, NAME_MAX))
.setRequired(true),
),
),
);
}
async function openLimitModal(interaction) {
const { row } = await resolveManagedChannel(interaction);
assertVoiceOwner(interaction, row, 'changer la limite');
await interaction.showModal(
new ModalBuilder()
.setCustomId('voice:limit:modal')
.setTitle('Limite de places')
.addComponents(
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId('limit')
.setLabel(`Entre 0 (illimité) et ${LIMIT_MAX}`)
.setStyle(TextInputStyle.Short)
.setMaxLength(2)
.setValue(String(row.user_limit ?? 0))
.setRequired(true),
),
),
);
}
/** Modal submissions opened from the panel (M14-T05). */
export async function handleVoiceModal(interaction) {
if (interaction.customId === 'voice:rename:modal') {
await renameChannel(interaction, interaction.fields.getTextInputValue('name'));
return;
}
if (interaction.customId === 'voice:limit:modal') {
const raw = interaction.fields.getTextInputValue('limit').trim();
const limit = Number.parseInt(raw, 10);
if (!/^\d{1,2}$/.test(raw)) {
throw new UserFacingError(`Indique un nombre entier entre 0 (illimité) et ${LIMIT_MAX}.`);
}
await setChannelLimit(interaction, limit);
return;
}
log.debug(`Ignored voice modal ${interaction.customId}`);
}
+89 -1
View File
@@ -1,4 +1,12 @@
import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js'; import { ActionRowBuilder, ButtonBuilder, ButtonStyle, UserSelectMenuBuilder } from 'discord.js';
/** Discord label and custom id limits. */
const LABEL_MAX = 80;
export const POLL_CHOICES_MAX = 10;
function truncate(text, max) {
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
}
/** Builds a row of link buttons, skipping links without a URL (M12-T03). */ /** Builds a row of link buttons, skipping links without a URL (M12-T03). */
export function linkButtons(links) { export function linkButtons(links) {
@@ -9,3 +17,83 @@ export function linkButtons(links) {
return buttons.length > 0 ? [new ActionRowBuilder().addComponents(buttons)] : []; return buttons.length > 0 ? [new ActionRowBuilder().addComponents(buttons)] : [];
} }
/** Claim / close controls posted in a ticket channel (M6-T05 / M6-T06). */
export function ticketButtons() {
return [
new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('ticket:claim')
.setLabel('Prendre en charge')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder().setCustomId('ticket:close').setLabel('Fermer').setStyle(ButtonStyle.Danger),
),
];
}
/**
* Control panel posted in a temporary voice channel (M14-T05):
* buttons for the whole channel, select menus for a specific member.
*/
export function voicePanelComponents({ locked = false } = {}) {
return [
new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('voice:rename')
.setLabel('Renommer')
.setEmoji('✏️')
.setStyle(ButtonStyle.Secondary),
new ButtonBuilder()
.setCustomId('voice:limit')
.setLabel('Limiter')
.setEmoji('👥')
.setStyle(ButtonStyle.Secondary),
new ButtonBuilder()
.setCustomId('voice:lock')
.setLabel(locked ? 'Déverrouiller' : 'Verrouiller')
.setEmoji(locked ? '🔓' : '🔒')
.setStyle(locked ? ButtonStyle.Success : ButtonStyle.Secondary),
new ButtonBuilder()
.setCustomId('voice:claim')
.setLabel('Réclamer')
.setEmoji('👑')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('voice:delete')
.setLabel('Supprimer')
.setEmoji('🗑️')
.setStyle(ButtonStyle.Danger),
),
memberSelect('voice:permit', 'Autoriser un membre à rejoindre...'),
memberSelect('voice:kick', 'Exclure un membre du salon...'),
memberSelect('voice:transfer', 'Transférer la propriété du salon...'),
];
}
function memberSelect(customId, placeholder) {
return new ActionRowBuilder().addComponents(
new UserSelectMenuBuilder()
.setCustomId(customId)
.setPlaceholder(placeholder)
.setMinValues(1)
.setMaxValues(1),
);
}
/** One button per choice, 5 per row at most (M10-T02). */
export function pollButtons(pollId, choices) {
const rows = [];
for (let start = 0; start < Math.min(choices.length, POLL_CHOICES_MAX); start += 5) {
rows.push(
new ActionRowBuilder().addComponents(
choices.slice(start, start + 5).map((choice, offset) =>
new ButtonBuilder()
.setCustomId(`poll:${pollId}:${start + offset}`)
.setLabel(truncate(choice, LABEL_MAX))
.setStyle(ButtonStyle.Secondary),
),
),
);
}
return rows;
}
-6
View File
@@ -17,9 +17,3 @@ export function successEmbed(description) {
export function errorEmbed(description) { export function errorEmbed(description) {
return baseEmbed(COLORS.error).setTitle('Erreur').setDescription(description); return baseEmbed(COLORS.error).setTitle('Erreur').setDescription(description);
} }
export function notImplementedEmbed(feature) {
return baseEmbed(COLORS.warning)
.setTitle('Bientôt disponible')
.setDescription(`La fonctionnalité **${feature}** n'est pas encore implémentée.`);
}
+34 -5
View File
@@ -2,6 +2,9 @@ import { createHmac, timingSafeEqual } from 'node:crypto';
import { env } from '../config/env.js'; import { env } from '../config/env.js';
import { createLogger } from '../core/logger.js'; import { createLogger } from '../core/logger.js';
import { getDatabase } from '../database/index.js'; import { getDatabase } from '../database/index.js';
import { logEvent } from '../database/repositories/event-log-repository.js';
import { buildGiteaNotification } from '../services/notifications/gitea-notifications.js';
import { notify } from '../services/notifications/notification-service.js';
const log = createLogger('webhooks'); const log = createLogger('webhooks');
@@ -20,8 +23,8 @@ function markDelivered(deliveryId, event) {
return result.changes > 0; return result.changes > 0;
} }
/** Validates and dispatches a Gitea webhook. Returns the HTTP status code. */ /** Validates, deduplicates and publishes a Gitea webhook. Returns the HTTP status code. */
export async function handleGiteaWebhook(_client, headers, rawBody) { export async function handleGiteaWebhook(client, headers, rawBody) {
if (!isValidSignature(rawBody, headers['x-gitea-signature'])) { if (!isValidSignature(rawBody, headers['x-gitea-signature'])) {
log.warn('Rejected webhook with invalid signature'); log.warn('Rejected webhook with invalid signature');
return 401; return 401;
@@ -32,9 +35,35 @@ export async function handleGiteaWebhook(_client, headers, rawBody) {
if (!event || !deliveryId) return 400; if (!event || !deliveryId) return 400;
if (!markDelivered(deliveryId, event)) return 200; if (!markDelivered(deliveryId, event)) return 200;
const payload = JSON.parse(rawBody.toString('utf8')); let payload;
log.info(`Received Gitea event ${event}`, { deliveryId, repository: payload.repository?.full_name }); try {
payload = JSON.parse(rawBody.toString('utf8'));
} catch {
log.warn('Rejected webhook with invalid JSON body', { deliveryId, event });
return 400;
}
log.info(`Received Gitea event ${event}`, {
deliveryId,
repository: payload.repository?.full_name,
});
const notification = buildGiteaNotification(event, payload);
if (!notification) {
log.debug(`No notification mapping for Gitea event ${event}`);
return 202;
}
logEvent({
guildId: env.discord.guildId || null,
type: `gitea.${event}`,
payload: { deliveryId, type: notification.type },
});
await notify(client, notification.type, {
embeds: [notification.embed],
content: payload.repository?.full_name ? `**${payload.repository.full_name}**` : undefined,
}).catch((error) => log.error('Could not publish the Gitea notification', error));
// TODO(M9-T03..T07): filter events and publish embeds through notification-service.
return 202; return 202;
} }
+76
View File
@@ -0,0 +1,76 @@
import assert from 'node:assert/strict';
import { createHmac } from 'node:crypto';
import { readdir } from 'node:fs/promises';
import { describe, it } from 'node:test';
import { ACCESS_LEVELS } from '../src/config/constants.js';
import { loadCommands } from '../src/core/command-loader.js';
const eventsDir = new URL('../src/events/', import.meta.url);
describe('command modules', () => {
it('exposes data, a valid access level and an execute function', async () => {
const commands = await loadCommands();
assert.ok(commands.length >= 16, `only ${commands.length} commands loaded`);
for (const command of commands) {
const json = command.data.toJSON();
assert.ok(json.name, 'a command has no name');
assert.ok(json.description, `/${json.name} has no description`);
assert.equal(typeof command.execute, 'function', `/${json.name} has no execute()`);
assert.ok(
Object.values(ACCESS_LEVELS).includes(command.access),
`/${json.name} has an unknown access level`,
);
}
});
it('uses unique command names', async () => {
const names = (await loadCommands()).map((command) => command.data.name);
assert.equal(new Set(names).size, names.length);
});
it('only overrides the access of declared subcommands', async () => {
for (const command of await loadCommands()) {
if (!command.subcommandAccess) continue;
const subcommands = (command.data.toJSON().options ?? [])
.filter((option) => option.type === 1)
.map((option) => option.name);
for (const name of Object.keys(command.subcommandAccess)) {
assert.ok(subcommands.includes(name), `/${command.data.name} ${name} is not a subcommand`);
}
}
});
});
describe('webhook entry points', () => {
it('exposes the server and the dispatch functions', async () => {
const server = await import('../src/webhooks/server.js');
const webhook = await import('../src/webhooks/gitea-webhook.js');
assert.equal(typeof server.startWebhookServer, 'function');
assert.equal(typeof webhook.handleGiteaWebhook, 'function');
});
it('accepts only a valid HMAC signature and refuses an empty secret', async () => {
const { isValidSignature } = await import('../src/webhooks/gitea-webhook.js');
const body = Buffer.from('{"action":"opened"}');
const signature = createHmac('sha256', 'secret').update(body).digest('hex');
assert.equal(isValidSignature(body, signature, 'secret'), true);
assert.equal(isValidSignature(body, 'deadbeef', 'secret'), false);
assert.equal(isValidSignature(body, signature, ''), false);
assert.equal(isValidSignature(body, undefined, 'secret'), false);
});
});
describe('event modules', () => {
it('exports a name and a handler', async () => {
const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js'));
assert.ok(files.length >= 6, `only ${files.length} event files found`);
for (const file of files) {
const event = await import(new URL(file, eventsDir).href);
assert.equal(typeof event.name, 'string', `${file} has no name`);
assert.equal(typeof event.execute, 'function', `${file} has no execute()`);
}
});
});
+88
View File
@@ -0,0 +1,88 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { buildGiteaNotification } from '../src/services/notifications/gitea-notifications.js';
import { releaseEmbed, truncate } from '../src/services/gitea/gitea-embeds.js';
const issue = {
number: 12,
title: 'Le lecteur ne démarre pas',
body: 'Depuis la mise à jour.',
state: 'open',
comments: 3,
user: { login: 'alice' },
html_url: 'https://gitea.example/FWS/FWS-Arch/issues/12',
labels: [{ name: 'bug' }],
};
describe('buildGiteaNotification', () => {
it('maps an issue event to the issues channel', () => {
const notification = buildGiteaNotification('issues', { issue });
assert.equal(notification.type, 'issues');
assert.equal(notification.embed.data.title, '#12 Le lecteur ne démarre pas');
assert.equal(notification.embed.data.url, issue.html_url);
});
it('maps a pull request to its own type', () => {
const notification = buildGiteaNotification('pull_request', {
pull_request: {
number: 4,
title: 'Corrige le démarrage',
state: 'open',
user: { login: 'bob' },
head: { ref: 'fix/boot' },
base: { ref: 'main' },
},
});
assert.equal(notification.type, 'pull_request');
assert.match(notification.embed.data.fields[2].value, /fix\/boot → main/);
});
it('reports a release with its tag', () => {
const notification = buildGiteaNotification('release', {
release: { tag_name: 'v1.2.0', name: 'Version 1.2.0', body: 'Nouveautés' },
});
assert.equal(notification.type, 'release');
assert.equal(notification.embed.data.title, 'Version 1.2.0');
});
it('ignores a push without commits', () => {
assert.equal(buildGiteaNotification('push', { commits: [], ref: 'refs/heads/main' }), null);
});
it('summarises the commits of a push', () => {
const notification = buildGiteaNotification('push', {
ref: 'refs/heads/main',
sender: { login: 'carol' },
commits: [{ id: 'abcdef1234567', message: 'fix: boot\n\nDétails' }],
});
assert.equal(notification.type, 'push');
assert.equal(notification.embed.data.title, 'Push sur main');
assert.match(notification.embed.data.description, /`abcdef1` fix: boot/);
});
it('ignores events without a notification type', () => {
assert.equal(buildGiteaNotification('repository', { repository: {} }), null);
});
});
describe('releaseEmbed', () => {
it('keeps the notes by default and can drop them', () => {
const release = {
tag_name: 'v2.0.0',
name: 'v2.0.0',
body: 'Changements',
published_at: '2026-01-01T10:00:00Z',
};
assert.equal(releaseEmbed(release).data.description, 'Changements');
assert.equal(releaseEmbed(release, { withNotes: false }).data.description, undefined);
});
});
describe('truncate', () => {
it('keeps short text and cuts long text', () => {
assert.equal(truncate('court'), 'court');
assert.equal(truncate('', 10), '');
assert.equal(truncate('ab'.repeat(20), 10).length, 10);
assert.match(truncate('ab'.repeat(20), 10), /…$/);
});
});
+33
View File
@@ -0,0 +1,33 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { consume, pendingCount, purgeExpired, remember } from '../src/services/gitea/pending-actions.js';
describe('pending actions', () => {
it('returns a stored value exactly once', () => {
remember('pr:1', { head: 'feature', base: 'main' });
assert.deepEqual(consume('pr:1'), { head: 'feature', base: 'main' });
assert.equal(consume('pr:1'), null);
});
it('returns null for an unknown key', () => {
assert.equal(consume('pr:unknown'), null);
});
it('drops an expired entry', () => {
const start = 1_000;
remember('pr:2', 'value', { ttlMs: 500, now: start });
assert.equal(consume('pr:2', { now: start + 501 }), null);
});
it('keeps a value still within its window', () => {
remember('pr:3', 'value', { ttlMs: 500, now: 0 });
assert.equal(consume('pr:3', { now: 499 }), 'value');
});
it('purges expired entries without touching fresh ones', () => {
remember('pr:4', 'old', { ttlMs: 10, now: 0 });
remember('pr:5', 'fresh', { ttlMs: 10_000, now: 0 });
assert.equal(purgeExpired(100), 1);
assert.equal(pendingCount(), 1);
});
});
+80
View File
@@ -0,0 +1,80 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { formatDuration } from '../src/services/moderation/moderation-service.js';
import { buildPollEmbed, parseChoices, toSqliteDate } from '../src/services/polls/poll-service.js';
describe('parseChoices', () => {
it('splits, trims and keeps the order', () => {
assert.deepEqual(parseChoices('Oui ; Non; Peut-être '), ['Oui', 'Non', 'Peut-être']);
});
it('rejects a single choice', () => {
assert.throws(() => parseChoices('Oui'), /entre 2 et 10 choix/);
});
it('rejects duplicated choices regardless of case', () => {
assert.throws(() => parseChoices('Oui;oui'), /différents/);
});
it('rejects more choices than allowed', () => {
assert.throws(() => parseChoices(Array.from({ length: 11 }, (_v, i) => i).join(';')), /entre 2 et 10/);
});
});
describe('toSqliteDate', () => {
it('formats a UTC datetime the way SQLite stores it', () => {
assert.equal(toSqliteDate(new Date('2026-03-04T05:06:07.890Z')), '2026-03-04 05:06:07');
});
});
describe('buildPollEmbed', () => {
const poll = {
id: 3,
creator_id: 'u1',
question: 'Quel thème ?',
choices: JSON.stringify(['Clair', 'Sombre']),
status: 'open',
ends_at: null,
};
it('reports the totals and the percentage of each choice', () => {
const embed = buildPollEmbed(poll, [
{ choice_index: 0, count: 3 },
{ choice_index: 1, count: 1 },
]);
assert.equal(embed.data.title, 'Sondage #3 — Quel thème ?');
assert.match(embed.data.description, /Clair/);
assert.match(embed.data.description, /3 \(75 %\)/);
assert.equal(embed.data.fields[0].value, '4');
});
it('handles a poll without any vote', () => {
const embed = buildPollEmbed(poll, []);
assert.match(embed.data.description, /0 \(0 %\)/);
assert.equal(embed.data.fields[0].value, '0');
});
it('announces the winning choice once closed', () => {
const closed = { ...poll, status: 'closed' };
const embed = buildPollEmbed(closed, [
{ choice_index: 0, count: 1 },
{ choice_index: 1, count: 5 },
]);
assert.equal(embed.data.fields.at(-1).value, '**Sombre** (5 vote(s))');
});
it('says so when a closed poll has no vote', () => {
const embed = buildPollEmbed({ ...poll, status: 'closed' }, []);
assert.equal(embed.data.fields.at(-1).value, 'Aucun vote');
});
});
describe('formatDuration', () => {
it('formats minutes, hours and days', () => {
assert.equal(formatDuration(30 * 60_000), '30 min');
assert.equal(formatDuration(60 * 60_000), '1 h');
assert.equal(formatDuration(150 * 60_000), '2 h 30 min');
assert.equal(formatDuration(24 * 60 * 60_000), '1 j');
assert.equal(formatDuration(30 * 60 * 60_000), '1 j 6 h');
});
});
+189
View File
@@ -0,0 +1,189 @@
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 {
countActions,
listActions,
recordAction,
} from '../src/database/repositories/moderation-repository.js';
import {
getNotificationChannel,
removeNotificationChannel,
setNotificationChannel,
} from '../src/database/repositories/notification-repository.js';
import {
castVote,
closePoll,
countVotes,
createPoll,
listDuePolls,
} from '../src/database/repositories/poll-repository.js';
import {
claimTicket,
closeTicket,
countOpenTickets,
createTicket,
getOpenTicket,
getTicketByChannel,
} from '../src/database/repositories/ticket-repository.js';
const reset = () =>
getDatabase().exec(
'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels;',
);
describe('ticket repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
const openTicket = () => createTicket({ guildId: 'g', channelId: 'c1', categoryId: 'bug', authorId: 'u1' });
it('creates a ticket and finds it by channel', () => {
const id = openTicket();
const ticket = getTicketByChannel('c1');
assert.equal(ticket.id, id);
assert.equal(ticket.status, 'open');
assert.equal(ticket.claimed_by, null);
});
it('refuses a second open ticket for the same author and category', () => {
openTicket();
assert.throws(
() => createTicket({ guildId: 'g', channelId: 'c2', categoryId: 'bug', authorId: 'u1' }),
/UNIQUE/,
);
assert.equal(getOpenTicket({ guildId: 'g', authorId: 'u1', categoryId: 'bug' }).channel_id, 'c1');
});
it('allows a new ticket once the previous one is closed', () => {
const id = openTicket();
closeTicket(id, { closedBy: 'staff', reason: 'résolu' });
const newId = createTicket({ guildId: 'g', channelId: 'c3', categoryId: 'bug', authorId: 'u1' });
assert.notEqual(newId, id);
assert.equal(countOpenTickets('g'), 1);
});
it('records who claimed and closed a ticket', () => {
const id = openTicket();
assert.equal(claimTicket(id, 'staff'), 1);
assert.equal(getTicketByChannel('c1').claimed_by, 'staff');
assert.equal(closeTicket(id, { closedBy: 'staff', reason: 'ok' }), 1);
const closed = getTicketByChannel('c1');
assert.equal(closed.status, 'closed');
assert.equal(closed.close_reason, 'ok');
assert.ok(closed.closed_at);
});
it('cannot close a ticket twice', () => {
const id = openTicket();
closeTicket(id, { closedBy: 'staff' });
assert.equal(closeTicket(id, { closedBy: 'staff' }), 0);
});
});
describe('moderation repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
it('records and lists actions of a target', () => {
recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'spam' });
recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'again' });
recordAction({ guildId: 'g', action: 'kick', moderatorId: 'm2', targetId: 'u2' });
assert.equal(countActions({ guildId: 'g', targetId: 'u1', action: 'warn' }), 2);
const history = listActions({ guildId: 'g', targetId: 'u1' });
assert.equal(history.length, 2);
assert.equal(history[0].reason, 'again');
assert.equal(listActions({ guildId: 'g', action: 'kick' }).length, 1);
});
it('keeps the duration of a mute', () => {
recordAction({
guildId: 'g',
action: 'mute',
moderatorId: 'm1',
targetId: 'u1',
durationMs: 60_000,
});
assert.equal(listActions({ guildId: 'g', targetId: 'u1' })[0].duration_ms, 60_000);
});
});
describe('poll repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
const poll = () =>
createPoll({
guildId: 'g',
channelId: 'c',
creatorId: 'u1',
question: 'Question ?',
choices: ['a', 'b'],
endsAt: null,
});
it('counts one vote per user and allows a change of mind', () => {
const id = poll();
assert.equal(castVote(id, 'u1', 0), 'created');
assert.equal(castVote(id, 'u1', 0), 'unchanged');
assert.equal(castVote(id, 'u1', 1), 'changed');
assert.equal(castVote(id, 'u2', 1), 'created');
const counts = countVotes(id);
assert.equal(counts.length, 1);
assert.deepEqual({ ...counts[0] }, { choice_index: 1, count: 2 });
});
it('lists only the polls whose end date has passed', () => {
const due = createPoll({
guildId: 'g',
channelId: 'c',
creatorId: 'u1',
question: 'Bientôt fini',
choices: ['a', 'b'],
endsAt: '2000-01-01 00:00:00',
});
createPoll({
guildId: 'g',
channelId: 'c',
creatorId: 'u1',
question: 'En cours',
choices: ['a', 'b'],
endsAt: '2999-01-01 00:00:00',
});
const ids = listDuePolls().map((row) => row.id);
assert.deepEqual(ids, [due]);
});
it('closes a poll only once', () => {
const id = poll();
assert.equal(closePoll(id), 1);
assert.equal(closePoll(id), 0);
});
});
describe('notification repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
it('stores one channel per type and replaces it', () => {
setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c1' });
setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c2' });
assert.equal(getNotificationChannel('g', 'issues').channel_id, 'c2');
assert.equal(getNotificationChannel('other', 'issues'), null);
});
it('removes an override and reports it', () => {
setNotificationChannel({ guildId: 'g', type: 'release', channelId: 'c1' });
assert.equal(removeNotificationChannel('g', 'release'), 1);
assert.equal(removeNotificationChannel('g', 'release'), 0);
});
});
+139
View File
@@ -0,0 +1,139 @@
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 {
addVoiceChannel,
countVoiceChannels,
getVoiceChannel,
listOwnedVoiceChannels,
listVoiceChannels,
removeVoiceChannel,
setVoiceLimit,
setVoiceLocked,
setVoiceName,
setVoiceOwner,
} from '../src/database/repositories/voice-repository.js';
import { PermissionDeniedError, UserFacingError } from '../src/core/errors.js';
import {
assertVoiceOwner,
buildChannelName,
clampLimit,
isStaff,
sanitizeChannelName,
} from '../src/services/voice/voice-service.js';
const member = (roleIds = [], { id = 'u1', guildOwnerId = 'someone-else' } = {}) => ({
id,
guild: { ownerId: guildOwnerId },
roles: { cache: new Set(roleIds) },
});
describe('voice repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM voice_channels'));
const add = (channelId, ownerId = 'u1') =>
addVoiceChannel({
channelId,
guildId: 'g',
ownerId,
triggerId: 'trigger',
name: 'Salon de u1',
userLimit: 0,
});
it('stores a temporary channel and reads it back', () => {
add('c1');
const row = getVoiceChannel('c1');
assert.equal(row.owner_id, 'u1');
assert.equal(row.trigger_id, 'trigger');
assert.equal(row.locked, 0);
assert.equal(row.user_limit, 0);
assert.ok(row.created_at);
});
it('keeps several channels per guild and per owner, without any limit', () => {
add('c1');
add('c2');
add('c3', 'u2');
assert.equal(countVoiceChannels('g'), 3);
assert.equal(listVoiceChannels('g').length, 3);
assert.deepEqual(
listOwnedVoiceChannels('g', 'u1').map((row) => row.channel_id),
['c1', 'c2'],
);
});
it('updates the owner, the name, the lock and the limit', () => {
add('c1');
setVoiceOwner('c1', 'u2');
setVoiceName('c1', 'Nouveau nom');
setVoiceLocked('c1', true);
setVoiceLimit('c1', 5);
const row = getVoiceChannel('c1');
assert.equal(row.owner_id, 'u2');
assert.equal(row.name, 'Nouveau nom');
assert.equal(row.locked, 1);
assert.equal(row.user_limit, 5);
});
it('forgets a channel once deleted', () => {
add('c1');
assert.equal(removeVoiceChannel('c1'), 1);
assert.equal(getVoiceChannel('c1'), null);
assert.equal(removeVoiceChannel('c1'), 0);
});
});
describe('voice helpers', () => {
it('normalises a channel name', () => {
assert.equal(sanitizeChannelName(' Salon de Léa '), 'Salon de Léa');
assert.equal(sanitizeChannelName('a\nb'), 'a b');
assert.equal(sanitizeChannelName('x'.repeat(150)).length, 100);
assert.throws(() => sanitizeChannelName(' '), UserFacingError);
});
it('builds the channel name from the template', () => {
const member = { displayName: 'Léa', user: { username: 'lea' } };
assert.equal(buildChannelName('🔊 Salon de {user}', member), '🔊 Salon de Léa');
assert.equal(buildChannelName('', member), '🔊 Salon de Léa');
assert.equal(buildChannelName('{user} {user}', member), 'Léa Léa');
assert.equal(buildChannelName(' ', member), '🔊 Salon vocal');
});
it('accepts 0..99 as a user limit and rejects anything else', () => {
assert.equal(clampLimit(0), 0);
assert.equal(clampLimit(99), 99);
assert.equal(clampLimit('12'), 12);
assert.equal(clampLimit(150), 0);
assert.equal(clampLimit('abc'), 0);
assert.throws(() => clampLimit(150, { strict: true }), UserFacingError);
assert.throws(() => clampLimit(-1, { strict: true }), UserFacingError);
});
});
describe('voice ownership', () => {
const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff' };
const row = { owner_id: 'u1' };
const context = (id, roleIds = [], overrides = {}) => ({
user: { id },
member: member(roleIds, { id, ...overrides }),
});
it('lets the owner manage their channel', () => {
assert.doesNotThrow(() => assertVoiceOwner(context('u1'), row));
});
it('refuses a plain member', () => {
assert.throws(() => assertVoiceOwner(context('u2'), row), PermissionDeniedError);
});
it('recognises staff from the configured roles', () => {
assert.equal(isStaff(member(['r-staff']), roles), true);
assert.equal(isStaff(member(['r-dev']), roles), true);
assert.equal(isStaff(member(['r-member']), roles), false);
assert.equal(isStaff(member([], { id: 'u9', guildOwnerId: 'u9' }), roles), true);
});
});