8 Commits
Author SHA1 Message Date
BlackAngelTV ee538cb943 docs(changelog): list the voice, status and tone work in the changelog
The generated file only knew the history of the previous pass, so the features
merged after it were missing from the notes.
2026-09-15 16:15:01 +02:00
BlackAngelTV 9bbe9cb0b4 docs(readme): translate the documentation and document the contribution workflow
The organisation asks every repository for both languages, for the issue and
pull request templates, and for the commit, branch and release rules; the
README now states them, README.en.md mirrors it, and a test keeps the two in
sync so a change on one side cannot be forgotten on the other.

The readme also documents what shipped since it was last written: several voice
triggers, the guaranteed cleanup of empty channels, the editable bot statuses,
the message tone and the variables they add.
2026-09-15 16:15:00 +02:00
BlackAngelTV 478ae41d86 build(changelog): generate the changelog from the commit history
Releases are expected to ship notes built from the Conventional Commits, and a
hand-written file drifts from the history within a few merges. The generator
reads the log directly, so it adds no dependency, and `npm run changelog:check`
gives CI a way to fail when the file was not regenerated.

A commit that only rewrites the changelog is left out of it, otherwise the
check could never be green once that file is committed.
2026-09-15 16:14:28 +02:00
BlackAngelTV 2df33c205c chore(gitignore): ignore the AI assistant data and the other toolchains
The organisation lists a minimum ignore set for every repository: the data
directory of the development assistants and the artefacts of the languages a
contributor may build next to this one must never reach the repository.
2026-09-15 16:13:52 +02:00
BlackAngelTV c785e9abb7 feat(status): rotate an editable list of bot statuses
The presence line was hard-coded, so advertising a different message meant
editing the source and restarting the bot. Statuses now live in the database
and are managed from Discord with /status — add, list, remove, pause and the
rotation interval, which applies without a restart.

An empty list falls back to a neutral "see the commands with /help" line, and
the first status added shows up right away instead of waiting a full turn.
2026-09-15 16:12:50 +02:00
BlackAngelTV ef8f09da10 refactor(ui): give every message one friendly, ungendered voice
Members read all replies as one voice, so the wording now lives in one place:
the shared titles, the list marker and the "what to do next" hint come from
src/ui/embeds.js, and every module follows them.

An error explains the cause, recalls the rule and offers the way out instead of
blaming; a success says what happens next. Nothing agrees on the gender of a
person ("utilisateur", "cher/chère", "ravie"), which also keeps the sentences
shorter. Two tests lock the shared titles and reject gendered descriptions.
2026-09-15 16:12:19 +02:00
BlackAngelTV 76e2269555 feat(voice): guarantee an empty generated channel disappears
A generated channel could survive with nobody in it: the row was dropped before
the channel was really gone, so a refused delete call left a room nothing could
track anymore, and an event missed while the bot was down was never retried.

The row is now kept until Discord confirms the channel is gone, and a sweep at
startup then every minute deletes whatever the event missed. The grace period
is tunable with VOICE_EMPTY_GRACE_MS, 0 deleting as soon as the room empties.
2026-09-15 16:11:30 +02:00
BlackAngelTV 836abeafd5 feat(voice): support several trigger channels with their own category
A server needs one "create your own room" channel per theme, which a single
trigger id could not express. Triggers are now stored as a list, each with its
own home category, name template and default limit.

Joining a trigger creates the channel at the bottom of that trigger's category,
and a member keeps one channel per trigger instead of one room for the whole
server. Triggers declared by the single-trigger version and
CHANNEL_VOICE_TRIGGER_ID still work as fallbacks, so no server has to be
reconfigured.
2026-09-15 16:09:39 +02:00
55 changed files with 3233 additions and 375 deletions

No files matched your search

+6
View File
@@ -47,6 +47,12 @@ CATEGORY_TICKETS_ID=
CHANNEL_VOICE_TRIGGER_ID=
# Catégorie d'accueil des salons vocaux créés (facultatif)
CATEGORY_VOICE_ID=
# Délai avant qu'un salon généré devenu vide soit supprimé, en ms (0 = immédiat)
VOICE_EMPTY_GRACE_MS=5000
# --- Statuts du bot (M15) -----------------------------------------------------
# Rythme par défaut de la rotation, en secondes (modifiable à chaud par /status interval)
BOT_STATUS_INTERVAL_SECONDS=60
# --- Gitea (M5-T01) ----------------------------------------------------------
GITEA_URL=https://gitea.nocode-var.tech
+39
View File
@@ -0,0 +1,39 @@
---
name: Bug
about: Signaler un comportement inattendu
title: "[bug] "
labels: bug
---
## Description
<!-- Ce qui ne va pas, en une ou deux phrases. -->
## Étapes de reproduction
1.
2.
3.
## Comportement attendu
<!-- Ce qui devrait se passer. -->
## Comportement observé
<!-- Ce qui se passe vraiment : message affiché, code d'erreur, capture. -->
## Environnement
- OS :
- Node.js (`node -v`) :
- Version du bot (`version` dans `package.json`) :
- Serveur / salon concerné :
## Logs
<!-- Colle les lignes de logs/AAAA-MM-JJ.log (en masquant les identifiants si besoin) ou une capture d'écran. -->
## Contexte
<!-- Optionnel : commande utilisée, carte Kanban, issue ou PR liée, contournement trouvé. -->
+29
View File
@@ -0,0 +1,29 @@
---
name: Demande / amélioration
about: Proposer une fonctionnalité ou une amélioration
title: "[enhancement] "
labels: enhancement
---
## Besoin
<!-- Quel problème cela résout, pour qui (membres, équipe, développeurs). -->
## Proposition
<!-- Le comportement souhaité, vu depuis Discord : quelle commande, quelles options, quelle réponse. -->
## Alternatives envisagées
<!-- Optionnel : autres pistes, solutions de contournement existantes. -->
## Impact
- [ ] Nouvelle commande ou nouvelle option
- [ ] Changement de comportement d'une fonctionnalité existante
- [ ] Base de données (nouvelle migration)
- [ ] Documentation (`README.md` / `README.en.md` / `docs/`)
## Contexte
<!-- Optionnel : carte Kanban, issue liée, maquette, capture. -->
+28
View File
@@ -0,0 +1,28 @@
## Objectif
<!-- Pourquoi cette pull request existe : besoin traité, carte Kanban. -->
Fixes #
## Ce que fait la pull request
<!-- Les changements, du point de vue de qui relit. Pas de liste de fichiers. -->
## Comment tester
<!-- Étapes concrètes : commande à lancer dans Discord, entrée à envoyer au webhook, migration à appliquer. -->
## Vérifications
- [ ] `npm run lint`
- [ ] `npm run format:check`
- [ ] `npm test`
- [ ] `npm run changelog` (si des commits `feat:` ou `fix:` sont ajoutés)
## Checklist
- [ ] Commits en **anglais** au format Conventional Commits (`<type>(<scope>): <description>`)
- [ ] Branche `type/description` créée depuis `main`
- [ ] Tests ajoutés ou mis à jour quand le comportement change
- [ ] `README.md` et `README.en.md` synchronisés quand la documentation change
- [ ] Au moins un reviewer demandé, merge en **squash** (1 PR = 1 commit)
+16 -1
View File
@@ -5,7 +5,10 @@ node_modules/
.env
.env.*
!.env.example
.freebuff
# Development assistant data (never committed)
.freebuff/
.cursor/
# SQLite databases and backups
data/*
@@ -29,7 +32,19 @@ build/
coverage/
.cache/
# Compiled artefacts of the other toolchains used across FWS projects
target/
__pycache__/
*.pyc
*.pyo
*.o
*.so
*.exe
*.dll
# Editors and OS
# `.vscode/extensions.json` stays tracked on purpose: it holds the recommended extensions
# shared by the project. Everything else in the folder is personal.
.vscode/*
!.vscode/extensions.json
.idea/
+92
View File
@@ -0,0 +1,92 @@
# Changelog
All notable changes to this project are documented in this file. It is **generated from the
Conventional Commits** of the history: run `npm run changelog` instead of editing it by hand.
The project follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Features
- **status:** _(feat)_ rotate an editable list of bot statuses ([c785e9a])
- **voice:** _(feat)_ guarantee an empty generated channel disappears ([76e2269])
- **voice:** _(feat)_ support several trigger channels with their own category ([836abea])
- **voice:** _(feat)_ add temporary voice channel manager ([5191942])
- **polls:** _(feat)_ implement polls, fun and statistics commands ([ef1bedb])
- **members:** _(feat)_ add welcome, default role and departure reporting ([f29c095])
- **moderation:** _(feat)_ implement the moderation service and commands ([c49c600])
- **tickets:** _(feat)_ implement the ticket service, command and channel controls ([e8c95b2])
- **notifications:** _(feat)_ dispatch Gitea webhooks through the notification service ([a5280ce])
- **fws:** _(feat)_ implement the version, status and changelog subcommands ([26d7cce])
- **gitea:** _(feat)_ add embeds, modals and the issue and pull request commands ([76d0bf9])
- **core:** _(feat)_ add shared constants, interaction components and Gitea client helpers ([66be463])
- **database:** _(feat)_ add repositories for tickets, moderation, polls and notifications ([03a217c])
- **database:** _(feat)_ add database initialization script ([9a266b7])
- **commands:** _(feat)_ add slash command deployment script ([6b4ac37])
- **core:** _(feat)_ add bot entry point ([de97f87])
- **fun:** _(feat)_ add fun command skeleton ([208d713])
- **stats:** _(feat)_ add stats command skeleton ([baca3f0])
- **polls:** _(feat)_ add poll command skeleton ([9ccecb3])
- **roles:** _(feat)_ add role command skeleton ([cef9ed0])
- **moderation:** _(feat)_ add moderation logs command skeleton ([744eaa8])
- **moderation:** _(feat)_ add clear command skeleton ([dc4958f])
- **moderation:** _(feat)_ add ban command skeleton ([002380c])
- **moderation:** _(feat)_ add kick command skeleton ([4cc475e])
- **moderation:** _(feat)_ add mute command skeleton ([373c7e6])
- **moderation:** _(feat)_ add warn command skeleton ([1bcc3d3])
- **support:** _(feat)_ add ticket command skeleton ([ab08253])
- **gitea:** _(feat)_ add activity and release command skeleton ([d9ce9e4])
- **gitea:** _(feat)_ add pull request command skeleton ([44c9595])
- **gitea:** _(feat)_ add issue command skeleton ([bd2475c])
- **fws:** _(feat)_ add fws information command ([4cc6964])
- **commands:** _(feat)_ add help command ([3aa17e5])
- **members:** _(feat)_ add member leave event handler ([9cb2a73])
- **members:** _(feat)_ add member join event handler ([aa404dd])
- **commands:** _(feat)_ dispatch slash commands with access control ([017764d])
- **discord:** _(feat)_ log shard disconnections ([8f48efd])
- **discord:** _(feat)_ log discord client errors ([e9c110a])
- **discord:** _(feat)_ handle client ready event ([0fb20d1])
- **webhooks:** _(feat)_ add http server for gitea webhooks ([fb63cc9])
- **webhooks:** _(feat)_ validate and deduplicate gitea webhook events ([7a7d8e6])
- **notifications:** _(feat)_ add notification dispatch service ([13f8e24])
- **gitea:** _(feat)_ add gitea api client ([6fca3b7])
- **ui:** _(feat)_ add link buttons builder ([856e7ba])
- **ui:** _(feat)_ add standard embed builders ([94dab89])
- **utils:** _(feat)_ add cooldown guard against duplicate actions ([f56e837])
- **utils:** _(feat)_ add retry helper with exponential backoff ([4205ed5])
- **database:** _(feat)_ add event log repository ([de64a0e])
- **database:** _(feat)_ add guild settings repository ([910cf32])
- **database:** _(feat)_ initialize sqlite connection and migrations ([5716d24])
- **database:** _(feat)_ add initial sqlite schema ([a2520fe])
- **discord:** _(feat)_ add event loader ([34da3eb])
- **commands:** _(feat)_ add slash command loader ([15e7279])
- **discord:** _(feat)_ create client with required gateway intents ([baf8db0])
- **auth:** _(feat)_ add centralized permission checks ([2085f57])
- **observability:** _(feat)_ add json logger with secret masking ([c03027e])
- **core:** _(feat)_ add typed application errors ([bba2ee7])
- **config:** _(feat)_ add colors, access levels and ticket categories ([eca9bbe])
- **config:** _(feat)_ load and expose environment settings ([d1388b6])
### Other changes
- **readme:** _(docs)_ translate the documentation and document the contribution workflow ([9bbe9cb])
- **changelog:** _(build)_ generate the changelog from the commit history ([478ae41])
- **gitignore:** _(chore)_ ignore the AI assistant data and the other toolchains ([2df33c2])
- **ui:** _(refactor)_ give every message one friendly, ungendered voice ([ef8f09d])
- **agents:** _(docs)_ add the shared agent instructions for FWS repositories ([66c04c6])
- **readme:** _(docs)_ document the implemented features and the voice manager ([be4981a])
- **app:** _(test)_ add command and event loading smoke tests ([aa5343b])
- **core:** _(docs)_ document project structure ([abf6701])
- **docs:** _(chore)_ add screenshots directory ([fec8007])
- **observability:** _(chore)_ keep logs directory in repository ([9f2aa90])
- **database:** _(chore)_ keep data directory in repository ([070612a])
- **database:** _(test)_ add sqlite storage tests ([baef3fa])
- **auth:** _(test)_ add permission checks tests ([52e24bd])
- **config:** _(build)_ add environment variables example ([1cf7b1f])
- **quality:** _(build)_ configure eslint flat config ([de328af])
- **quality:** _(build)_ add prettier ignore rules ([25cc44d])
- **quality:** _(build)_ configure prettier ([bafda6b])
- **deps:** _(build)_ add npm lockfile ([d4d5854])
- **deps:** _(build)_ add package manifest with discord.js and npm scripts ([f57a4f2])
- **editor:** _(chore)_ add editorconfig settings ([4693ea0])
- **security:** _(build)_ replace python ignore rules with node.js rules ([bfd4c26])
- **BREAKING** **readme:** _(docs)_ Edit of the Readme ([2a91229])
- Initial commit ([5fc5cf8])
+473
View File
@@ -0,0 +1,473 @@
# FWS-Bot
> Discord bot for the open source **FWS** organisation — community support, tickets, moderation, Gitea integration and statistics for **FWS Arch** (an Arch Linux fork with a friendly layer on top).
🌍 [Version française](README.md) · **English**
Status: **working**. The 19 commands are implemented (support, private tickets, moderation, Gitea, polls, statistics, bot statuses, voice channel manager), together with member welcome and the Gitea webhook delivery.
This project follows the [FWS organisation conventions](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md): English commit messages in the Conventional Commits format, `type/description` branches, reviewed pull requests merged with squash, SemVer and a `CHANGELOG.md` generated from the commits.
---
## 1. Tech stack
Deliberate choices: **a single runtime dependency** (discord.js), no native module to compile, and the test runner built into Node.
| Tech | Version | Purpose |
| ------------------ | --------------------- | ------------------------------------------------------------------------- |
| **Node.js** | ≥ 22.13.0 (ESM) | Runtime. Required for `node:sqlite`, `process.loadEnvFile`, `--watch` |
| **discord.js** | ^14.21.0 | Discord API: slash commands, embeds, buttons, intents |
| **`node:sqlite`** | native module | SQLite database (WAL, foreign keys) — no `better-sqlite3`, no compilation |
| **native `fetch`** | — | Gitea REST client (with `AbortSignal.timeout`) |
| **`node:http`** | — | Gitea webhook server (no Express) |
| **`node:crypto`** | — | HMAC-SHA256 signature of the webhooks |
| **`node:test`** | — | Built-in unit tests (`node --test`) |
| **ESLint** | ^9.30.0 (flat config) | Linting |
| **Prettier** | ^3.6.2 | Formatting |
## 2. Requirements
- Node.js ≥ 22.13 (`node -v` to check) and npm
- A Discord application (free) with a bot token
- (Optional) a Gitea instance for issues/pull requests and webhooks
## 3. Quick start with a test token
### 3.1 Create the Discord application
1. Open the [Discord Developer Portal](https://discord.com/developers/applications) → **New Application**.
2. **Bot** tab → **Reset Token** → copy the token: that is your `DISCORD_TOKEN` (never share it, never commit it).
3. Still in **Bot** → **Privileged Gateway Intents** → enable **Server Members Intent** (needed to welcome new members; `Message Content` is not required).
4. **General Information** tab → copy the **Application ID**: that is your `DISCORD_CLIENT_ID`.
### 3.2 Invite the bot to a test server
Replace `CLIENT_ID` with your Application ID:
```text
https://discord.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot+applications.commands&permissions=1099812662294
```
That URL pre-checks every permission the commands use: View Channels, Send Messages, Manage Messages, Embed Links, Read Message History, Kick Members, Ban Members, Manage Roles, Moderate Members (timeout), plus the voice channel ones: Manage Channels, Connect, Speak, Mute Members, Deafen Members, Move Members. You can also use **OAuth2 → URL Generator** with the `bot` + `applications.commands` scopes.
Create (or reuse) a test server you own: that is what grants the bot the **Owner** level.
### 3.3 Collect the Discord IDs
On Discord: **Settings → Advanced → Developer Mode** on, then right-click a server / channel / role → **Copy ID**.
| Variable | Where to find it |
| ----------------------------------------------------------------- | ------------------------------------------- |
| `DISCORD_GUILD_ID` | Right-click the test server |
| `ROLE_OWNER_ID`, `ROLE_DEV_ID`, `ROLE_STAFF_ID`, `ROLE_MEMBER_ID` | Server settings → Roles (create them first) |
| `CHANNEL_WELCOME_ID`, `CHANNEL_LOGS_ID`, etc. | Right-click each channel |
> Without configured roles everyone counts as **User** (except the server owner, who is Owner).
### 3.4 Run the bot
```bash
# 1. Dependencies
npm install
# 2. Configuration: copy .env.example to .env and fill it in
# Minimum required: DISCORD_TOKEN, DISCORD_CLIENT_ID, DISCORD_GUILD_ID
cp .env.example .env
# 3. Create the SQLite database and apply the migrations
npm run db:init
# 4. Register the slash commands on the server (instant, per guild)
npm run deploy:commands
# 5. Start with automatic reload
npm run dev
```
The logs should show `Connected as <BotName>`. Type `/help` on the server: you should see the commands your role can use.
Without a `.env` the bot refuses to start (`assertRequiredEnv` checks the token, client ID and guild ID).
## 4. Configuration — every variable (`.env`)
Full template: [`.env.example`](.env.example). Default values in brackets.
### Runtime
| Variable | Default | Description |
| ----------------------------- | ------------- | ------------------------------------------------------------------------------- |
| `NODE_ENV` | `development` | `development` \| `production` \| `test` |
| `LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` |
| `LOG_DIR` | `./logs` | Directory of the daily JSON logs |
| `LOG_RETENTION_DAYS` | `30` | Retention window (purges `event_logs`) |
| `VOICE_EMPTY_GRACE_MS` | `5000` | Delay before a generated voice channel left empty is deleted (`0` = immediate) |
| `BOT_STATUS_INTERVAL_SECONDS` | `60` | Default rotation speed of the bot statuses (changeable with `/status interval`) |
### Discord application
| Variable | Description |
| ------------------- | ------------------------------------------------------------ |
| `DISCORD_TOKEN` | **Required.** Bot token (Developer Portal → Bot) |
| `DISCORD_CLIENT_ID` | **Required.** Application ID |
| `DISCORD_GUILD_ID` | **Required.** Server where the slash commands are registered |
### FWS roles (Discord role IDs)
| Variable | Matching level |
| ---------------- | ------------------------------------------ |
| `ROLE_OWNER_ID` | Owner — full access |
| `ROLE_DEV_ID` | Dev — FWS Arch configuration, Gitea writes |
| `ROLE_STAFF_ID` | Staff — moderation, support, tickets |
| `ROLE_MEMBER_ID` | Initial role given to new members |
### Discord channels (IDs)
| Variable | Usage |
| -------------------------------- | --------------------------------------------------------------------------- |
| `CHANNEL_WELCOME_ID` | Welcome messages |
| `CHANNEL_RULES_ID` | Rules (link sent to newcomers) |
| `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements |
| `CHANNEL_LOGS_ID` | Functional logs |
| `CHANNEL_MOD_LOGS_ID` | Moderation logs |
| `CHANNEL_TICKETS_LOGS_ID` | Ticket opening/closing journal |
| `CHANNEL_NOTIF_ISSUES_ID` | Issue notifications |
| `CHANNEL_NOTIF_PULL_REQUESTS_ID` | Pull request notifications |
| `CHANNEL_NOTIF_COMMITS_ID` | Commit notifications |
| `CHANNEL_NOTIF_RELEASES_ID` | Release notifications |
| `CHANNEL_NOTIF_ERRORS_ID` | Errors and incidents |
| `CATEGORY_TICKETS_ID` | Category where the private ticket channels are created |
| `CHANNEL_VOICE_TRIGGER_ID` | Trigger voice channel (fallback: `/voice setup` manages a list of triggers) |
| `CATEGORY_VOICE_ID` | Home category of the generated voice channels (optional) |
### Gitea
| Variable | Default | Description |
| ------------------- | ------- | ---------------------------------------------------------------------- |
| `GITEA_URL` | — | Instance URL (without a trailing `/`) |
| `GITEA_TOKEN` | — | Least privilege token (`read:repository`, `write:issue`). Never logged |
| `GITEA_OWNER` | — | Repository owner (e.g. `FWS`) |
| `GITEA_REPO` | — | Target repository (e.g. `FWS-Arch`) |
| `GITEA_TIMEOUT_MS` | `10000` | Request timeout |
| `GITEA_MAX_RETRIES` | `2` | Retries on transient errors (429, 5xx, timeout) |
### Gitea webhooks
| Variable | Default | Description |
| ---------------------- | ----------------- | ---------------------------------------------------- |
| `WEBHOOK_ENABLED` | `false` | Starts the receiving HTTP server |
| `WEBHOOK_HOST` | `0.0.0.0` | Listening interface |
| `WEBHOOK_PORT` | `3000` | Listening port |
| `WEBHOOK_PATH` | `/webhooks/gitea` | Path to configure in Gitea |
| `GITEA_WEBHOOK_SECRET` | — | Shared secret (HMAC-SHA256), set in Gitea → Webhooks |
### SQLite and links
| Variable | Default | Description |
| -------------------------------------------------------------------------------- | ----------------------- | -------------------------------------------------------------------------------- |
| `DATABASE_PATH` | `./data/fws-bot.sqlite` | Database file (excluded from git) |
| `BACKUP_DIR` | `./data/backups` | Backup directory |
| `FWS_WEBSITE_URL`, `FWS_DOCS_URL`, `FWS_DISCORD_INVITE_URL`, `FWS_ARCH_REPO_URL` | — | Official links shown by `/fws info` and `/fws links` (empty buttons are omitted) |
## 5. Slash commands
19 commands are registered. Every command carries an **FWS access level** checked server-side before running, and the moderation commands additionally check the matching **Discord permission** (`DefaultMemberPermissions`).
### Access levels
Resolved from the roles configured in `.env` (highest to lowest):
| Level | Who |
| ----------- | ------------------------------- |
| `OWNER` (3) | Owner role, or the server owner |
| `DEV` (2) | Dev role |
| `STAFF` (1) | Staff role |
| `USER` (0) | Every member |
### General and FWS
| Command | Options | Access | State | Description |
| --------------------------------------- | --------------------------------- | --------------------------- | ----- | -------------------------------------------------------------------------------------- |
| `/help` | — | User | ✅ | Lists the commands your role can use (ephemeral reply) |
| `/fws info` | — | User | ✅ | Presents FWS and FWS Arch (text overridable through `guild_settings`) + official links |
| `/fws links` | — | User | ✅ | Resources: website, docs, repository, Gitea, Discord |
| `/fws version` | — | User | ✅ | Latest Gitea release (tag, date, author) + button to the notes |
| `/fws status` | — | User | ✅ | Service status: Gitea API, webhooks, SQLite, Discord latency, uptime |
| `/fws changelog` | `version` (optional) | User | ✅ | Release notes (latest by default, clear message when the tag does not exist) |
| `/status add` | `text` (128 chars), `type`, `url` | **Staff** + _Manage Server_ | ✅ | Adds a status to the rotation; the first one is shown right away |
| `/status list` | — | **Staff** + _Manage Server_ | ✅ | Stored statuses: number, type, state, rotation speed |
| `/status remove` · `enable` · `disable` | `id` | **Staff** + _Manage Server_ | ✅ | Removes a status, puts it back in rotation or pauses it |
| `/status interval` | `seconds` (5–86 400) | **Staff** + _Manage Server_ | ✅ | Rotation speed, applied without a restart |
| `/status clear` | — | **Staff** + _Manage Server_ | ✅ | Empties the list and returns to the default line |
### Gitea — issues and pull requests
| Command | Options | Access | State | Description |
| ----------------- | ------------------------------------------- | ------------------- | ----- | ------------------------------------------------------ |
| `/issue create` | — (modal: title + description) | User (configurable) | ✅ | Creates a Gitea issue and returns its link |
| `/issue view` | `number` | User | ✅ | Title, author, state, labels, link of an issue |
| `/issue list` | — | User | ✅ | Open issues (last 15) |
| `/pr create` | `head`, `base` + modal (title, description) | **Dev** | ✅ | Creates a Gitea pull request |
| `/pr view` | `number` | User | ✅ | Title, author, state, branches, link of a pull request |
| `/pr list` | — | User | ✅ | Open pull requests (last 15) |
| `/gitea activity` | — | User | ✅ | Latest commits + open issues and pull requests |
| `/gitea release` | — | User | ✅ | FWS Arch releases (last 5) |
> The Gitea client (`src/services/gitea/gitea-client.js`): REST with token, timeout, exponential retry on transient errors. The forms (`/issue create`, `/pr create`) go through a **modal**; the branch options are kept in memory for a few minutes (`pending-actions.js`). Any failure (missing token, 404, 5xx) becomes an explicit ephemeral message, never a raw error.
### Support tickets
Tickets are private channels created under `CATEGORY_TICKETS_ID`. One open ticket per member and per category (SQL constraint).
| Command | Options | Access | State | Description |
| ---------------- | ------------------------------ | -------------------------------- | ----- | ------------------------------------------------------------------------------------ |
| `/ticket create` | `category` (required) | User (depending on the category) | ✅ | Creates a private channel under `CATEGORY_TICKETS_ID` |
| `/ticket close` | `reason` (optional, 500 chars) | Author, Staff | ✅ | Closes, logs and then deletes the channel (10 s) — also through the **Close** button |
| `/ticket claim` | — | **Staff** | ✅ | Takes the ticket over (**Claim** button) |
| `/ticket add` | `user` | **Staff** | ✅ | Adds a participant to the private channel |
Available categories and who can use them:
| Category | Visible to |
| ------------------------- | ----------------- |
| Aide et support | Staff, Owner |
| Bug | Staff, Dev, Owner |
| Question de développement | Dev, Owner |
| Signalement | Staff, Owner |
| Demande interne | Owner |
### Temporary voice channels
A server can declare **as many trigger channels as it needs** — one per theme (`Dev`, `SIO`, …) — each with its own home category (`/voice setup`): joining a trigger creates a private voice channel **at the bottom of that trigger's category**, moves the member in and hands over ownership. The channel is then managed from the **control panel** posted in its chat (_Rename_, _Limit_, _Lock_, _Claim_, _Delete_ buttons and the _Permit_, _Reject_, _Transfer_ menus) or with `/voice`. The number of simultaneous channels is **unlimited**, and a member keeps one channel **per trigger**: joining the same trigger again simply moves them back into the channel they already own.
As soon as **nobody** is left in a generated channel, it is deleted: the delay (5 s by default) lets it survive a quick hop to another channel — tunable with `VOICE_EMPTY_GRACE_MS`, `0` deletes it immediately. A periodic sweep (at startup, then every minute) catches the cases where a Discord event was missed or a deletion was refused, so a generated channel cannot stay empty: either it is deleted, or the attempt is retried.
| Command | Options | Access | Description |
| ---------------------------------------- | ------------------------------------------------------------ | --------------------- | ------------------------------------------------------------------------------------------- |
| `/voice setup` | `trigger`, `label`, `category`, `template`, `limit`, `panel` | **Staff** | Adds (or updates) a trigger channel; without `category`, the trigger's own category is used |
| `/voice config` · `/voice triggers list` | — | User · **Staff** | Declared triggers: category, template, limit, state and live channels |
| `/voice triggers disable` · `enable` | `trigger` | **Staff** | Pauses a trigger (its configuration is kept, joining it creates nothing) · resumes it |
| `/voice triggers remove` | `trigger` | **Staff** | Deletes a trigger declared from Discord |
| `/voice panel` | `trigger` (default: all) | **Staff** | Re-posts the explanation panel in the trigger channels |
| `/voice name` | `name` (100 chars) | Owner | Renames the channel |
| `/voice limit` | `limit` (0–99, 0 = unlimited) | Owner | Number of spots |
| `/voice lock` · `/voice unlock` | — | Owner | Refuses · allows everyone to join |
| `/voice permit` | `user` | Owner | Allows a member to join the channel |
| `/voice reject` | `user` | Owner | Denies access (and kicks them out if they are inside) |
| `/voice kick` | `user` | Owner | Kicks a member out of the channel |
| `/voice transfer` | `user` | Owner | Transfers ownership (the new owner must already be inside) |
| `/voice claim` | — | Member of the channel | Claims a channel whose owner left |
| `/voice delete` | `channel` (staff) | Owner, Staff | Deletes the channel immediately |
| `/voice info` | `channel` (staff) | User | Owner, state, limit, members, age |
> Name template: `{user}` is replaced by the member's display name (default `🔊 Salon de {user}`). Staff can always act on any temporary channel. The owner receives `Manage Channel` + `Move Members` on their own channel only.
>
> `CHANNEL_VOICE_TRIGGER_ID` / `CATEGORY_VOICE_ID` remain a **fallback**: a server whose `.env` declares a trigger works without `/voice setup`, but a trigger coming from the environment can only be paused (`/voice triggers disable`), not deleted from Discord. Changing a trigger's category does not move the channels already created.
### Moderation
Every command checks the FWS level **and** the matching Discord permission. The bot refuses to act on a member whose highest role is equal or higher than the caller's (`canActOn`), and never acts on the server owner.
| Command | Options | Discord permission | State | Description |
| ---------------- | ----------------------------------------- | ------------------ | ----- | ------------------------------------------------------------------ |
| `/warn` | `user`, `reason` (required) | Moderate Members | ✅ | Warns, notifies the member by DM and records the action |
| `/mute` | `user`, `minutes` (1–40320), `reason` | Moderate Members | ✅ | Temporary timeout (28 days max) + DM notification |
| `/kick` | `user`, `reason` | Kick Members | ✅ | Kicks from the server and logs the action |
| `/ban` | `user`, `reason`, `delete_days` (0–7) | Ban Members | ✅ | Bans (even if the member already left), optional message purge |
| `/clear` | `amount` (1–100) | Manage Messages | ✅ | Deletes the last N messages (those older than 14 days are skipped) |
| `/mod logs` | `user` (filter) | Moderate Members | ✅ | History read from `moderation_actions` (last 15, ephemeral) |
| `/role set` | `user`, `role`, `action` (`add`/`remove`) | Manage Roles | ✅ | Adds or removes a role (both hierarchies checked) |
| `/notify set` | `type`, `channel` | Manage Server | ✅ | Notification channel specific to this server (SQLite) |
| `/notify remove` | `type` | Manage Server | ✅ | Returns to the default channel (environment variables) |
| `/notify list` | — | Manage Server | ✅ | Current configuration of every type |
> Every successful action is recorded in `moderation_actions` **and** posted in `CHANNEL_MOD_LOGS_ID` (member, moderator, reason, duration).
### Community and statistics
| Command | Options | Access | State | Description |
| ---------------- | --------------------------------------------------------------------- | --------- | ----- | ---------------------------------------------------------------- |
| `/poll create` | `question`, `choices` (separated by « ; », 2–10), `minutes` (1–10080) | **Staff** | ✅ | Poll voted with buttons, live results |
| `/poll close` | `id` | **Staff** | ✅ | Closes it, shows the winning choice and freezes the message |
| `/stats discord` | — | User | ✅ | Members, channels, roles, boosts, server age, latency |
| `/stats gitea` | — | User | ✅ | Recent commits, open issues and pull requests, latest release |
| `/stats fws` | — | User | ✅ | Local indicators (tickets, polls, moderation) + FWS Arch version |
| `/fun coinflip` | — | User | ✅ | Heads or tails |
| `/fun dice` | `sides` (2–1000, 6 by default) | User | ✅ | Dice roll |
| `/fun 8ball` | `question` | User | ✅ | Magic eight ball (12 answers) |
| `/fun choose` | `options` (separated by « ; », 2–10) | User | ✅ | Random pick |
Legend: ✅ working · expected errors are returned as ephemeral messages (`UserFacingError`), everything else is logged and replaced by a generic message.
## 6. Automations
- **Welcome** (`src/events/guild-member-add.js`): assigns `ROLE_MEMBER_ID` (skipped when that role sits above the bot's), posts a welcome embed in `CHANNEL_WELCOME_ID` pointing at `CHANNEL_RULES_ID`, and sends a DM with the official links (silent when DMs are closed).
- **Departures** (`src/events/guild-member-remove.js`): embed in `CHANNEL_LOGS_ID` (falls back to `CHANNEL_MOD_LOGS_ID`) with the member count, time on the server and account age.
- **Notifications** (`src/services/notifications/notification-service.js`): routing per type — per-guild override in SQLite (`notification_channels`, configured with `/notify set`), otherwise the matching environment variable. A type without a channel is simply ignored (`debug` log).
- **Gitea webhooks**: native HTTP server (`WEBHOOK_ENABLED=true`). Verifies the **HMAC-SHA256** signature (`x-gitea-signature`) in constant time, rejects bodies over 1 MB and invalid JSON, deduplicates redeliveries through `webhook_deliveries`, then posts the embeds through the notification service: `issues` → issues, `pull_request` → PR, `push` → commits, `create`/`delete` → refs, `release` → releases.
- **Polls** (`src/services/polls/poll-service.js`): one vote per member and per poll (changeable, one click moves the vote), the message is refreshed on every vote, and a scheduler closes expired polls automatically (checked every 30 s) even after a restart.
- **Bot statuses** (`src/services/status/bot-status-service.js`): the presence shown under the bot name is a **list stored in the database** (`bot_statuses`), editable live with `/status` (add, remove, pause, speed). The rotation starts over from the first enabled status each cycle and the delay is re-read on every turn, so `/status interval` applies without restarting the bot. Empty list → default line “les commandes avec /help” instead of a hard-coded status.
- **Voice channels** (`src/events/voice-state-update.js`): joining **one of the trigger channels** creates a temporary channel at the bottom of that trigger's category and moves the member in (or moves them back into the one they already own for that trigger); as soon as the last member leaves, the channel is deleted after a short grace period (`VOICE_EMPTY_GRACE_MS`, 5 s by default) that leaves time to switch channels without losing theirs. The deletion only forgets the database row once the channel is really gone: an API error keeps it registered so the attempt can be retried. `sweepVoiceChannels()` forgets vanished channels and deletes the empty ones — at startup, then every minute through `startVoiceJanitor()`, which guarantees a generated channel never survives empty after a missed event or a failed API call.
## 7. Architecture
Full details: [`docs/architecture.md`](docs/architecture.md).
```text
src/
├── index.js # Entry point: env, DB, client, loaders, webhooks, clean shutdown
├── config/ # env.js (.env reading/validation) · constants.js (colors, levels, categories)
├── core/ # client.js · command-loader.js · event-loader.js
│ # permissions.js (levels + hierarchy) · logger.js · errors.js
├── commands/<category>/ # fws, gitea, tickets, moderation, community, general
├── events/ # interaction-create (commands, buttons, modals), ready, member add/remove,
│ # voice state (voice channels), errors, shard
├── services/
│ ├── gitea/ # gitea-client.js (REST + retry) · gitea-embeds.js · gitea-modals.js · pending-actions.js
│ ├── members/ # member-service.js (welcome, initial role, departures)
│ ├── moderation/ # moderation-service.js (hierarchy, sanctions, journal)
│ ├── notifications/ # notification-service.js (routing) · gitea-notifications.js (webhook mapping)
│ ├── polls/ # poll-service.js (creation, votes, closing, scheduler)
│ ├── status/ # bot-status-service.js (bot statuses, validation, rotation)
│ ├── tickets/ # ticket-service.js (private channels, lifecycle)
│ └── voice/ # voice-service.js (several triggers, temporary channels, panel)
├── database/ # index.js (connection + SQL migrations) · migrations/ · repositories/
├── webhooks/ # server.js (node:http) · gitea-webhook.js (signature + dispatch)
├── ui/ # embeds.js (visual identity) · buttons.js (links, tickets, polls)
└── utils/ # retry.js (exponential backoff) · cooldown.js
```
Automatic loading: any command under `src/commands/**` and any event under `src/events/*` is picked up at startup.
**Command contract** (`access` checked in `interaction-create.js`, a `UserFacingError` is shown as-is, any other error is logged and replaced by a generic message):
```js
export const access = ACCESS_LEVELS.STAFF; // minimum level
export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optional, per subcommand
export const data = new SlashCommandBuilder(); /* ... */
export async function execute(interaction) {}
```
**Intents used**: `Guilds`, `GuildMembers` _(privileged — enable it in the portal)_, `GuildModeration`, `GuildMessages`, `GuildVoiceStates`. `MessageContent` is deliberately not requested.
### Message tone and vocabulary
Every text shown in Discord follows the same rules, listed at the top of `src/ui/embeds.js` (single source of truth):
- **Informal “tu”**, short sentences, active voice; never a reproach, irony or shouting capitals.
- The **title** states the outcome, the **description** says what to do next; one emoji per title, never decorative inside the body.
- **No gendered agreement** on a person: “tu es propriétaire”, “cette personne”, “l'équipe”, “ce membre” — no “il / elle”, no “cher / chère”, no inclusive dots.
- An **error** explains the cause, recalls the rule and offers the way out; a success thanks and gives the next step (`/ban` points at `/mod logs`, `/ticket create` recalls that the owner can close).
- Shared titles: `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` in `src/ui/embeds.js`). Lists always prefixed with `•` (`bullets()`), closing advice line added by `withHint()`.
- Same vocabulary everywhere: **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (never “raison” as a label), voice **déclencheur**.
## 8. Database (SQLite)
- Engine: `node:sqlite` (`DatabaseSync`), **WAL** mode, foreign keys enabled.
- Migrations: numbered SQL files in `src/database/migrations/`, applied in a transaction and tracked in `schema_migrations` (`npm run db:init`).
- Tables: `guild_settings` (per-guild settings), `notification_channels`, `ticket_categories`, `tickets` (one open ticket per author and category), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (voice triggers and their category), `voice_channels` (owner, lock, limit), `bot_statuses` (bot statuses, global — unique text), `event_logs`, `webhook_deliveries`.
- Data access: one repository per domain (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-repository.js`) — SQL queries never leave that layer.
- Migrations `002-ticket-and-poll-details.sql` (claim tracking `claimed_at` and closing `close_reason`), `003-voice-channels.sql` (temporary voice channels), `004-voice-triggers.sql` (several voice triggers per server) and `005-bot-statuses.sql` (bot statuses edited from a command) complete the initial schema.
- The database holds real data: it is **excluded from git** (`.gitignore`) and must be backed up (`BACKUP_DIR`).
## 9. Logs
- **JSON** format, one line per entry, one file per day: `logs/YYYY-MM-DD.log` + console.
- Levels filtered by `LOG_LEVEL`; errors and warnings go to stderr.
- **Secret masking**: the Discord token, Gitea token and webhook secret are replaced with `***` in every logged line.
- Functional retention: `LOG_RETENTION_DAYS` (purges `event_logs`).
## 10. npm scripts
| Script | Purpose |
| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `npm start` | Starts the bot (`node src/index.js`) |
| `npm run dev` | Starts with automatic reload (`node --watch`) |
| `npm run deploy:commands` | Registers the slash commands on `DISCORD_GUILD_ID` (run it again after adding or changing a command) |
| `npm run db:init` | Creates the SQLite database and applies the migrations |
| `npm run lint` / `npm run lint:fix` | ESLint (check / fix) |
| `npm run format` / `npm run format:check` | Prettier (format / check) |
| `npm run changelog` | Regenerates `CHANGELOG.md` from the Conventional Commits (see §12) |
| `npm run changelog:check` | Fails with exit code 1 when `CHANGELOG.md` is out of date |
| `npm test` | `node:test` unit tests: `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs` |
When something goes wrong: run `npm run deploy:commands` after any command change, check that the **Server Members** intent is enabled, and that the bot has the permissions listed in 3.2 on its target channels.
## 11. Security
- Permissions are checked **server-side** (FWS level + Discord permissions + role hierarchy): the client is never trusted.
- No action is possible on a role or member positioned above the caller.
- Secrets are never committed (`.env` is ignored) nor logged in plain text (automatic masking).
- Gitea webhooks: mandatory HMAC-SHA256 signature, constant-time comparison, 1 MB body limit, duplicate protection on the delivery ID.
- Least privilege tokens; rate limits respected (timeout + controlled retry on transient errors only).
- User input is validated (`setMinValue`/`setMaxValue`/`setMaxLength` on every option).
## 12. Versioning and releases
- **SemVer** (`MAJOR.MINOR.PATCH`): `MAJOR` = breaking change, `MINOR` = backwards-compatible feature, `PATCH` = fix. Current version: see `version` in [`package.json`](package.json) (before `1.0.0` anything may change — a breaking change only bumps `MINOR`, as SemVer §4 states).
- **`CHANGELOG.md` is generated** from the Conventional Commits: `npm run changelog` (`feat:` feeds _Features_, `fix:` feeds _Bug Fixes_, the other types go to _Other changes_). The script also prints the **suggested next version**; `npm run changelog:check` fails when the file is out of date.
- Tags are picked up automatically: every `vX.Y.Z` tag found in the history opens its own section in the changelog, newer commits stay under `[Unreleased]`.
- Generating it is part of the definition of done: the file is never edited by hand.
## 13. Contributing
The rules shared by every FWS repository live in the [organisation `.profile`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md). Summary as applied here:
### Commits
- Messages in **English**, **Conventional Commits** format: `<type>(<scope>): <description>`.
- Allowed types: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`.
- Short imperative title; a **body** is added only to explain the _why_ (context, decision, trade-off).
### Branches and pull requests
1. Create a `type/description` branch **from `main`** (e.g. `feat/ticket-service`, `fix/voice-cleanup`).
2. Commit following the conventions above.
3. Open a **pull request** with a clear title and description, referencing the issue (`Fixes #123`).
4. **At least one reviewer** approves; the tests must pass.
5. Merge with **squash**: 1 PR = 1 clean commit on `main`.
### Work organisation
- Project **Kanban** board: _Backlog / To do_, _In progress_, _In review_, _Done_. One card = one unit of work = one branch + one pull request; a card only moves to _Done_ once its pull request is merged.
- Every bug or request goes through an **issue** (clear title + precise description) with a recommended label: `bug`, `enhancement`, `question`, `good first issue`, `help wanted`. Templates are provided in [`.gitea/ISSUE_TEMPLATE/`](.gitea/ISSUE_TEMPLATE) and [`.gitea/PULL_REQUEST_TEMPLATE.md`](.gitea/PULL_REQUEST_TEMPLATE.md).
- A bug report includes the **reproduction steps**, the **expected** vs **observed** behaviour, the **environment** and useful **logs**.
### Code and documentation
- Files in **kebab-case**, identifiers **in English**, comments **in English** explaining the _why_ (the non-obvious: trade-offs, edge cases, references).
- Check the stack and the dependencies already present before adding a new one (a single runtime dependency here: `discord.js`).
- Before proposing: `npm run lint`, `npm run format:check`, `npm test` and `npm run changelog` must pass.
- **Bilingual** documentation: [`README.md`](README.md) (FR) and [`README.en.md`](README.en.md) (EN) stay in sync; a test enforces it.
- Instructions for AI agents: [`AGENTS.md`](AGENTS.md), updated together with the conventions.
## 14. Production checklist
- [ ] Rename the repository to `fws-discordbot` on Gitea (the organisation `fws-*` convention)
- [ ] Create the Kanban board (_Backlog / To do_, _In progress_, _In review_, _Done_)
- [ ] Fill in the bot statuses (`/status add`, `/status interval`) — the rotation is stored in the database
- [ ] Register the slash commands on the FWS server (`npm run deploy:commands`)
- [ ] Create and configure the Owner, Dev, Staff and User roles (IDs in `.env`)
- [ ] Set the channels: welcome, tickets, notifications, logs
- [ ] Configure each trigger voice channel (`/voice setup`) and check automatic creation/deletion
- [ ] Enable the **Server Members** intent in the developer portal
- [ ] Configure Gitea: least privilege token + webhook with a secret
- [ ] Protect and back up the SQLite database
- [ ] Test the critical paths: end-to-end ticket, warning, poll, Gitea webhook
- [ ] Test the API limits and the error paths
- [ ] Check the embeds on desktop and mobile
- [ ] Fill in the official links and the screenshots (`assets/screenshots/`)
- [ ] Publish the first version `0.1.0` (tag `v0.1.0` then `npm run changelog`)
## 15. Resources
- FWS organisation: `[link to add]`
- FWS Discord server: `[link to add]`
- FWS Arch repository: `[link to add]`
- Gitea instance: `[link to add]`
- FWS documentation: `[link to add]`
- Technical documentation: [`docs/architecture.md`](docs/architecture.md)
- Organisation conventions: [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.en.md)
- Changelog: [`CHANGELOG.md`](CHANGELOG.md) _(generated)_
- Instructions for AI agents: [`AGENTS.md`](AGENTS.md)
- French version of this document: [`README.md`](README.md)
+94 -23
View File
@@ -2,7 +2,11 @@
> 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).
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.
🌍 **Français** · [English version](README.en.md)
Statut : **fonctionnel**. Les 19 commandes sont implémentées (assistance, tickets privés, modération, Gitea, sondages, statistiques, statuts du bot, gestionnaire de salons vocaux), tout comme l'accueil des membres et la diffusion des webhooks Gitea.
Projet conforme aux [conventions de l'organisation FWS](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md) : commits en anglais au format Conventional Commits, branche `type/description`, PR relue puis mergée en squash, SemVer et `CHANGELOG.md` généré depuis les commits.
---
@@ -97,6 +101,8 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare
| `LOG_LEVEL` | `info` | `debug` \| `info` \| `warn` \| `error` |
| `LOG_DIR` | `./logs` | Dossier des logs JSON journaliers |
| `LOG_RETENTION_DAYS` | `30` | Durée de conservation (purge des `event_logs`) |
| `VOICE_EMPTY_GRACE_MS` | `5000` | Délai avant qu'un salon vocal généré devenu vide soit supprimé (`0` = immédiat) |
| `BOT_STATUS_INTERVAL_SECONDS` | `60` | Rythme par défaut de la rotation des statuts du bot (modifiable par `/status interval`) |
### Application Discord
@@ -131,7 +137,7 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare
| `CHANNEL_NOTIF_RELEASES_ID` | Notifications releases |
| `CHANNEL_NOTIF_ERRORS_ID` | Erreurs et incidents |
| `CATEGORY_TICKETS_ID` | Catégorie où sont créés les salons de tickets privés |
| `CHANNEL_VOICE_TRIGGER_ID` | Salon vocal déclencheur : y entrer crée un salon temporaire |
| `CHANNEL_VOICE_TRIGGER_ID` | Salon vocal déclencheur (repli : `/voice setup` gère une liste de déclencheurs) |
| `CATEGORY_VOICE_ID` | Catégorie d'accueil des salons vocaux créés (facultatif) |
### Gitea
@@ -165,7 +171,7 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare
## 5. Commandes slash
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`).
19 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`).
### Niveaux d'accès
@@ -188,6 +194,11 @@ Résolus depuis les rôles configurés dans `.env` (du plus haut au plus bas) :
| `/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) |
| `/status add` | `text` (128 car.), `type`, `url` | **Staff** + *Gérer le serveur* | ✅ | Ajoute un statut à la rotation ; le premier ajouté s'affiche tout de suite |
| `/status list` | — | **Staff** + *Gérer le serveur* | ✅ | Statuts enregistrés : numéro, type, état, rythme de rotation |
| `/status remove` · `enable` · `disable` | `id` | **Staff** + *Gérer le serveur* | ✅ | Retire un statut, le remet en rotation ou le met en pause |
| `/status interval` | `seconds` (5–86 400) | **Staff** + *Gérer le serveur* | ✅ | Rythme de la rotation, appliqué sans redémarrage |
| `/status clear` | — | **Staff** + *Gérer le serveur* | ✅ | Vide la liste et revient à la ligne par défaut |
### Gitea — issues et pull requests
@@ -219,7 +230,7 @@ Catégories disponibles et qui y a accès :
| Catégorie | Visible par |
| --- | --- |
| Support utilisateur | Staff, Owner |
| Aide et support | Staff, Owner |
| Bug | Staff, Dev, Owner |
| Question de développement | Dev, Owner |
| Signalement | Staff, Owner |
@@ -227,13 +238,17 @@ Catégories disponibles et qui y a accès :
### 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é**.
Un serveur peut déclarer **autant de salons déclencheurs que nécessaire** — un par thème (`Dev`, `SIO`, …) — chacun avec sa propre catégorie d'accueil (`/voice setup`) : rejoindre un déclencheur crée un salon vocal privé **en bas de la catégorie de ce déclencheur**, y déplace le membre et lui en donne la propriété. Le salon se gère ensuite depuis le **panneau de contrôle** publié dans son chat (boutons *Renommer*, *Limiter*, *Verrouiller*, *Réclamer*, *Supprimer* et menus *Autoriser*, *Exclure*, *Transférer*) ou avec `/voice`. Le nombre de salons simultanés est **illimité**, et un membre conserve un salon **par déclencheur** : rejoindre à nouveau le même déclencheur le renvoie simplement dans le salon qu'il possède déjà.
Dès que **plus personne** ne reste dans un salon généré, il est supprimé : le délai (5 s par défaut) le laisse survivre à un passage rapide dans un autre salon — réglable par `VOICE_EMPTY_GRACE_MS`, `0` le supprime immédiatement. Un balayage automatique (au démarrage puis toutes les minutes) rattrape les cas où l'événement Discord a été manqué ou la suppression refusée, si bien qu'un salon généré ne peut pas rester vide : soit il est supprimé, soit la tentative est réessayée.
| 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 setup` | `trigger`, `label`, `category`, `template`, `limit`, `panel` | **Staff** | Ajoute (ou met à jour) un salon déclencheur ; sans `category`, celle du salon déclencheur est utilisée |
| `/voice config` · `/voice triggers list` | — | User · **Staff** | Déclencheurs déclarés : catégorie, modèle, limite, état et salons actifs |
| `/voice triggers disable` · `enable` | `trigger` | **Staff** | Désactive un déclencheur (sans perdre sa configuration, y entrer ne crée plus de salon) · le réactive |
| `/voice triggers remove` | `trigger` | **Staff** | Supprime un déclencheur déclaré dans Discord |
| `/voice panel` | `trigger` (défaut : tous) | **Staff** | Republie le panneau d'explication dans les salons déclencheurs |
| `/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 |
@@ -246,6 +261,8 @@ Rejoindre le salon déclencheur (`CHANNEL_VOICE_TRIGGER_ID`, ou `/voice setup`)
| `/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.
>
> `CHANNEL_VOICE_TRIGGER_ID` / `CATEGORY_VOICE_ID` restent un **repli** : un serveur dont le `.env` déclare un déclencheur fonctionne sans `/voice setup`, mais ce déclencheur venu de l'environnement ne peut qu'être désactivé (`/voice triggers disable`), pas supprimé depuis Discord. Changer la catégorie d'un déclencheur ne déplace pas les salons déjà créés.
### Modération
@@ -289,7 +306,8 @@ Légende : ✅ fonctionnel · les erreurs attendues sont renvoyées en message
- **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.
- **Statuts du bot** (`src/services/status/bot-status-service.js`) : la présence affichée sous le nom du bot est une **liste enregistrée en base** (`bot_statuses`), éditable à chaud avec `/status` (ajout, retrait, pause, rythme). La rotation repart du premier statut activé à chaque cycle et le rythme est relu à chaque tour, donc `/status interval` s'applique sans redémarrer le bot. Liste vide → ligne par défaut « les commandes avec /help » plutôt qu'un statut figé.
- **Salons vocaux** (`src/events/voice-state-update.js`) : entrer dans **l'un des salons déclencheurs** crée un salon temporaire en bas de la catégorie de ce déclencheur et y déplace le membre (ou le renvoie dans celui qu'il possède déjà pour ce déclencheur) ; dès que le dernier membre part, le salon est supprimé après un court délai de grâce (`VOICE_EMPTY_GRACE_MS`, 5 s par défaut) qui laisse le temps de changer de salon sans perdre le sien. La suppression n'oublie la ligne en base que lorsque le salon a réellement disparu : une erreur d'API laisse le salon enregistré pour être réessayé. `sweepVoiceChannels()` oublie les salons disparus et supprime les vides — au démarrage, puis toutes les minutes via `startVoiceJanitor()`, ce qui garantit qu'un salon généré ne survit pas vide après un événement manqué ou un échec d'API.
## 7. Architecture
@@ -310,8 +328,9 @@ src/
│ ├── 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)
│ ├── status/ # bot-status-service.js (statuts du bot, validation, rotation)
│ ├── tickets/ # ticket-service.js (salons privés, cycle de vie)
│ └── voice/ # voice-service.js (salons vocaux temporaires, panneau, permissions)
│ └── voice/ # voice-service.js (déclencheurs multiples, salons temporaires, panneau)
├── 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)
@@ -331,13 +350,24 @@ export async function execute(interaction) {}
**Intents utilisés** : `Guilds`, `GuildMembers` *(privilégié — à activer dans le portail)*, `GuildModeration`, `GuildMessages`, `GuildVoiceStates`. `MessageContent` n'est volontairement pas demandé.
### Ton et vocabulaire des messages
Tous les textes visibles dans Discord suivent les mêmes règles, rappelées en tête de `src/ui/embeds.js` (source unique de vérité) :
- **Tutoiement**, phrases courtes, voix active ; jamais de reproche, d'ironie ni de majuscules hurlantes.
- Le **titre** annonce le résultat, la **description** dit quoi faire ensuite ; un seul emoji par titre, jamais décoratif dans le corps.
- **Aucun accord genré** sur une personne : « tu es propriétaire », « cette personne », « l'équipe », « ce membre » — pas de « il / elle », de « cher / chère », ni d'écriture inclusive à points.
- Une **erreur** explique la cause, rappelle la règle et propose la sortie de secours ; un succès remercie et précise la suite (`/ban` renvoie vers `/mod logs`, `/ticket create` rappelle que la personne propriétaire peut fermer).
- Titres partagés : `✅ C'est fait`, `❌ Oups`, `⚠️ Attention`, `💡 Bon à savoir` (`TONE` dans `src/ui/embeds.js`). Listes toujours préfixées de `•` (`bullets()`), dernière ligne de conseil ajoutée par `withHint()`.
- Même vocabulaire partout : **équipe** (staff), **membre**, **salon**, **ticket**, **motif** (jamais « raison » comme libellé), **déclencheur** vocal.
## 8. Base de données (SQLite)
- Moteur : `node:sqlite` (`DatabaseSync`), mode **WAL**, foreign keys activées.
- Migrations : fichiers SQL numérotés dans `src/database/migrations/`, appliqués en transaction et tracés dans `schema_migrations` (`npm run db:init`).
- 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`.
- 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.
- 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.
- Tables : `guild_settings` (paramètres par serveur), `notification_channels`, `ticket_categories`, `tickets` (unicité ticket ouvert/auteur/catégorie), `moderation_actions`, `polls`, `poll_votes`, `voice_triggers` (déclencheurs vocaux et leur catégorie), `voice_channels` (propriétaire, verrouillage, limite), `bot_statuses` (statuts du bot, globaux — unicité du texte), `event_logs`, `webhook_deliveries`.
- Accès données : un repository par domaine (`settings-`, `event-log-`, `ticket-`, `moderation-`, `poll-`, `notification-`, `voice-`, `voice-trigger-`, `bot-status-repository.js`) — les requêtes SQL ne sortent jamais de cette couche.
- Les migrations `002-ticket-and-poll-details.sql` (traçabilité de prise en charge `claimed_at` et de fermeture `close_reason`), `003-voice-channels.sql` (salons vocaux temporaires), `004-voice-triggers.sql` (plusieurs déclencheurs vocaux par serveur) et `005-bot-statuses.sql` (statuts du bot édités en commande) complètent le schéma initial.
- La base contient des données réelles : elle est **exclue de git** (`.gitignore`) et doit être sauvegardée (`BACKUP_DIR`).
## 9. Logs
@@ -357,7 +387,9 @@ export async function execute(interaction) {}
| `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` |
| `npm run changelog` | Regénère `CHANGELOG.md` depuis les commits Conventional Commits (voir §12) |
| `npm run changelog:check` | Vérifie que `CHANGELOG.md` est à jour (code de sortie 1 sinon) |
| `npm test` | Tests unitaires `node:test` : `modules`, `permissions`, `poll-service`, `notifications`, `pending-actions`, `repositories`, `voice`, `bot-status`, `database`, `docs` |
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.
@@ -370,20 +402,54 @@ En cas de souci : `npm run deploy:commands` après chaque changement de commande
- 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
## 12. Versionnage et releases
- 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).
- **SemVer** (`MAJEUR.MINEUR.PATCH`) : `MAJEUR` = changement incompatible, `MINEUR` = fonctionnalité rétrocompatible, `PATCH` = correction. Version courante : voir `version` dans [`package.json`](package.json) (avant `1.0.0`, tout peut changer — un changement incompatible ne fait monter que le `MINEUR`, conformément au §4 de SemVer).
- **`CHANGELOG.md` est généré** depuis les commits Conventional Commits : `npm run changelog` (les `feat:` alimentent *Features*, les `fix:` *Bug Fixes*, les autres types *Other changes*). Le script affiche aussi la **version suivante suggérée** ; `npm run changelog:check` échoue si le fichier n'est pas à jour.
- Les tags sont repris automatiquement : chaque tag `vX.Y.Z` trouvé dans l'historique ouvre sa propre section dans le changelog, les commits plus récents restent sous `[Unreleased]`.
- La génération fait partie de la définition de « terminé » : le fichier ne se modifie pas à la main.
## 13. Checklist de mise en production
## 13. Contribution
Les règles communes à tous les repos FWS sont décrites dans le [`.profile` de l'organisation](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md). Résumé appliqué ici :
### Commits
- Messages en **anglais**, format **Conventional Commits** : `<type>(<scope>): <description>`.
- Types autorisés : `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`.
- Titre court et impératif ; un **corps** est ajouté seulement pour expliquer le *pourquoi* (contexte, décision, compromis).
### Branches et pull requests
1. Créer une branche `type/description` **depuis `main`** (ex. `feat/ticket-service`, `fix/voice-cleanup`).
2. Commiter selon les conventions ci-dessus.
3. Ouvrir une **pull request** avec un titre et une description clairs, en référençant l'issue (`Fixes #123`).
4. **Au moins un reviewer** valide ; les tests doivent passer.
5. Merger en **squash** : 1 PR = 1 commit propre sur `main`.
### Organisation du travail
- Tableau **Kanban** du projet : *Backlog / À faire*, *En cours*, *En revue*, *Terminé*. Une carte = une unité de travail = une branche + une PR ; une carte ne passe en *Terminé* qu'une fois la PR mergée.
- Toute anomalie ou demande passe par une **issue** (titre clair + description précise) avec un label recommandé : `bug`, `enhancement`, `question`, `good first issue`, `help wanted`. Les modèles sont fournis dans [`.gitea/ISSUE_TEMPLATE/`](.gitea/ISSUE_TEMPLATE) et [`.gitea/PULL_REQUEST_TEMPLATE.md`](.gitea/PULL_REQUEST_TEMPLATE.md).
- Un bug se décrit avec les **étapes de reproduction**, le **comportement attendu** vs **observé**, l'**environnement** et les **logs** utiles.
### Code et documentation
- Fichiers en **kebab-case**, identifiants **en anglais**, commentaires **en anglais** expliquant le *pourquoi* (le non-évident : compromis, cas limites, références).
- Vérifier la stack et les dépendances déjà présentes avant d'en ajouter une nouvelle (une seule dépendance runtime ici : `discord.js`).
- Avant de proposer : `npm run lint`, `npm run format:check`, `npm test` et `npm run changelog` doivent passer.
- Documentation **bilingue** : [`README.md`](README.md) (FR) et [`README.en.md`](README.en.md) (EN) restent synchronisés ; un test le vérifie.
- Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md), à mettre à jour avec les conventions.
## 14. Checklist de mise en production
- [ ] Renommer le dépôt en `fws-discordbot` côté Gitea (convention `fws-*` de l'organisation)
- [ ] Créer le tableau Kanban (*Backlog / À faire*, *En cours*, *En revue*, *Terminé*)
- [ ] Renseigner les statuts du bot (`/status add`, `/status interval`) — la rotation est enregistrée en base
- [ ] 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
- [ ] Configurer chaque salon vocal déclencheur (`/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
@@ -391,8 +457,9 @@ En cas de souci : `npm run deploy:commands` après chaque changement de commande
- [ ] 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/`)
- [ ] Publier la première version `0.1.0` (tag `v0.1.0` puis `npm run changelog`)
## 14. Ressources
## 15. Ressources
- Organisation FWS : `[lien à ajouter]`
- Serveur Discord FWS : `[lien à ajouter]`
@@ -400,3 +467,7 @@ En cas de souci : `npm run deploy:commands` après chaque changement de commande
- Instance Gitea : `[lien à ajouter]`
- Documentation FWS : `[lien à ajouter]`
- Documentation technique : [`docs/architecture.md`](docs/architecture.md)
- Conventions de l'organisation : [`.profile/README.md`](https://gitea.nocode-var.tech/FWS/.profile/src/branch/main/README.md)
- Journal des modifications : [`CHANGELOG.md`](CHANGELOG.md) *(généré)*
- Instructions pour les agents IA : [`AGENTS.md`](AGENTS.md)
- Version anglaise de ce document : [`README.en.md`](README.en.md)
+2
View File
@@ -13,6 +13,8 @@
"dev": "node --watch src/index.js",
"deploy:commands": "node scripts/deploy-commands.js",
"db:init": "node scripts/init-database.js",
"changelog": "node scripts/generate-changelog.js",
"changelog:check": "node scripts/generate-changelog.js --check",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env node
import { execFileSync } from 'node:child_process';
import { readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* Builds CHANGELOG.md from the Conventional Commits of the history, as the FWS conventions
* require: `feat` and `fix` feed the Features and Bug Fixes sections, the other types are
* grouped under "Other changes". The file is generated, so run this script instead of editing it.
*
* Usage: node scripts/generate-changelog.js [--check]
* --check exits with code 1 when CHANGELOG.md is out of date (used by CI and tests)
*/
const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const changelogPath = path.join(rootDir, 'CHANGELOG.md');
const checkOnly = process.argv.includes('--check');
/** Section order and titles; anything else falls into "Other changes". */
const SECTIONS = [
{ title: 'Features', test: (type) => type === 'feat' },
{ title: 'Bug Fixes', test: (type) => type === 'fix' },
{ title: 'Performance', test: (type) => type === 'perf' },
{
title: 'Other changes',
test: (type) => type !== 'feat' && type !== 'fix' && type !== 'perf',
},
];
const OTHER_LABELS = {
build: 'build',
chore: 'chore',
ci: 'ci',
docs: 'docs',
refactor: 'refactor',
revert: 'revert',
style: 'style',
test: 'test',
};
const git = (args) => execFileSync('git', args, { cwd: rootDir, encoding: 'utf8' });
function readCommits() {
// One record per commit, fields separated by unit separators so bodies stay readable.
const raw = git([
'log',
'--no-merges',
'--date=short',
'--format=%H%x1f%ad%x1f%s%x1f%b%x1f%D%x1e',
// A commit that only rewrites the changelog must not appear in it, otherwise `--check`
// could never be green once that file is committed.
'--',
'.',
':(exclude)CHANGELOG.md',
]);
return raw
.split('\x1e')
.map((record) => record.trim())
.filter(Boolean)
.map((record) => {
const [hash, date, subject, body = '', decoration = ''] = record.split('\x1f');
const match = /^(?<type>[a-z]+)(?:\((?<scope>[^)]*)\))?(?<breaking>!)?: (?<description>.+)$/.exec(
subject.trim(),
);
const breaking = Boolean(match?.groups.breaking) || /BREAKING CHANGE/.test(body);
return {
hash,
date,
subject: subject.trim(),
type: match?.groups.type ?? 'other',
scope: match?.groups.scope ?? null,
description: match?.groups.description ?? subject.trim(),
breaking,
tags: decoration
.split(',')
.map((ref) => ref.trim().replace(/^tag: /, ''))
.filter((ref) => /^v?\d+\.\d+\.\d+/.test(ref)),
};
});
}
function entryLine(commit) {
const scope = commit.scope ? `**${commit.scope}:** ` : '';
const breaking = commit.breaking ? '**BREAKING** ' : '';
const label = commit.type === 'other' ? '' : `_(${OTHER_LABELS[commit.type] ?? commit.type})_ `;
const detail = commit.type === 'other' ? commit.subject : commit.description;
return `- ${breaking}${scope}${label}${detail} ([${commit.hash.slice(0, 7)}])`;
}
/** A commit without a tag belongs to "Unreleased"; a tag closes the section it points to. */
function groupByRelease(commits) {
const releases = [];
let current = { title: 'Unreleased', date: null, commits: [] };
for (const commit of commits) {
current.commits.push(commit);
for (const tag of commit.tags) {
releases.push({ title: tag, date: commit.date, commits: current.commits });
current = { title: 'Unreleased', date: null, commits: [] };
}
}
if (current.commits.length > 0) releases.push(current);
return releases;
}
function renderRelease(release) {
const heading = release.date ? `## [${release.title}] — ${release.date}` : `## [${release.title}]`;
const lines = [heading];
for (const section of SECTIONS) {
const entries = release.commits.filter((commit) => section.test(commit.type));
if (entries.length === 0) continue;
lines.push('', `### ${section.title}`, ...entries.map(entryLine));
}
if (release.commits.length === 0) lines.push('', '_Nothing yet._');
return lines.join('\n');
}
/** SemVer hint from the commits since the last release: breaking > feature > fix. */
function suggestVersion(commits) {
const version = JSON.parse(readFileSync(path.join(rootDir, 'package.json'), 'utf8')).version;
const [major, minor, patch] = version.split('.').map(Number);
const breaking = commits.some((commit) => commit.breaking);
const feature = commits.some((commit) => commit.type === 'feat');
// SemVer §4: below 1.0.0 anything may change, so a breaking change only bumps the minor.
if (major === 0) return breaking || feature ? `0.${minor + 1}.0` : `0.${minor}.${patch + 1}`;
if (breaking) return `${major + 1}.0.0`;
if (feature) return `${major}.${minor + 1}.0`;
return `${major}.${minor}.${patch + 1}`;
}
function buildChangelog(commits) {
const releases = groupByRelease(commits);
return [
'# Changelog',
'',
'All notable changes to this project are documented in this file. It is **generated from the',
'Conventional Commits** of the history: run `npm run changelog` instead of editing it by hand.',
'The project follows [Semantic Versioning](https://semver.org/).',
'',
releases.map(renderRelease).join('\n\n'),
'',
].join('\n');
}
const commits = readCommits();
const content = buildChangelog(commits);
const unreleased = commits.filter((commit) => !commit.tags.length);
const previous = (() => {
try {
return readFileSync(changelogPath, 'utf8');
} catch {
return null;
}
})();
if (checkOnly) {
if (previous !== content) {
console.error('CHANGELOG.md is out of date: run `npm run changelog`.');
process.exit(1);
}
console.log('CHANGELOG.md is up to date.');
process.exit(0);
}
writeFileSync(changelogPath, content);
console.log(`Wrote ${path.relative(rootDir, changelogPath)} from ${commits.length} commits.`);
console.log(`Suggested next version: ${suggestVersion(unreleased)}`);
+6 -6
View File
@@ -1,7 +1,7 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { parseChoices } from '../../services/polls/poll-service.js';
import { baseEmbed } from '../../ui/embeds.js';
import { baseEmbed, bullets } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
@@ -62,7 +62,7 @@ export async function execute(interaction) {
if (subcommand === 'coinflip') {
const result = pick(['Pile', 'Face']);
await interaction.reply({
embeds: [baseEmbed(COLORS.info).setTitle('Pile ou face').setDescription(`🪙 ${result} !`)],
embeds: [baseEmbed(COLORS.info).setTitle('🪙 Pile ou face').setDescription(`**${result}** !`)],
});
return;
}
@@ -73,8 +73,8 @@ export async function execute(interaction) {
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle(`Lancer de dé (d${sides})`)
.setDescription(`🎲 Tu obtiens **${roll}** !`),
.setTitle(`🎲 Lancer de dé (d${sides})`)
.setDescription(`Tu obtiens **${roll}** !`),
],
});
return;
@@ -99,8 +99,8 @@ export async function execute(interaction) {
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle('Choix aléatoire')
.addFields({ name: 'Options', value: options.map((option) => `• ${option}`).join('\n') })
.setTitle('🎯 Choix aléatoire')
.addFields({ name: 'Options', value: bullets(options) })
.setDescription(`Je choisis : **${pick(options)}**`),
],
});
+18 -5
View File
@@ -13,20 +13,29 @@ export const data = new SlashCommandBuilder()
.setName('create')
.setDescription('Créer un sondage')
.addStringOption((option) =>
option.setName('question').setDescription('Question').setRequired(true).setMaxLength(200),
option.setName('question').setDescription('Question posée').setRequired(true).setMaxLength(200),
)
.addStringOption((option) =>
option.setName('choices').setDescription('Choix séparés par ";" (2 à 10)').setRequired(true),
option
.setName('choices')
.setDescription('Propositions séparées par des « ; » (2 à 10)')
.setRequired(true),
)
.addIntegerOption((option) =>
option.setName('minutes').setDescription('Durée en minutes').setMinValue(1).setMaxValue(10_080),
option
.setName('minutes')
.setDescription('Durée avant fermeture automatique, en minutes')
.setMinValue(1)
.setMaxValue(10_080),
),
)
.addSubcommand((sub) =>
sub
.setName('close')
.setDescription('Fermer un sondage')
.addIntegerOption((option) => option.setName('id').setDescription('ID du sondage').setRequired(true)),
.addIntegerOption((option) =>
option.setName('id').setDescription('Numéro du sondage (affiché dans l’embed)').setRequired(true),
),
);
/** Polls are published in the current channel and voted with buttons (M10). */
@@ -44,6 +53,10 @@ export async function execute(interaction) {
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}>.`)],
embeds: [
successEmbed(
`Ton sondage **#${pollId}** est en ligne dans <#${interaction.channelId}> : tout le monde vote avec les boutons.`,
),
],
});
}
+7 -5
View File
@@ -21,7 +21,7 @@ export const data = new SlashCommandBuilder()
const discordStatsEmbed = (interaction) => {
const guild = interaction.guild;
return baseEmbed()
.setTitle(`Statistiques — ${guild.name}`)
.setTitle(`📊 Statistiques — ${guild.name}`)
.setThumbnail(guild.iconURL({ size: 128 }))
.addFields(
{ name: 'Membres', value: String(guild.memberCount), inline: true },
@@ -48,9 +48,9 @@ async function giteaStatsEmbed() {
const release = asList(releases)[0];
const embed = baseEmbed(COLORS.gitea)
.setTitle('Activité Gitea')
.setTitle('📈 Activité Gitea')
.setURL(repositoryUrl())
.setDescription(latestCommits || 'Aucun commit récent.')
.setDescription(latestCommits || 'Aucun commit récent pour le moment.')
.addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
@@ -67,7 +67,7 @@ function fwsStatsEmbed(interaction) {
const total = actions.reduce((sum, row) => sum + row.count, 0);
return baseEmbed(COLORS.gitea)
.setTitle('Indicateurs FWS')
.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 },
@@ -107,7 +107,9 @@ export async function execute(interaction) {
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`.'),
errorEmbed(
'Les statistiques Gitea ne répondent pas. Réessaie dans un instant — si ça continue, l’équipe peut vérifier `GITEA_URL` et `GITEA_TOKEN`. Le reste du bot fonctionne normalement.',
),
],
});
}
+36 -16
View File
@@ -24,8 +24,10 @@ export const data = new SlashCommandBuilder()
.addSubcommand((sub) =>
sub
.setName('changelog')
.setDescription("Changements d'une version")
.addStringOption((option) => option.setName('version').setDescription('Version (dernière par défaut)')),
.setDescription('Nouveautés d’une version')
.addStringOption((option) =>
option.setName('version').setDescription('Version souhaitée (la dernière par défaut)'),
),
);
const officialLinks = () => [
@@ -62,7 +64,7 @@ async function showInfo(interaction) {
const configured = readSetting(interaction.guildId, 'fws.info', DEFAULT_PRESENTATION);
const description = typeof configured === 'string' && configured ? configured : DEFAULT_PRESENTATION;
await interaction.reply({
embeds: [baseEmbed().setTitle('FWS & FWS Arch').setDescription(description)],
embeds: [baseEmbed().setTitle('🚀 FWS & FWS Arch').setDescription(description)],
components: linkButtons(officialLinks()),
});
}
@@ -73,8 +75,10 @@ async function showVersion(interaction) {
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.'),
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: errorEmbed(
'La partie Gitea n’est pas encore configurée : je ne peux pas lire la dernière version. L’équipe peut la renseigner dans le `.env`.',
),
],
});
return;
@@ -87,8 +91,8 @@ async function showVersion(interaction) {
await interaction.editReply({
embeds: [
fallback
? infoEmbed('Version FWS Arch', `Version publiée : **${fallback}**`)
: infoEmbed('Version FWS Arch', 'Aucune release publiée pour le moment.'),
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: infoEmbed('📦 Version FWS Arch', 'Aucune release publiée pour le moment.'),
],
});
return;
@@ -123,15 +127,15 @@ async function showStatus(interaction) {
const uptime = Math.floor(process.uptime());
const embed = baseEmbed(COLORS.info)
.setTitle('État des services')
.setTitle('🩺 État des services')
.addFields(
{
name: 'API Gitea',
value: !giteaConfigured
? '⚙️ Non configurée'
? '⚙️ Pas encore configurée'
: giteaReachable
? `✅ En ligne — ${repositoryUrl()}`
: '❌ Injoignable',
: '❌ Injoignable pour le moment',
inline: false,
},
{
@@ -142,7 +146,9 @@ async function showStatus(interaction) {
{
name: 'Base SQLite',
value:
openTickets === null ? '❌ Indisponible' : `✅ Accessible — ${openTickets} ticket(s) ouvert(s)`,
openTickets === null
? '❌ Indisponible pour le moment'
: `✅ Accessible — ${openTickets} ticket(s) ouvert(s)`,
inline: false,
},
{
@@ -150,7 +156,7 @@ async function showStatus(interaction) {
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>` },
{ name: 'En ligne depuis', value: `<t:${Math.floor((Date.now() - uptime * 1000) / 1000)}:R>` },
);
await interaction.editReply({ embeds: [embed] });
@@ -160,7 +166,11 @@ 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.')],
embeds: [
errorEmbed(
'La partie Gitea n’est pas encore configurée : le changelog arrivera dès qu’elle sera branchée.',
),
],
});
return;
}
@@ -170,7 +180,12 @@ async function showChangelog(interaction) {
const release = version ? await gitea.getReleaseByTag(version) : await latestRelease();
if (!release) {
await interaction.editReply({
embeds: [infoEmbed('Changelog', `Aucune release trouvée pour **${version}**.`)],
embeds: [
infoEmbed(
'📜 Changelog',
`Je ne trouve aucune release pour **${version}** : \`/gitea release\` liste les versions existantes.`,
),
],
});
return;
}
@@ -183,7 +198,12 @@ async function showChangelog(interaction) {
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.`)],
embeds: [
infoEmbed(
'📜 Changelog',
`Cette version **${version}** n’existe pas dans les releases Gitea : \`/gitea release\` liste celles qui existent.`,
),
],
});
return;
}
@@ -199,7 +219,7 @@ export async function execute(interaction) {
return;
case 'links':
await interaction.reply({
embeds: [baseEmbed().setTitle('Liens officiels FWS')],
embeds: [baseEmbed().setTitle('🔗 Liens officiels FWS')],
components: linkButtons(officialLinks()),
});
return;
+7 -3
View File
@@ -1,7 +1,7 @@
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js';
import { getAccessLevel } from '../../core/permissions.js';
import { baseEmbed } from '../../ui/embeds.js';
import { baseEmbed, bullets } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
@@ -16,6 +16,10 @@ export async function execute(interaction) {
.map((command) => `\`/${command.data.name}\` — ${command.data.description}`)
.sort();
const embed = baseEmbed().setTitle('Commandes FWS-Bot').setDescription(lines.join('\n'));
const embed = baseEmbed()
.setTitle('🤖 Tes commandes')
.setDescription(
`Tu es au niveau **${ACCESS_LABELS[level]}**. Voici ce que tu peux lancer :\n\n${bullets(lines)}`,
);
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
}
+153
View File
@@ -0,0 +1,153 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
addBotStatus,
applyBotStatus,
applyStatusIfAlone,
clearBotStatusList,
FALLBACK_STATUS,
formatSeconds,
removeBotStatus,
ROTATION_MAX_SECONDS,
ROTATION_MIN_SECONDS,
saveRotationSeconds,
STATUS_TYPE_CHOICES,
statusAddedEmbed,
statusListEmbed,
toggleBotStatus,
} from '../../services/status/bot-status-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const idOption = (option) =>
option.setName('id').setDescription('Numéro affiché par /status list').setRequired(true).setMinValue(1);
export const data = new SlashCommandBuilder()
.setName('status')
.setDescription('Statuts affichés sous le nom du bot')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addSubcommand((sub) =>
sub
.setName('add')
.setDescription('Ajouter un statut à la rotation')
.addStringOption((option) =>
option
.setName('text')
.setDescription('Texte affiché, par exemple « les tickets ouverts en un clic »')
.setRequired(true)
.setMaxLength(128),
)
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type d’activité (regarde par défaut)')
.addChoices(...STATUS_TYPE_CHOICES),
)
.addStringOption((option) =>
option.setName('url').setDescription('Lien exigé par le type « en direct »'),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Voir les statuts enregistrés'))
.addSubcommand((sub) =>
sub.setName('remove').setDescription('Retirer un statut de la rotation').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub.setName('enable').setDescription('Remettre un statut en rotation').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub.setName('disable').setDescription('Mettre un statut en pause').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub
.setName('interval')
.setDescription('Rythme de la rotation')
.addIntegerOption((option) =>
option
.setName('seconds')
.setDescription('Secondes entre deux changements')
.setRequired(true)
.setMinValue(ROTATION_MIN_SECONDS)
.setMaxValue(ROTATION_MAX_SECONDS),
),
)
.addSubcommand((sub) =>
sub.setName('clear').setDescription('Vider la liste et revenir au statut par défaut'),
);
const reply = (interaction, embed) => interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
/** The bot presence is global, but the rotation delay is stored per guild like other settings (M15). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'list') {
await reply(interaction, statusListEmbed({ guildId: interaction.guildId }));
return;
}
if (subcommand === 'add') {
const status = addBotStatus({
text: interaction.options.getString('text', true),
type: interaction.options.getString('type') ?? 'watching',
url: interaction.options.getString('url'),
createdBy: interaction.user.id,
});
// A single status is shown right away: an addition should never wait for the next turn.
const applied = applyStatusIfAlone(interaction.client) !== null;
await reply(interaction, statusAddedEmbed(status, { applied }));
return;
}
if (subcommand === 'interval') {
const seconds = saveRotationSeconds(
interaction.options.getInteger('seconds', true),
interaction.guildId,
interaction.user.id,
);
await reply(
interaction,
successEmbed(
`C’est noté : les statuts changeront toutes les **${formatSeconds(seconds)}**. Ça prend effet tout de suite, sans redémarrage.`,
),
);
return;
}
if (subcommand === 'clear') {
const removed = clearBotStatusList();
applyBotStatus(interaction.client);
await reply(
interaction,
successEmbed(
removed === 0
? `La liste était déjà vide : j’affiche « ${FALLBACK_STATUS.text} ».`
: `C’est fait : ${removed} statut(s) supprimé(s). J’affiche de nouveau « ${FALLBACK_STATUS.text} » en attendant les prochains.`,
),
);
return;
}
const id = interaction.options.getInteger('id', true);
if (subcommand === 'remove') {
const status = removeBotStatus(id);
await reply(
interaction,
successEmbed(`C’est fait : « ${status.text} » ne fait plus partie de la rotation.`),
);
return;
}
const enabled = subcommand === 'enable';
const status = toggleBotStatus(id, enabled);
if (enabled) applyStatusIfAlone(interaction.client);
await reply(
interaction,
successEmbed(
enabled
? `« ${status.text} » reprend sa place dans la rotation.`
: `« ${status.text} » est en pause : il reste dans la liste, mais ne s’affiche plus.`,
),
);
}
+12 -11
View File
@@ -2,7 +2,7 @@ import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.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';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
@@ -13,13 +13,14 @@ export const data = new SlashCommandBuilder()
.addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles'));
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');
bullets(
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 ?? 'un compte inconnu'}*`;
}),
);
/** Read-only summaries of the repository (M5-T06 / M5-T07). */
export async function execute(interaction) {
@@ -35,7 +36,7 @@ export async function execute(interaction) {
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('Releases FWS Arch')
.setTitle('📦 Releases FWS Arch')
.setURL(repositoryUrl())
.setDescription(
releases
@@ -59,9 +60,9 @@ export async function execute(interaction) {
]);
const embed = baseEmbed(COLORS.gitea)
.setTitle('Activité récente')
.setTitle('📈 Activité récente')
.setURL(repositoryUrl())
.setDescription(commitLines(commits) || 'Aucun commit récent.')
.setDescription(commitLines(commits) || 'Aucun commit récent pour le moment.')
.addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
+17 -8
View File
@@ -8,7 +8,7 @@ import {
openIssueModal,
replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
@@ -24,7 +24,7 @@ export const data = new SlashCommandBuilder()
.setName('view')
.setDescription('Afficher une issue')
.addIntegerOption((option) =>
option.setName('number').setDescription("Numéro de l'issue").setRequired(true).setMinValue(1),
option.setName('number').setDescription('Numéro de l’issue').setRequired(true).setMinValue(1),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les issues ouvertes'));
@@ -44,24 +44,33 @@ export async function execute(interaction) {
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.');
if (!issue?.number) {
throw new UserFacingError(
'Je ne trouve pas cette issue sur Gitea : vérifie son numéro avec `/issue list`.',
);
}
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. 🎉')] });
await interaction.editReply({
embeds: [successEmbed('Aucune issue ouverte : rien en attente, tout est traité 🎉')],
});
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('Issues ouvertes')
.setTitle('🐙 Issues ouvertes')
.setURL(`${repositoryUrl()}/issues`)
.setDescription(
issues
.map((issue) => `**#${issue.number}** ${issue.title} — *${issue.user?.login ?? 'inconnu'}*`)
.join('\n'),
bullets(
issues.map(
(issue) =>
`**#${issue.number}** ${issue.title} — ouverte par *${issue.user?.login ?? 'un compte inconnu'}*`,
),
),
)
.setFooter({ text: `${issues.length} issue(s) affichée(s)` });
await interaction.editReply({ embeds: [embed] });
+27 -11
View File
@@ -8,7 +8,7 @@ import {
openPullRequestModal,
replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = { create: ACCESS_LEVELS.DEV };
@@ -20,8 +20,18 @@ export const data = new SlashCommandBuilder()
sub
.setName('create')
.setDescription('Créer une pull request')
.addStringOption((option) => option.setName('head').setDescription('Branche source').setRequired(true))
.addStringOption((option) => option.setName('base').setDescription('Branche cible').setRequired(true)),
.addStringOption((option) =>
option
.setName('head')
.setDescription('Branche source, celle qui apporte les changements')
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('base')
.setDescription('Branche cible, celle qui reçoit les changements')
.setRequired(true),
),
)
.addSubcommand((sub) =>
sub
@@ -48,28 +58,34 @@ export async function execute(interaction) {
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.');
if (!pull?.number) {
throw new UserFacingError(
'Je ne trouve pas cette pull request sur Gitea : vérifie son numéro avec `/pr list`.',
);
}
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.')] });
await interaction.editReply({
embeds: [successEmbed('Aucune pull request ouverte : rien à relire pour le moment 🎉')],
});
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('Pull requests ouvertes')
.setTitle('🐙 Pull requests ouvertes')
.setURL(`${repositoryUrl()}/pulls`)
.setDescription(
pulls
.map(
bullets(
pulls.map(
(pull) =>
`**#${pull.number}** ${pull.title} — ${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'} ` +
`(*${pull.user?.login ?? 'inconnu'}*)`,
)
.join('\n'),
`(proposée par *${pull.user?.login ?? 'un compte inconnu'}*)`,
),
),
)
.setFooter({ text: `${pulls.length} PR affichée(s)` });
await interaction.editReply({ embeds: [embed] });
+8 -4
View File
@@ -14,11 +14,11 @@ export const data = new SlashCommandBuilder()
.setDescription('Bannir un membre')
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500))
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500))
.addIntegerOption((option) =>
option
.setName('delete_days')
.setDescription('Supprimer les messages des N derniers jours')
.setDescription('Supprimer aussi les messages des N derniers jours (0 à 7)')
.setMinValue(0)
.setMaxValue(7),
);
@@ -41,12 +41,16 @@ export async function execute(interaction) {
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await interaction.guild.bans.create(user.id, {
reason: reason ?? `Banni par ${interaction.user.tag}`,
reason: reason ?? `Bannissement demandé 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.`)],
embeds: [
successEmbed(
`C’est fait : **${user.tag}** ne peut plus revenir sur le serveur. L’historique reste consultable avec \`/mod logs\`.`,
),
],
});
}
+8 -4
View File
@@ -13,7 +13,7 @@ export const data = new SlashCommandBuilder()
.addIntegerOption((option) =>
option
.setName('amount')
.setDescription('Nombre de messages')
.setDescription('Nombre de messages à supprimer (1 à 100)')
.setRequired(true)
.setMinValue(1)
.setMaxValue(100),
@@ -23,7 +23,9 @@ export const data = new SlashCommandBuilder()
export async function execute(interaction) {
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.');
throw new UserFacingError(
'Je ne peux pas supprimer plusieurs messages d’un coup ici : lance la commande dans un salon textuel.',
);
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
@@ -37,8 +39,10 @@ export async function execute(interaction) {
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._' : ''),
`C’est nettoyé : ${deleted.size} message(s) supprimé(s) dans <#${interaction.channelId}>.` +
(deleted.size < amount
? '\n_Discord conserve les messages de plus de 14 jours : ils n’ont pas pu être retirés._'
: ''),
),
],
});
+7 -3
View File
@@ -15,7 +15,7 @@ export const data = new SlashCommandBuilder()
.setDescription('Expulser un membre du serveur')
.setDefaultMemberPermissions(PermissionFlagsBits.KickMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500));
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Expels the member after the hierarchy checks (M8-T03 / M8-T06). */
export async function execute(interaction) {
@@ -31,10 +31,14 @@ export async function execute(interaction) {
embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })],
})
.catch(() => {});
await target.kick(reason ?? `Expulsé par ${interaction.user.tag}`);
await target.kick(reason ?? `Expulsion demandée 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.`)],
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** ne fait plus partie du serveur. La personne peut revenir avec une nouvelle invitation.`,
),
],
});
}
+7 -5
View File
@@ -25,7 +25,7 @@ function formatEntry(row) {
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'}`
`↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}`
);
}
@@ -41,13 +41,15 @@ export async function execute(interaction) {
const embed =
actions.length === 0
? infoEmbed(
'Historique de modération',
user ? `Aucune action enregistrée contre ${user}.` : 'Aucune action enregistrée sur ce serveur.',
'📜 Historique de modération',
user
? `Rien à signaler concernant ${user} : aucune action de modération enregistrée.`
: 'Aucune action de modération enregistrée sur ce serveur, tout est calme.',
)
: baseEmbed(COLORS.moderation)
.setTitle(user ? `Historique de ${user.tag}` : 'Dernières actions de modération')
.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)` });
.setFooter({ text: `${actions.length} action(s) affichée(s)` });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
}
+5 -3
View File
@@ -19,12 +19,12 @@ export const data = new SlashCommandBuilder()
.addIntegerOption((option) =>
option
.setName('minutes')
.setDescription('Durée en minutes')
.setDescription('Durée de la sanction, en minutes')
.setRequired(true)
.setMinValue(1)
.setMaxValue(40_320),
)
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500));
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */
export async function execute(interaction) {
@@ -53,7 +53,9 @@ export async function execute(interaction) {
await interaction.editReply({
embeds: [
successEmbed(`**${target.user.tag}** est réduit au silence pendant **${formatDuration(durationMs)}**.`),
successEmbed(
`C’est fait : **${target.user.tag}** est en exclusion temporaire pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`,
),
],
});
}
+15 -7
View File
@@ -6,7 +6,7 @@ import {
removeNotificationChannel,
setNotificationChannel,
} from '../../database/repositories/notification-repository.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
@@ -58,7 +58,9 @@ export async function execute(interaction) {
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}>.`)],
embeds: [
successEmbed(`C’est noté : les notifications **${type}** partent maintenant dans <#${channel.id}>.`),
],
flags: MessageFlags.Ephemeral,
});
return;
@@ -67,9 +69,15 @@ export async function execute(interaction) {
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}**.`);
if (!removed) {
throw new UserFacingError(
`Le type **${type}** utilise déjà la configuration par défaut : il n’y a rien à retirer.`,
);
}
await interaction.reply({
embeds: [successEmbed(`Les notifications **${type}** repassent à la configuration par défaut.`)],
embeds: [
successEmbed(`C’est fait : les notifications **${type}** repassent à la configuration par défaut.`),
],
flags: MessageFlags.Ephemeral,
});
return;
@@ -81,15 +89,15 @@ export async function execute(interaction) {
const lines = NOTIFICATION_TYPES.map((type) => {
const channelId = overrides.get(type);
return channelId
? `\`${type}\` → <#${channelId}> _(personnalisé)_`
? `\`${type}\` → <#${channelId}> _(choisi sur ce serveur)_`
: `\`${type}\` → _configuration par défaut_`;
});
await interaction.reply({
embeds: [
baseEmbed()
.setTitle('Salons de notification')
.setDescription(lines.join('\n'))
.setTitle('🔔 Salons de notification')
.setDescription(`${bullets(lines)}\n\nPour changer une destination : \`/notify set\`.`)
.setFooter({ text: `Serveur ${interaction.guildId}` }),
],
flags: MessageFlags.Ephemeral,
+26 -10
View File
@@ -19,9 +19,12 @@ export const data = new SlashCommandBuilder()
.addStringOption((option) =>
option
.setName('action')
.setDescription('Action')
.setDescription('Ajouter ou retirer le rôle')
.setRequired(true)
.addChoices({ name: 'Ajouter', value: 'add' }, { name: 'Retirer', value: 'remove' }),
.addChoices(
{ name: 'Ajouter le rôle', value: 'add' },
{ name: 'Retirer le rôle', value: 'remove' },
),
),
);
@@ -33,26 +36,37 @@ export async function execute(interaction) {
const adding = action === 'add';
if (role.id === interaction.guild.roles.everyone.id) {
throw new UserFacingError('Le rôle @everyone ne peut pas être attribué.');
throw new UserFacingError(
'Le rôle @everyone ne s’attribue pas : il est porté par tout le monde à la fois.',
);
}
if (role.managed) {
throw new UserFacingError('Ce rôle est géré par une intégration et ne peut pas être modifié.');
throw new UserFacingError(
'Ce rôle appartient à une intégration : Discord le gère tout seul, je ne peux pas le modifier.',
);
}
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.');
throw new UserFacingError(
'Je ne peux pas gérer ce rôle : il est placé plus haut que le mien. Remonte mon rôle dans la hiérarchie du serveur, et je m’en occupe.',
);
}
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}.`);
if (adding && hasRole) {
throw new UserFacingError(`Rien à faire : **${target.user.tag}** porte déjà le rôle ${role}.`);
}
if (!adding && !hasRole) {
throw new UserFacingError(`Rien à retirer : **${target.user.tag}** n’a 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.');
throw new UserFacingError(
'Ce rôle est au même niveau (ou plus haut) que le tien : je ne peux pas y toucher. Demande à quelqu’un de plus haut dans la hiérarchie.',
);
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
@@ -69,7 +83,9 @@ export async function execute(interaction) {
});
await interaction.editReply({
embeds: [
successEmbed(`Le rôle ${role} a été ${adding ? 'ajouté à' : 'retiré de'} **${target.user.tag}**.`),
successEmbed(
`C’est fait : le rôle ${role} a été ${adding ? 'ajouté à' : 'retiré de'} **${target.user.tag}**.`,
),
],
});
}
+6 -2
View File
@@ -17,7 +17,7 @@ export const data = new SlashCommandBuilder()
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) =>
option.setName('reason').setDescription('Raison').setRequired(true).setMaxLength(500),
option.setName('reason').setDescription('Motif').setRequired(true).setMaxLength(500),
);
/** Records the warning, notifies the member and logs it (M8-T01 / M8-T06). */
@@ -44,6 +44,10 @@ export async function execute(interaction) {
.catch(() => {});
await interaction.editReply({
embeds: [successEmbed(`**${target.user.tag}** a été averti (${total} avertissement(s) au total).`)],
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** reçoit un avertissement (${total} au total). La personne a aussi reçu un message privé quand c’était possible.`,
),
],
});
}
+6 -2
View File
@@ -31,7 +31,7 @@ export const data = new SlashCommandBuilder()
sub
.setName('close')
.setDescription('Fermer le ticket')
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500)),
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500)),
)
.addSubcommand((sub) => sub.setName('claim').setDescription('Prendre le ticket en charge'))
.addSubcommand((sub) =>
@@ -49,7 +49,11 @@ export async function execute(interaction) {
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const channel = await createTicket(interaction, categoryId);
await interaction.editReply({
embeds: [successEmbed(`Ton ticket est ouvert : <#${channel.id}>`)],
embeds: [
successEmbed(
`Ton ticket est ouvert : <#${channel.id}>. Décris ta demande dedans, une personne de l’équipe te répond dès que possible.`,
),
],
});
return;
}
+173 -48
View File
@@ -4,16 +4,19 @@ import { UserFacingError } from '../../core/errors.js';
import {
activeChannelCount,
claimOwnership,
getVoiceSettings,
findTrigger,
kickUser,
listTriggerSummaries,
NAME_MAX,
permitUser,
postSetupPanel,
rejectUser,
removeChannel,
removeVoiceTriggerConfig,
renameChannel,
saveVoiceSettings,
saveVoiceTrigger,
setChannelLimit,
setTriggerEnabled,
showInfo,
toggleLock,
transferOwnership,
@@ -21,17 +24,27 @@ import {
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = { setup: ACCESS_LEVELS.STAFF, panel: ACCESS_LEVELS.STAFF };
export const subcommandAccess = {
setup: ACCESS_LEVELS.STAFF,
panel: ACCESS_LEVELS.STAFF,
list: ACCESS_LEVELS.STAFF,
remove: ACCESS_LEVELS.STAFF,
enable: ACCESS_LEVELS.STAFF,
disable: ACCESS_LEVELS.STAFF,
};
const voiceChannelOption = (option) => option.addChannelTypes(ChannelType.GuildVoice);
/** Longest embed listing worth sending before it gets unreadable. */
const MAX_LISTED_TRIGGERS = 20;
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')
.setDescription('Ajouter ou modifier un salon déclencheur')
.addChannelOption((option) =>
voiceChannelOption(
option
@@ -40,10 +53,13 @@ export const data = new SlashCommandBuilder()
.setRequired(true),
),
)
.addStringOption((option) =>
option.setName('label').setDescription('Nom du déclencheur (ex. « Dev », « SIO »)').setMaxLength(40),
)
.addChannelOption((option) =>
option
.setName('category')
.setDescription('Catégorie d’accueil des salons créés')
.setDescription('Catégorie d’accueil des salons créés (défaut : celle du déclencheur)')
.addChannelTypes(ChannelType.GuildCategory),
)
.addStringOption((option) =>
@@ -60,12 +76,47 @@ export const data = new SlashCommandBuilder()
.setMaxValue(99),
)
.addBooleanOption((option) =>
option.setName('panel').setDescription('Publier le panneau d’explication dans le salon déclencheur'),
option.setName('panel').setDescription('Publier le panneau d’explication dans le salon'),
),
)
.addSubcommand((sub) => sub.setName('config').setDescription('Afficher la configuration actuelle'))
.addSubcommand((sub) => sub.setName('config').setDescription('Afficher les déclencheurs configurés'))
.addSubcommand((sub) =>
sub.setName('panel').setDescription('Republier le panneau d’explication dans le salon déclencheur'),
sub
.setName('panel')
.setDescription('Republier le panneau d’explication dans les salons déclencheurs')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Un seul déclencheur (défaut : tous)')),
),
)
.addSubcommandGroup((group) =>
group
.setName('triggers')
.setDescription('Gérer les salons déclencheurs')
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les déclencheurs'))
.addSubcommand((sub) =>
sub
.setName('remove')
.setDescription('Supprimer un déclencheur')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
)
.addSubcommand((sub) =>
sub
.setName('disable')
.setDescription('Désactiver un déclencheur sans le supprimer')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
)
.addSubcommand((sub) =>
sub
.setName('enable')
.setDescription('Réactiver un déclencheur')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
),
)
.addSubcommand((sub) =>
sub
@@ -134,66 +185,133 @@ export const data = new SlashCommandBuilder()
),
);
const ORIGIN_LABELS = {
env: 'variables d’environnement',
settings: 'anciens réglages du bot',
};
/** One embed field per trigger, shared by `/voice config`, `/voice triggers list` and `/voice setup`. */
function describeTrigger(trigger, index = null) {
const lines = [
`**Salon :** <#${trigger.triggerId}>`,
`**Catégorie :** ${trigger.categoryId ? `<#${trigger.categoryId}>` : 'celle du salon déclencheur'}`,
`**Modèle :** \`${trigger.template}\``,
`**Limite :** ${trigger.userLimit ? `${trigger.userLimit} places` : 'illimitée'}`,
`**Salons en cours :** ${trigger.activeChannels ?? 0}`,
];
const origin = ORIGIN_LABELS[trigger.source];
if (origin) lines.push(`**Origine :** ${origin}`);
return {
name: `${index === null ? '' : `${index + 1}. `}${trigger.label ? `${trigger.label} · ` : ''}${
trigger.enabled ? '✅ Actif' : '⛔ Désactivé'
}`,
value: lines.join('\n'),
};
}
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 },
const triggers = listTriggerSummaries(guildId);
const embed = baseEmbed(COLORS.primary).setTitle('🎧 Salons vocaux temporaires');
if (triggers.length === 0) {
return embed.setDescription(
'Aucun déclencheur pour le moment : tu peux en ajouter un avec `/voice setup` (un par thème, ex. « Dev », « SIO »).',
);
}
embed.setDescription(
`**${triggers.length}** déclencheur(s) · **${activeChannelCount(guildId)}** salon(s) temporaire(s) en cours\n` +
'Chaque déclencheur crée ses salons en bas de sa propre catégorie, et ils disparaissent dès qu’ils se vident.',
);
embed.addFields(triggers.slice(0, MAX_LISTED_TRIGGERS).map((trigger, i) => describeTrigger(trigger, i)));
if (triggers.length > MAX_LISTED_TRIGGERS) {
embed.addFields({
name: 'Autres déclencheurs',
value: `… et ${triggers.length - MAX_LISTED_TRIGGERS} autre(s), visibles sur le serveur.`,
});
}
return embed;
}
async function runSetup(interaction) {
const trigger = interaction.options.getChannel('trigger', true);
if (trigger.type !== ChannelType.GuildVoice) {
const channel = interaction.options.getChannel('trigger', true);
if (channel.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(
const existing = findTrigger(interaction.guildId, channel.id);
const template = interaction.options.getString('template');
const limit = interaction.options.getInteger('limit');
const label = interaction.options.getString('label');
const trigger = saveVoiceTrigger(
interaction.guildId,
{
trigger: trigger.id,
...(category && { category: category.id }),
...(template && { template }),
...(limit !== null && { limit }),
triggerId: channel.id,
...(label !== null && { label }),
// A trigger with no explicit category hosts its channels in its own category.
categoryId: category?.id ?? existing?.categoryId ?? channel.parentId ?? null,
...(template !== null && { template }),
...(limit !== null && { userLimit: limit }),
},
interaction.user.id,
);
await interaction.reply({
embeds: [successEmbed(`Salon déclencheur : <#${trigger.id}>`)],
flags: MessageFlags.Ephemeral,
});
if (!trigger) {
throw new UserFacingError('Le déclencheur n’a pas pu être enregistré, réessaie.');
}
const embed = baseEmbed(COLORS.success)
.setTitle(existing ? '✅ Déclencheur mis à jour' : '✅ Déclencheur ajouté')
.addFields(describeTrigger(trigger))
.setFooter({ text: 'Les salons créés depuis ce déclencheur apparaîtront en bas de sa catégorie.' });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
const wantsPanel = interaction.options.getBoolean('panel') ?? true;
if (wantsPanel) await postSetupPanel(interaction).catch(() => {});
if (wantsPanel) await postSetupPanel(interaction, { triggerId: channel.id }).catch(() => {});
}
/** `/voice triggers …` — declaration and lifecycle of the trigger channels (M14-T01). */
async function runTriggerGroup(interaction, subcommand) {
const guildId = interaction.guildId;
if (subcommand === 'list') {
await interaction.reply({ embeds: [configEmbed(guildId)], flags: MessageFlags.Ephemeral });
return;
}
const target = interaction.options.getChannel('trigger', true);
if (subcommand === 'remove') {
removeVoiceTriggerConfig(guildId, target.id);
await interaction.reply({
embeds: [
successEmbed(
`C’est fait : <#${target.id}> n’est plus un déclencheur. Les salons déjà créés depuis lui restent en place jusqu’à ce qu’ils se vident.`,
),
],
flags: MessageFlags.Ephemeral,
});
return;
}
const trigger = setTriggerEnabled(guildId, target.id, subcommand === 'enable');
await interaction.reply({
embeds: [
successEmbed(
trigger.enabled
? `Bon retour ! Le déclencheur <#${trigger.triggerId}> crée à nouveau des salons.`
: `Le déclencheur <#${trigger.triggerId}> est en pause : y entrer ne crée plus de salon, et sa configuration est conservée.`,
),
],
flags: MessageFlags.Ephemeral,
});
}
/** Every subcommand acts on the caller's temporary channel, checked by the service (M14-T06). */
@@ -201,12 +319,19 @@ export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
const channel = interaction.options.getChannel('channel');
if (interaction.options.getSubcommandGroup(false) === 'triggers') {
await runTriggerGroup(interaction, subcommand);
return;
}
switch (subcommand) {
case 'setup':
await runSetup(interaction);
return;
case 'panel':
await postSetupPanel(interaction);
await postSetupPanel(interaction, {
triggerId: interaction.options.getChannel('trigger')?.id ?? null,
});
return;
case 'config':
await interaction.reply({ embeds: [configEmbed(interaction.guildId)], flags: MessageFlags.Ephemeral });
+9 -1
View File
@@ -20,6 +20,14 @@ export const ACCESS_LEVELS = Object.freeze({
OWNER: 3,
});
/** Same names for the same levels in every message (M12-T02). */
export const ACCESS_LABELS = Object.freeze({
[ACCESS_LEVELS.USER]: 'Membre',
[ACCESS_LEVELS.STAFF]: 'Staff',
[ACCESS_LEVELS.DEV]: 'Dev',
[ACCESS_LEVELS.OWNER]: 'Owner',
});
/** Moderation actions: Discord label, embed color and stored duration (M8). */
export const MODERATION_ACTIONS = Object.freeze({
warn: { label: 'Avertissement', color: COLORS.warning, duration: false },
@@ -32,7 +40,7 @@ export const MODERATION_ACTIONS = Object.freeze({
/** Ticket categories and who can see them (M0-T05 / M6-T01). */
export const TICKET_CATEGORIES = Object.freeze([
{ id: 'support', label: 'Support utilisateur', scope: ['staff', 'owner'] },
{ id: 'support', label: 'Aide et support', scope: ['staff', 'owner'] },
{ id: 'bug', label: 'Bug', scope: ['staff', 'dev', 'owner'] },
{ id: 'dev-question', label: 'Question de développement', scope: ['dev', 'owner'] },
{ id: 'report', label: 'Signalement', scope: ['staff', 'owner'] },
+15
View File
@@ -10,6 +10,13 @@ const readBool = (key, fallback = false) => {
const value = read(key);
return value === '' ? fallback : value === 'true';
};
/** Durations accept 0, which `readInt` cannot express because 0 is falsy. */
const readDuration = (key, fallback) => {
const value = read(key);
if (value === '') return fallback;
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
};
export const env = Object.freeze({
nodeEnv: read('NODE_ENV', 'development'),
@@ -47,6 +54,14 @@ export const env = Object.freeze({
voiceCategory: read('CATEGORY_VOICE_ID'),
},
voice: {
emptyGraceMs: readDuration('VOICE_EMPTY_GRACE_MS', 5_000),
},
bot: {
statusIntervalSeconds: readDuration('BOT_STATUS_INTERVAL_SECONDS', 60),
},
gitea: {
url: read('GITEA_URL').replace(/\/+$/, ''),
token: read('GITEA_TOKEN'),
+3 -1
View File
@@ -7,7 +7,9 @@ export class UserFacingError extends Error {
}
export class PermissionDeniedError extends UserFacingError {
constructor(message = "Tu n'as pas la permission d'utiliser cette commande.") {
constructor(
message = 'Cette action est réservée à l’équipe pour l’instant. Demande à une personne du staff si tu en as besoin.',
) {
super(message);
this.name = 'PermissionDeniedError';
}
@@ -0,0 +1,14 @@
-- Several "join to create" triggers per guild, each with its own home category (M14)
CREATE TABLE IF NOT EXISTS voice_triggers (
trigger_id TEXT PRIMARY KEY,
guild_id TEXT NOT NULL,
label TEXT,
category_id TEXT,
template TEXT,
user_limit INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_voice_triggers_guild ON voice_triggers (guild_id);
@@ -0,0 +1,14 @@
-- Rotating presence of the bot, editable from Discord (M15)
-- The presence is global to the bot, so these rows are not tied to a guild.
CREATE TABLE IF NOT EXISTS bot_statuses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'watching',
url TEXT,
enabled INTEGER NOT NULL DEFAULT 1,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_bot_statuses_text ON bot_statuses (text);
CREATE INDEX IF NOT EXISTS idx_bot_statuses_enabled ON bot_statuses (enabled, id);
@@ -0,0 +1,42 @@
import { getDatabase } from '../index.js';
/** Adds a status and returns the stored row, so the command can show its id. */
export function addBotStatus({ text, type = 'watching', url = null, createdBy = null }) {
const result = getDatabase()
.prepare('INSERT INTO bot_statuses (text, type, url, created_by) VALUES (?, ?, ?, ?)')
.run(text, type, url, createdBy);
return getBotStatus(Number(result.lastInsertRowid));
}
export function getBotStatus(id) {
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE id = ?').get(id) ?? null;
}
/** Every status, disabled ones included, in the order they were added. */
export function listBotStatuses() {
return getDatabase().prepare('SELECT * FROM bot_statuses ORDER BY id ASC').all();
}
/** The statuses the rotation is allowed to show. */
export function listEnabledBotStatuses() {
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE enabled = 1 ORDER BY id ASC').all();
}
export function setBotStatusEnabled(id, enabled) {
return getDatabase()
.prepare('UPDATE bot_statuses SET enabled = ? WHERE id = ?')
.run(enabled ? 1 : 0, id).changes;
}
export function removeBotStatus(id) {
return getDatabase().prepare('DELETE FROM bot_statuses WHERE id = ?').run(id).changes;
}
export function clearBotStatuses() {
return getDatabase().prepare('DELETE FROM bot_statuses').run().changes;
}
export function countBotStatuses() {
const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM bot_statuses').get();
return row.count;
}
@@ -62,3 +62,11 @@ export function countVoiceChannels(guildId) {
.get(guildId);
return row.count;
}
/** Channels still alive for one trigger, used by the configuration embed (M14-T01). */
export function countVoiceChannelsByTrigger(triggerId) {
const row = getDatabase()
.prepare('SELECT COUNT(*) AS count FROM voice_channels WHERE trigger_id = ?')
.get(triggerId);
return row.count;
}
@@ -0,0 +1,52 @@
import { getDatabase } from '../index.js';
/**
* Declares (or updates) a trigger channel. Every value is explicit: the service merges the
* previous row before writing, so an omitted option keeps its stored value (M14-T01).
*/
export function upsertVoiceTrigger({
triggerId,
guildId,
label = null,
categoryId = null,
template = null,
userLimit = 0,
enabled = true,
}) {
getDatabase()
.prepare(
`INSERT INTO voice_triggers (trigger_id, guild_id, label, category_id, template, user_limit, enabled)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (trigger_id) DO UPDATE SET
guild_id = excluded.guild_id,
label = excluded.label,
category_id = excluded.category_id,
template = excluded.template,
user_limit = excluded.user_limit,
enabled = excluded.enabled,
updated_at = datetime('now')`,
)
.run(triggerId, guildId, label, categoryId, template, userLimit, enabled ? 1 : 0);
}
export function getVoiceTrigger(triggerId) {
return getDatabase().prepare('SELECT * FROM voice_triggers WHERE trigger_id = ?').get(triggerId) ?? null;
}
/** All the triggers of a guild, disabled ones included, in creation order. */
export function listVoiceTriggers(guildId) {
return getDatabase()
.prepare('SELECT * FROM voice_triggers WHERE guild_id = ? ORDER BY created_at ASC, trigger_id ASC')
.all(guildId);
}
export function removeVoiceTrigger(triggerId) {
return getDatabase().prepare('DELETE FROM voice_triggers WHERE trigger_id = ?').run(triggerId).changes;
}
export function countVoiceTriggers(guildId) {
const row = getDatabase()
.prepare('SELECT COUNT(*) AS count FROM voice_triggers WHERE guild_id = ?')
.get(guildId);
return row.count;
}
+5 -3
View File
@@ -1,7 +1,8 @@
import { ActivityType, Events } from 'discord.js';
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
import { startPollScheduler } from '../services/polls/poll-service.js';
import { sweepVoiceChannels } from '../services/voice/voice-service.js';
import { startBotStatusRotation } from '../services/status/bot-status-service.js';
import { startVoiceJanitor, sweepVoiceChannels } from '../services/voice/voice-service.js';
const log = createLogger('discord');
@@ -9,9 +10,10 @@ export const name = Events.ClientReady;
export const once = true;
export async function execute(client) {
client.user.setActivity('FWS Arch', { type: ActivityType.Watching });
startPollScheduler(client);
await sweepVoiceChannels(client);
startVoiceJanitor(client);
startBotStatusRotation(client);
log.info(`Connected as ${client.user.tag}`, {
guilds: client.guilds.cache.size,
commands: client.commands.size,
+8 -2
View File
@@ -1,4 +1,5 @@
import { Events, MessageFlags } from 'discord.js';
import { ACCESS_LABELS } from '../config/constants.js';
import { PermissionDeniedError, UserFacingError } from '../core/errors.js';
import { createLogger } from '../core/logger.js';
import { hasAccess } from '../core/permissions.js';
@@ -37,7 +38,9 @@ async function runChatInputCommand(interaction) {
const subcommand = interaction.options.getSubcommand(false);
const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access;
if (!hasAccess(interaction.member, requiredLevel)) {
throw new PermissionDeniedError();
throw new PermissionDeniedError(
`Cette commande demande le niveau **${ACCESS_LABELS[requiredLevel]}**. Si tu en as besoin, demande à une personne du staff : elle peut le faire pour toi.`,
);
}
await command.execute(interaction);
}
@@ -77,6 +80,9 @@ export async function execute(_client, interaction) {
}
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,
'Quelque chose s’est mal passé de mon côté, rien n’est perdu. Réessaie dans un instant — je l’ai noté dans mes logs, l’équipe pourra regarder si ça recommence.',
).catch(() => {});
}
}
+6 -7
View File
@@ -1,14 +1,15 @@
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
import { cleanupVoiceChannel, createFromTrigger, getVoiceSettings } from '../services/voice/voice-service.js';
import { cleanupVoiceChannel, createFromTrigger, getVoiceTrigger } 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).
* Joining any of the trigger channels creates a private channel in that trigger's category 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;
@@ -18,10 +19,8 @@ export async function execute(_client, oldState, newState) {
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);
}
const trigger = getVoiceTrigger(newState.guild.id, joinedId);
if (trigger) await createFromTrigger(member, trigger);
}
if (oldState.channelId && oldState.channelId !== newState.channelId) {
+10 -9
View File
@@ -10,23 +10,24 @@ export function truncate(text, max = DESCRIPTION_MAX) {
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
}
/** Falls back to a neutral word: the value always sits next to a person, never a role. */
const authorOf = (source) =>
source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'inconnu';
source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'compte 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.')
.setDescription(truncate(issue.body) || 'Aucune description fournie.')
.addFields(
{ name: 'Auteur', value: authorOf(issue), inline: true },
{ name: 'Ouverte par', 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(', ') });
if (labels.length > 0) embed.addFields({ name: 'Étiquettes', value: labels.join(', ') });
return embed;
}
@@ -35,9 +36,9 @@ 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.')
.setDescription(truncate(pull.body) || 'Aucune description fournie.')
.addFields(
{ name: 'Auteur', value: authorOf(pull), inline: true },
{ name: 'Proposée par', value: authorOf(pull), inline: true },
{ name: 'État', value: state, inline: true },
{ name: 'Branches', value: `${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'}`, inline: true },
);
@@ -74,12 +75,12 @@ export function pushEmbed(payload, maxCommits = 5) {
const embed = baseEmbed(COLORS.gitea)
.setTitle(`Push sur ${branch || 'le dépôt'}`)
.setDescription(lines.join('\n') || 'Aucun commit dans cet événement.')
.setDescription(lines.join('\n') || 'Aucun commit à afficher pour cet événement.')
.addFields(
{ name: 'Auteur', value: authorOf(payload), inline: true },
{ name: 'Poussé par', 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 (remaining > 0) embed.addFields({ name: 'Et aussi', value: `${remaining} commit(s) de plus` });
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed;
}
+8 -4
View File
@@ -15,7 +15,9 @@ 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`.');
throw new UserFacingError(
'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`. Tout le reste du bot fonctionne sans cela.',
);
}
}
@@ -68,8 +70,8 @@ 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.';
? 'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`.'
: 'Gitea ne répond pas pour le moment. Réessaie dans quelques instants — si ça persiste, préviens l’équipe.';
const payload = { embeds: [errorEmbed(detail)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) {
@@ -107,7 +109,9 @@ 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.');
throw new UserFacingError(
'La sélection des branches a expiré : relance `/pr create` pour les choisir à nouveau.',
);
}
await interaction.deferReply();
+6 -6
View File
@@ -26,13 +26,13 @@ export async function sendWelcome(client, member) {
}
const embed = baseEmbed(COLORS.primary)
.setTitle('Nouveau membre !')
.setDescription(`${member} rejoint le serveur. ${DEFAULT_WELCOME}`)
.setTitle('🎉 Nouveau membre')
.setDescription(`${member} vient d’arriver. ${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}>` });
embed.addFields({ name: 'Règlement', value: `À lire ici : <#${env.channels.rules}>` });
}
await channel.send({ content: `${member}`, embeds: [embed] });
@@ -70,8 +70,8 @@ export async function sendWelcomeDirectMessage(member) {
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.',
'Merci d’avoir rejoint la communauté FWS 🌱 Prends un instant pour lire le règlement, ' +
'puis présente‑toi si tu le souhaites : on adore découvrir les nouvelles personnes.',
);
if (links.length > 0) embed.addFields({ name: 'Ressources', value: links.join('\n') });
@@ -90,7 +90,7 @@ export async function announceDeparture(client, member) {
const joinedAt = member.joinedTimestamp;
const embed = baseEmbed(COLORS.warning)
.setTitle('Départ d’un membre')
.setTitle('👋 Départ d’un membre')
.setDescription(`${member.user.tag} a quitté le serveur.`)
.addFields(
{ name: 'Membres', value: String(member.guild.memberCount), inline: true },
+25 -11
View File
@@ -12,17 +12,25 @@ import { baseEmbed } from '../../ui/embeds.js';
* @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) {
throw new UserFacingError(
'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.',
);
}
if (target.id === interaction.user.id) {
throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi-même.');
throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi‑même 😅 Vise un autre membre.');
}
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.');
throw new UserFacingError(
'Cette personne a un rôle égal ou supérieur au tien : je ne peux pas la viser. Demande à quelqu’un de plus haut dans la hiérarchie si c’est nécessaire.',
);
}
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}.`);
throw new UserFacingError(
`Je ne peux pas agir sur ${target.user.tag} : mon rôle est placé plus bas que le sien. Remonte mon rôle dans les paramètres du serveur, et je m’en occupe.`,
);
}
}
@@ -73,11 +81,11 @@ export async function sendModerationLog(
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color)
.setTitle(`Modération — ${meta?.label ?? action}`)
.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' },
{ name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true },
{ name: 'Par', value: `<@${moderatorId}>`, inline: true },
{ name: 'Motif', value: reason || 'Non précisé' },
);
if (durationMs) {
embed.addFields({ name: 'Durée', value: formatDuration(durationMs), inline: true });
@@ -92,8 +100,10 @@ export function targetNoticeEmbed({ action, guildName, reason = null, durationMs
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' });
.setDescription(
`Action : **${meta?.label ?? action}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`,
)
.addFields({ name: 'Motif', value: reason || 'Non précisé' });
if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) });
return embed;
}
@@ -113,6 +123,10 @@ export function formatDuration(durationMs) {
/** 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.');
if (!member) {
throw new UserFacingError(
'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.',
);
}
return member;
}
@@ -50,7 +50,9 @@ 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({
errorEmbed(
`Un incident est survenu dans **${context}**. Rien d’inquiétant pour les membres : je continue de fonctionner, mais l’équipe technique gagne à y jeter un œil.`,
).addFields({
name: 'Détail',
value: `\`${String(error?.message ?? error).slice(0, 500)}\``,
}),
+18 -10
View File
@@ -29,10 +29,14 @@ export function parseChoices(input, { min = CHOICES_MIN, max = POLL_CHOICES_MAX
.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 « ; ».`);
throw new UserFacingError(
`Il faut entre ${min} et ${max} propositions, séparées par des points‑virgules. Exemple : \`Pizza ; Sushis ; Tacos\`.`,
);
}
if (new Set(choices.map((choice) => choice.toLowerCase())).size !== choices.length) {
throw new UserFacingError('Les choix d’un sondage doivent être différents.');
throw new UserFacingError(
'Deux propositions identiques rendraient le vote ambigu : donne un libellé différent à chacune.',
);
}
return choices;
}
@@ -60,7 +64,7 @@ export function buildPollEmbed(poll, counts = countVotes(poll.id)) {
});
const embed = baseEmbed(COLORS.info)
.setTitle(`Sondage #${poll.id} — ${poll.question}`)
.setTitle(`📊 Sondage #${poll.id} — ${poll.question}`)
.setDescription(lines.join('\n\n'))
.addFields(
{ name: 'Votes', value: String(total), inline: true },
@@ -130,8 +134,12 @@ async function fetchPollMessage(interaction, poll) {
/** 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é.`);
if (!poll) {
throw new UserFacingError(`Je ne trouve pas le sondage **#${pollId}** : il a peut‑être été supprimé.`);
}
if (poll.status === 'closed') {
throw new UserFacingError(`Le sondage **#${pollId}** est déjà fermé — les résultats sont figés.`);
}
closePoll(pollId);
const closed = { ...poll, status: 'closed' };
@@ -155,19 +163,19 @@ 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é.');
throw new UserFacingError('Ce sondage est terminé : les boutons ne prennent plus les votes.');
}
const choices = JSON.parse(poll.choices);
const index = Number(rawIndex);
if (!Number.isInteger(index) || index < 0 || index >= choices.length) {
throw new UserFacingError('Choix inconnu.');
throw new UserFacingError('Cette proposition n’existe plus dans le sondage.');
}
const result = castVote(poll.id, interaction.user.id, index);
if (result === 'unchanged') {
await interaction.reply({
content: `Tu as déjà voté pour **${choices[index]}**.`,
content: `Ton vote est déjà sur **${choices[index]}** — rien n’a bougé.`,
flags: MessageFlags.Ephemeral,
});
return;
@@ -179,8 +187,8 @@ export async function handlePollComponent(interaction) {
await interaction.reply({
content:
result === 'changed'
? `Ton vote a été changé pour **${choices[index]}**.`
: `Vote enregistré pour **${choices[index]}**.`,
? `C’est noté : ton vote va maintenant à **${choices[index]}**.`
: `Merci ! Ton vote est sur **${choices[index]}**.`,
flags: MessageFlags.Ephemeral,
});
}
+314
View File
@@ -0,0 +1,314 @@
import { ActivityType } from 'discord.js';
import { COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
addBotStatus as addBotStatusRow,
clearBotStatuses,
countBotStatuses,
getBotStatus,
listBotStatuses,
listEnabledBotStatuses,
removeBotStatus as removeBotStatusRow,
setBotStatusEnabled,
} from '../../database/repositories/bot-status-repository.js';
import { resolveSetting, setSetting } from '../../database/repositories/settings-repository.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
const log = createLogger('status');
/** Discord caps an activity name at 128 characters. */
export const STATUS_TEXT_MAX = 128;
/** Beyond that the picker in `/status list` becomes unreadable; ask for fewer, clearer lines. */
export const STATUS_MAX = 25;
export const ROTATION_MIN_SECONDS = 5;
export const ROTATION_MAX_SECONDS = 86_400;
/** Key of the rotation delay, stored per guild like the other settings (M15). */
export const ROTATION_KEY = 'bot.status.interval';
/** Shown while the list is empty, so the bot never displays nothing useful. */
export const FALLBACK_STATUS = Object.freeze({
id: null,
text: 'les commandes avec /help',
type: 'watching',
});
/**
* Accepted activity types. Discord writes the verb itself, so only the label used in the
* embeds lives here; `streaming` is the one type that requires a link.
*/
export const STATUS_TYPES = Object.freeze({
playing: { label: 'joue à', activity: ActivityType.Playing },
streaming: { label: 'en direct sur', activity: ActivityType.Streaming, needsUrl: true },
listening: { label: 'écoute', activity: ActivityType.Listening },
watching: { label: 'regarde', activity: ActivityType.Watching },
competing: { label: 'participe à', activity: ActivityType.Competing },
});
/** Choice list for the slash command. */
export const STATUS_TYPE_CHOICES = Object.freeze(
Object.entries(STATUS_TYPES).map(([value, type]) => ({ name: type.label, value })),
);
/** Strips control characters without a control-character regex, then collapses the spaces. */
const clean = (value) =>
[...String(value ?? '')]
.map((char) => {
const code = char.codePointAt(0);
return code <= 31 || code === 127 ? ' ' : char;
})
.join('')
.replace(/\s+/g, ' ')
.trim();
export function sanitizeStatusText(value) {
const text = clean(value);
if (!text) {
throw new UserFacingError(
'Il me manque le texte du statut : écris quelques mots, par exemple « les commandes avec /help ».',
);
}
if (text.length > STATUS_TEXT_MAX) {
throw new UserFacingError(
`Discord limite un statut à ${STATUS_TEXT_MAX} caractères, et ce texte en fait ${text.length}. Raccourcis‑le un peu.`,
);
}
return text;
}
export function normalizeStatusType(value) {
const key = String(value ?? 'watching')
.toLowerCase()
.trim();
if (!STATUS_TYPES[key]) {
throw new UserFacingError(
`Je ne connais pas ce type de statut. Choisis parmi : ${Object.keys(STATUS_TYPES).join(', ')}.`,
);
}
return key;
}
/** Only a streaming status uses a link, and Discord refuses it without a valid URL. */
export function validateStatusUrl(value, typeKey) {
const url = String(value ?? '').trim();
if (STATUS_TYPES[typeKey]?.needsUrl && !url) {
throw new UserFacingError(
'Le type « en direct » a besoin d’un lien (Twitch, YouTube…) : ajoute l’option `url`.',
);
}
if (!url) return null;
if (!/^https?:\/\/\S+$/i.test(url)) {
throw new UserFacingError('Un lien de diffusion doit commencer par `http://` ou `https://`.');
}
return url;
}
/** `45 s`, `5 min`, `2 h 30 min` — used by the embeds of `/status`. */
export function formatSeconds(seconds) {
const value = Math.max(0, Math.round(Number(seconds) || 0));
if (value < 60) return `${value} s`;
const minutes = Math.round(value / 60);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`;
}
/** Delay used when neither the database nor the environment gives a usable value. */
const FALLBACK_ROTATION_SECONDS = 60;
/** The environment default, ignored when it is out of range rather than applied blindly. */
const envRotationSeconds = () => {
const value = Number(env.bot.statusIntervalSeconds);
return Number.isInteger(value) && value >= ROTATION_MIN_SECONDS && value <= ROTATION_MAX_SECONDS
? value
: FALLBACK_ROTATION_SECONDS;
};
export function clampRotation(value, { strict = false } = {}) {
const seconds = Number(value);
if (!Number.isInteger(seconds) || seconds < ROTATION_MIN_SECONDS || seconds > ROTATION_MAX_SECONDS) {
if (strict) {
throw new UserFacingError(
`Le rythme doit être un nombre de secondes entre ${ROTATION_MIN_SECONDS} et ${ROTATION_MAX_SECONDS} (${formatSeconds(ROTATION_MIN_SECONDS)} à ${formatSeconds(ROTATION_MAX_SECONDS)}).`,
);
}
return envRotationSeconds();
}
return seconds;
}
/** Rotation delay, overridable from Discord; the environment provides the default (M15). */
export function getRotationSeconds(guildId = env.discord.guildId) {
return clampRotation(resolveSetting(guildId, ROTATION_KEY, env.botStatusIntervalSeconds));
}
export function saveRotationSeconds(seconds, guildId = env.discord.guildId, updatedBy = null) {
const value = clampRotation(seconds, { strict: true });
setSetting(guildId, ROTATION_KEY, value, updatedBy);
return value;
}
/** Adds a status, or explains why it cannot be added (duplicate text, too many, invalid link). */
export function addBotStatus({ text, type = 'watching', url = null, createdBy = null } = {}) {
const statusText = sanitizeStatusText(text);
const typeKey = normalizeStatusType(type);
const statusUrl = validateStatusUrl(url, typeKey);
if (countBotStatuses() >= STATUS_MAX) {
throw new UserFacingError(
`La liste est déjà pleine (${STATUS_MAX} statuts) : supprime‑en un avec \`/status remove\` avant d’en ajouter un autre.`,
);
}
let status;
try {
status = addBotStatusRow({ text: statusText, type: typeKey, url: statusUrl, createdBy });
} catch (error) {
if (!/UNIQUE constraint/i.test(String(error?.message))) throw error;
log.debug('Duplicate status refused', error);
throw new UserFacingError(
`« ${statusText} » est déjà dans la liste : \`/status list\` montre les statuts existants.`,
);
}
logEvent({
guildId: env.discord.guildId,
type: 'bot.status.added',
actorId: createdBy,
payload: { id: status.id },
});
return status;
}
export function removeBotStatus(id) {
const status = getBotStatus(id);
if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`);
removeBotStatusRow(id);
logEvent({ guildId: env.discord.guildId, type: 'bot.status.removed', payload: { id } });
return status;
}
export function toggleBotStatus(id, enabled) {
const status = getBotStatus(id);
if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`);
if (Boolean(status.enabled) === enabled) {
throw new UserFacingError(
enabled
? `Le statut **#${id}** tourne déjà — il n’y a rien à changer.`
: `Le statut **#${id}** est déjà en pause — il n’y a rien à changer.`,
);
}
setBotStatusEnabled(id, enabled);
return { ...status, enabled: enabled ? 1 : 0 };
}
/** Empties the list; the fallback status takes over immediately. */
export function clearBotStatusList() {
const removed = clearBotStatuses();
logEvent({ guildId: env.discord.guildId, type: 'bot.status.cleared', payload: { removed } });
return removed;
}
/**
* Next status of the rotation: the enabled ones in insertion order, one after the other.
* Returns `null` when nothing is enabled, so the caller falls back to a default line.
*/
export function selectNextStatus(statuses, lastId = null) {
if (statuses.length === 0) return null;
const index = statuses.findIndex((status) => status.id === lastId);
return statuses[(index + 1) % statuses.length];
}
/** Shows one status in Discord. */
export function applyBotStatus(client, status = FALLBACK_STATUS) {
const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching;
const activity = { name: status.text, type: type.activity };
if (type.needsUrl && status.url) activity.url = status.url;
client.user.setPresence({ status: 'online', activities: [activity] });
return activity;
}
/** Applies the only enabled status right away, so an addition shows up immediately. */
export function applyStatusIfAlone(client) {
const statuses = listEnabledBotStatuses();
if (statuses.length !== 1) return null;
applyBotStatus(client, statuses[0]);
return statuses[0];
}
/** Shows the next status and returns it; used by the rotation and by the tests. */
export function rotateBotStatus(client, lastId = null) {
const status = selectNextStatus(listEnabledBotStatuses(), lastId) ?? FALLBACK_STATUS;
applyBotStatus(client, status);
return status;
}
/**
* Rotates the statuses forever. The delay is read again on every turn, so `/status interval`
* takes effect without restarting the bot (M15).
*/
export function startBotStatusRotation(client, { guildId = env.discord.guildId } = {}) {
let lastId = null;
let timer = null;
const tick = () => {
try {
lastId = rotateBotStatus(client, lastId)?.id ?? null;
} catch (error) {
log.warn('Could not rotate the bot status', error);
}
timer = setTimeout(tick, getRotationSeconds(guildId) * 1000);
timer.unref?.();
};
tick();
return { stop: () => clearTimeout(timer) };
}
function describeStatus(status) {
const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching;
const link = type.needsUrl && status.url ? ` · ${status.url}` : '';
return `« ${status.text} » — ${type.label}${link}`;
}
/** The list shown by `/status list` (M15). */
export function statusListEmbed({ guildId = env.discord.guildId, statuses = listBotStatuses() } = {}) {
const embed = baseEmbed(COLORS.primary).setTitle('🎭 Statuts du bot');
if (statuses.length === 0) {
return embed.setDescription(
`Aucun statut personnalisé pour le moment : j’affiche « ${FALLBACK_STATUS.text} » en attendant.\n\nAjoute le premier avec \`/status add\`.`,
);
}
const active = statuses.filter((status) => status.enabled).length;
embed.setDescription(
`${bullets([
`**${statuses.length}** statut(s), dont **${active}** en rotation`,
`changement toutes les **${formatSeconds(getRotationSeconds(guildId))}**`,
'la rotation suit l’ordre d’ajout et saute les statuts en pause',
])}`,
);
embed.addFields(
statuses.map((status) => ({
name: `#${status.id} · ${status.enabled ? '✅ en rotation' : '⛔ en pause'}`,
value: describeStatus(status),
})),
);
return embed;
}
/** Confirmation shown after `/status add`, including when the addition changes what is displayed. */
export function statusAddedEmbed(status, { applied = false } = {}) {
const next = applied
? 'C’était le premier statut : il s’affiche tout de suite sous le nom du bot.'
: 'Il apparaît dans la rotation ; `/status list` montre l’ensemble.';
return successEmbed(
`C’est dans la liste : **#${status.id}** — ${describeStatus(status)}.\n\n${next}`,
).setTitle('✅ Statut ajouté');
}
+41 -23
View File
@@ -37,10 +37,10 @@ export function canUseCategory(member, category) {
function ticketEmbed(ticket, category) {
const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne';
return baseEmbed(COLORS.ticket)
.setTitle(`Ticket ${category.label} #${ticket.id}`)
.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.',
`<@${ticket.author_id}> décris ta demande ici, avec le plus de détails possible : ` +
'contexte, étapes pour reproduire, messages d’erreur. Plus tu en dis, plus vite on t’aide.',
)
.addFields(
{ name: 'Catégorie', value: category.label, inline: true },
@@ -96,18 +96,28 @@ async function logTicket(client, 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 (!category) {
throw new UserFacingError(
'Je ne connais pas cette catégorie de ticket : `/ticket create` te propose la liste à jour.',
);
}
if (!canUseCategory(interaction.member, category)) {
throw new UserFacingError(`Tu n’as pas accès à la catégorie **${category.label}**.`);
throw new UserFacingError(
`La catégorie **${category.label}** est réservée à l’équipe. Tu peux ouvrir un ticket dans une autre catégorie : \`/ticket create\` te montre celles qui te sont ouvertes.`,
);
}
if (!env.channels.ticketCategory) {
throw new UserFacingError('Le salon parent des tickets n’est pas configuré (`CATEGORY_TICKETS_ID`).');
throw new UserFacingError(
'Les tickets ne sont pas encore installés : il manque `CATEGORY_TICKETS_ID` dans le `.env`. Préviens l’équipe !',
);
}
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.');
throw new UserFacingError(
'`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.',
);
}
const channel = await guild.channels.create({
@@ -139,7 +149,9 @@ export async function createTicket(interaction, categoryId) {
// 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.');
throw new UserFacingError(
'Tu as déjà un ticket ouvert dans cette catégorie : continue dessus, ou ferme‑le avant d’en ouvrir un autre.',
);
}
await channel.send({
@@ -157,9 +169,9 @@ export async function createTicket(interaction, categoryId) {
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('Ticket ouvert')
.setTitle('🎫 Ticket ouvert')
.setDescription(`<#${channel.id}> — ${category.label}`)
.addFields({ name: 'Auteur', value: `<@${ticket.author_id}>`, inline: true }),
.addFields({ name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true }),
);
return channel;
@@ -169,10 +181,12 @@ export async function createTicket(interaction, categoryId) {
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.');
throw new UserFacingError(
'Cette action se lance depuis un salon de ticket : ouvre‑en un avec `/ticket create`, ou place‑toi dans le bon salon.',
);
}
if (ticket.status !== 'open') {
throw new UserFacingError('Ce ticket est déjà fermé.');
throw new UserFacingError('Ce ticket est déjà fermé : il n’y a plus rien à faire ici.');
}
return ticket;
}
@@ -180,7 +194,7 @@ export async function getChannelTicket(interaction) {
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.');
throw new UserFacingError('Tu as déjà ce ticket en charge — il n’y a rien à changer.');
}
claimTicketRow(ticket.id, interaction.user.id);
@@ -192,14 +206,14 @@ export async function claimTicket(interaction) {
});
await interaction.reply({
embeds: [successEmbed(`<@${interaction.user.id}> prend ce ticket en charge.`)],
embeds: [successEmbed(`C’est noté : <@${interaction.user.id}> prend ce ticket en charge. Merci !`)],
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('Ticket pris en charge')
.setTitle('🎫 Ticket pris en charge')
.setDescription(`#${ticket.id} — <#${ticket.channel_id}>`)
.addFields({ name: 'Staff', value: `<@${interaction.user.id}>`, inline: true }),
.addFields({ name: 'Avec', value: `<@${interaction.user.id}>`, inline: true }),
);
}
@@ -208,7 +222,9 @@ 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.');
throw new PermissionDeniedError(
'Seules la personne qui a ouvert ce ticket et l’équipe peuvent le fermer. Si besoin, demande‑le dans le salon.',
);
}
closeTicketRow(ticket.id, { closedBy: interaction.user.id, reason });
@@ -221,18 +237,20 @@ export async function closeTicket(interaction, reason = null) {
await interaction.reply({
embeds: [
successEmbed(`Ticket fermé par <@${interaction.user.id}>. Le salon sera supprimé dans 10 secondes.`),
successEmbed(
`Ticket fermé par <@${interaction.user.id}> — merci ! Le salon disparaît dans 10 secondes, tu as le temps de copier ce qui t’intéresse.`,
),
],
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('Ticket fermé')
.setTitle('🎫 Ticket fermé')
.setDescription(`#${ticket.id} — ${findCategory(ticket.category_id)?.label ?? ticket.category_id}`)
.addFields(
{ name: 'Auteur', value: `<@${ticket.author_id}>`, inline: true },
{ name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true },
{ name: 'Fermé par', value: `<@${interaction.user.id}>`, inline: true },
{ name: 'Raison', value: reason || 'Non précisée' },
{ name: 'Motif', value: reason || 'Non précisé' },
),
);
@@ -244,7 +262,7 @@ export async function closeTicket(interaction, reason = null) {
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.');
throw new UserFacingError('Cette personne est déjà dans le ticket — pas besoin de l’ajouter.');
}
await interaction.channel.permissionOverwrites.edit(userId, {
@@ -259,7 +277,7 @@ export async function addParticipant(interaction, userId) {
actorId: interaction.user.id,
payload: { ticketId: ticket.id, userId },
});
await interaction.reply({ embeds: [successEmbed(`<@${userId}> a été ajouté au ticket.`)] });
await interaction.reply({ embeds: [successEmbed(`C’est noté : <@${userId}> rejoint ce ticket.`)] });
}
/** Routes the buttons posted in ticket channels. */
+396 -110
View File
@@ -13,10 +13,11 @@ 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 { resolveSetting } from '../../database/repositories/settings-repository.js';
import {
addVoiceChannel,
countVoiceChannels,
countVoiceChannelsByTrigger,
getVoiceChannel,
listOwnedVoiceChannels,
listVoiceChannels,
@@ -26,6 +27,11 @@ import {
setVoiceName,
setVoiceOwner,
} from '../../database/repositories/voice-repository.js';
import {
listVoiceTriggers,
removeVoiceTrigger as deleteVoiceTriggerRow,
upsertVoiceTrigger,
} from '../../database/repositories/voice-trigger-repository.js';
import { voicePanelComponents } from '../../ui/buttons.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
@@ -35,8 +41,13 @@ 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;
/**
* Delay before an empty temporary channel is deleted, so a quick move does not destroy a channel
* its owner customised. `VOICE_EMPTY_GRACE_MS=0` deletes it as soon as it is empty (M14-T04).
*/
const EMPTY_GRACE_MS = Math.max(0, env.voice.emptyGraceMs);
/** Interval of the safety net that catches the channels an event could not clean up. */
const SWEEP_INTERVAL_MS = 60_000;
/** Creation in flight per member, to never create two channels for the same person (M14-T02). */
const pendingCreations = new Set();
@@ -71,7 +82,7 @@ const clean = (value) =>
/** 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.');
if (!name) throw new UserFacingError('Il me manque un nom : écris au moins un caractère pour ton salon.');
return name.slice(0, NAME_MAX);
}
@@ -89,33 +100,161 @@ 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}.`);
throw new UserFacingError(
`Indique un nombre entre 0 (aucune limite) et ${LIMIT_MAX}. Par exemple 5 pour cinq places.`,
);
}
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)),
};
/** Index of the last slot of a category once the new channel is part of it (M14-T02). */
export function bottomPosition(childCount) {
return Math.max(0, Number(childCount) - 1);
}
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);
/**
* Every trigger channel declared for a guild, so one server can host several of them
* ("dev", "sio", …), each with its own home category (M14-T01). Triggers written by the
* single-trigger version and the environment are still accepted as fallbacks.
*/
export function getVoiceTriggers(guildId) {
const triggers = new Map();
let rows = [];
try {
rows = listVoiceTriggers(guildId);
} catch (error) {
log.warn('Could not read the voice triggers', error);
}
for (const row of rows) {
triggers.set(row.trigger_id, {
triggerId: row.trigger_id,
label: row.label || null,
categoryId: row.category_id || null,
template: row.template || DEFAULT_TEMPLATE,
userLimit: clampLimit(row.user_limit),
enabled: Boolean(row.enabled),
source: 'database',
});
}
const legacyId = resolveSetting(guildId, 'voice.trigger', null);
if (legacyId && !triggers.has(legacyId)) {
triggers.set(legacyId, {
triggerId: legacyId,
label: null,
categoryId: resolveSetting(guildId, 'voice.category', env.channels.voiceCategory) || null,
template: resolveSetting(guildId, 'voice.template', DEFAULT_TEMPLATE) || DEFAULT_TEMPLATE,
userLimit: clampLimit(resolveSetting(guildId, 'voice.limit', 0)),
enabled: true,
source: 'settings',
});
}
const envId = env.channels.voiceTrigger;
if (envId && !triggers.has(envId)) {
triggers.set(envId, {
triggerId: envId,
label: null,
categoryId: env.channels.voiceCategory || null,
template: DEFAULT_TEMPLATE,
userLimit: 0,
enabled: true,
source: 'env',
});
}
return [...triggers.values()];
}
/** Any declared trigger, disabled ones included, so the commands can report and toggle them. */
export function findTrigger(guildId, triggerId) {
return getVoiceTriggers(guildId).find((trigger) => trigger.triggerId === triggerId) ?? null;
}
/** An enabled trigger: joining it creates a temporary channel (M14-T02). */
export function getVoiceTrigger(guildId, triggerId) {
const trigger = findTrigger(guildId, triggerId);
return trigger?.enabled ? trigger : null;
}
export function isTriggerChannel(guildId, channelId) {
return getVoiceTrigger(guildId, channelId) !== null;
}
/** Triggers with the number of channels they currently host, for the configuration embed. */
export function listTriggerSummaries(guildId) {
return getVoiceTriggers(guildId).map((trigger) => ({
...trigger,
activeChannels: countVoiceChannelsByTrigger(trigger.triggerId),
}));
}
/** Declares or updates a trigger; an omitted field keeps its stored value (M14-T01). */
export function saveVoiceTrigger(guildId, patch, updatedBy = null) {
const existing = patch.triggerId ? findTrigger(guildId, patch.triggerId) : null;
upsertVoiceTrigger({
triggerId: patch.triggerId,
guildId,
label: patch.label ?? existing?.label ?? null,
categoryId: patch.categoryId ?? existing?.categoryId ?? null,
template: patch.template ?? existing?.template ?? DEFAULT_TEMPLATE,
userLimit: clampLimit(patch.userLimit ?? existing?.userLimit ?? 0),
enabled: patch.enabled ?? existing?.enabled ?? true,
});
logEvent({
guildId,
type: 'voice.trigger.saved',
actorId: updatedBy,
payload: { triggerId: patch.triggerId },
});
return findTrigger(guildId, patch.triggerId);
}
/** Writes the trigger before toggling it, so an environment fallback can be switched off. */
export function setTriggerEnabled(guildId, triggerId, enabled) {
const trigger = findTrigger(guildId, triggerId);
if (!trigger)
throw new UserFacingError('Ce salon n’est pas un déclencheur : ajoute-le d’abord avec `/voice setup`.');
if (trigger.enabled === enabled) {
throw new UserFacingError(
enabled
? 'Ce déclencheur est déjà actif — il n’y a rien à changer.'
: 'Ce déclencheur est déjà désactivé — il n’y a rien à changer.',
);
}
upsertVoiceTrigger({
triggerId,
guildId,
label: trigger.label,
categoryId: trigger.categoryId,
template: trigger.template,
userLimit: trigger.userLimit,
enabled,
});
logEvent({ guildId, type: 'voice.trigger.toggled', payload: { triggerId, enabled } });
return findTrigger(guildId, triggerId);
}
/** Removes a trigger declared from Discord; the ones coming from the environment cannot be deleted. */
export function removeVoiceTriggerConfig(guildId, triggerId) {
const trigger = findTrigger(guildId, triggerId);
if (!trigger)
throw new UserFacingError('Ce salon n’est pas un déclencheur : il n’y a donc rien à supprimer.');
if (trigger.source !== 'database') {
throw new UserFacingError(
'Ce déclencheur vient des variables d’environnement (`CHANNEL_VOICE_TRIGGER_ID`) : je ne peux pas le supprimer d’ici. Retire‑le du `.env`, ou mets‑le en pause avec `/voice triggers disable`.',
);
}
deleteVoiceTriggerRow(triggerId);
logEvent({ guildId, type: 'voice.trigger.removed', payload: { triggerId } });
}
export function isStaff(member, roles = env.roles) {
@@ -132,7 +271,7 @@ export function voicePanelEmbed(channel, row) {
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.',
'Les boutons ci-dessous agissent sur ce salon seulement. Tu retrouves exactement les mêmes options dans `/voice`.',
)
.addFields(
{ name: 'Propriétaire', value: ownerId ? `<@${ownerId}>` : 'Personne', inline: true },
@@ -166,7 +305,8 @@ export function voiceInfoEmbed(channel, row) {
)
.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}` });
if (row?.trigger_id)
embed.setFooter({ text: `Salon temporaire · créé depuis le déclencheur ${row.trigger_id}` });
return embed;
}
@@ -201,20 +341,47 @@ export async function refreshPanel(channel) {
.catch(() => {});
}
async function findReusableChannel(guild, ownerId) {
/** Drops a channel from the database and from the panel cache. */
function forgetVoiceChannel(channelId) {
removeVoiceChannel(channelId);
panelMessages.delete(channelId);
}
/**
* The channel an owner can be moved back into: only one created from the same trigger, so that
* each trigger keeps its own channel in its own category (M14-T03). Rows of vanished channels
* are dropped along the way, whichever trigger they came from.
*/
async function findReusableChannel(guild, ownerId, triggerId) {
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);
forgetVoiceChannel(row.channel_id);
continue;
}
if (row.trigger_id !== triggerId) continue;
const full = channel.userLimit > 0 && channel.members.size >= channel.userLimit;
if (!full) return { channel, row };
}
return null;
}
/** New channels are appended below the ones already sitting in the target category (M14-T02). */
async function placeAtBottomOfCategory(channel) {
if (!channel.parentId) return;
const siblings = channel.guild.channels.cache.filter(
(candidate) => candidate.parentId === channel.parentId,
);
const target = bottomPosition(siblings.size);
if (channel.position === target) return;
await channel
.setPosition(target, { reason: 'Nouveau salon en bas de sa catégorie' })
.catch((error) => log.warn('Could not move the new channel to the bottom of its category', error));
}
function buildOverwrites(guild, client, ownerId) {
return [
{ id: guild.roles.everyone.id, allow: MEMBER_ALLOW },
@@ -224,14 +391,14 @@ function buildOverwrites(guild, client, ownerId) {
}
/**
* 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).
* Called when a member joins a trigger channel: creates their channel in the category of that
* trigger, below the channels already there, or moves them back into the one they already own
* (M14-T02 / M14-T03).
*/
export async function createFromTrigger(member) {
const settings = getVoiceSettings(member.guild.id);
if (!settings.triggerId || pendingCreations.has(member.id)) return null;
export async function createFromTrigger(member, trigger) {
if (!trigger?.triggerId || pendingCreations.has(member.id)) return null;
const reusable = await findReusableChannel(member.guild, member.id);
const reusable = await findReusableChannel(member.guild, member.id, trigger.triggerId);
if (reusable) {
await member.voice
.setChannel(reusable.channel, 'Retour dans son salon vocal temporaire')
@@ -241,26 +408,28 @@ export async function createFromTrigger(member) {
pendingCreations.add(member.id);
try {
const parent = settings.categoryId
? await member.guild.channels.fetch(settings.categoryId).catch(() => null)
const parent = trigger.categoryId
? await member.guild.channels.fetch(trigger.categoryId).catch(() => null)
: null;
const channel = await member.guild.channels.create({
name: buildChannelName(settings.template, member),
name: buildChannelName(trigger.template, member),
type: ChannelType.GuildVoice,
userLimit: settings.defaultLimit,
userLimit: trigger.userLimit,
...(parent?.type === ChannelType.GuildCategory && { parent: parent.id }),
reason: `Salon vocal temporaire de ${member.user.tag}`,
permissionOverwrites: buildOverwrites(member.guild, member.client, member.id),
});
await placeAtBottomOfCategory(channel);
addVoiceChannel({
channelId: channel.id,
guildId: member.guild.id,
ownerId: member.id,
triggerId: settings.triggerId,
triggerId: trigger.triggerId,
name: channel.name,
userLimit: settings.defaultLimit,
userLimit: trigger.userLimit,
});
await member.voice
@@ -280,44 +449,82 @@ export async function createFromTrigger(member) {
}
}
/** Deletes a temporary channel and forgets it. */
/**
* Deletes a temporary channel. The row is only dropped once the channel is really gone, so that a
* failed API call leaves a channel the sweep can retry instead of an orphaned room (M14-T04).
*/
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));
try {
await channel.delete(reason);
} catch (error) {
if (!(await isChannelGone(channel, error))) {
log.warn('Could not delete the voice channel', error);
return false;
}
}
forgetVoiceChannel(channel.id);
return true;
}
/** A 404 or an unknown-channel error means the channel is already deleted, whatever the cause. */
async function isChannelGone(channel, error) {
const codes = [error?.code, String(error?.code ?? '')];
if (error?.status === 404 || codes.includes(10003)) return true;
const fresh = await channel.guild.channels.fetch(channel.id).catch(() => null);
return fresh === null;
}
/** Resolves a channel from the cache or the API, or `null` when it does not exist anymore. */
async function resolveChannel(guild, channelId) {
return guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null));
}
/**
* Deletes an empty temporary channel after a short grace period, so that a member
* moving between channels does not lose their channel (M14-T04).
* Deletes an empty temporary channel after a short grace period, so that a member moving between
* channels does not lose the one they customised (M14-T04).
*/
export async function cleanupVoiceChannel(guild, channelId) {
export async function cleanupVoiceChannel(guild, channelId, { graceMs = EMPTY_GRACE_MS } = {}) {
const row = getVoiceChannel(channelId);
if (!row) return;
const channel =
guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null));
const channel = await resolveChannel(guild, channelId);
if (!channel) {
removeVoiceChannel(channelId);
forgetVoiceChannel(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);
const removeEmptyChannel = async () => {
const fresh = await resolveChannel(guild, channelId);
if (!fresh) {
forgetVoiceChannel(channelId);
return;
}
}, EMPTY_GRACE_MS).unref();
if (fresh.members.size > 0) return;
if (await deleteVoiceChannel(fresh, 'Salon vocal temporaire vide')) {
logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId } });
}
};
if (graceMs <= 0) {
await removeEmptyChannel().catch((error) => log.warn('Could not clean up an empty voice channel', error));
return;
}
setTimeout(
() => removeEmptyChannel().catch((error) => log.warn('Could not clean up an empty voice channel', error)),
graceMs,
).unref();
}
/** Startup sweep: forget deleted channels, remove the ones left empty by a restart (M14-T07). */
/**
* Forgets the channels that no longer exist and deletes the ones with nobody left in them
* (M14-T04 / M14-T07). Run at startup and then every minute: the voice state event is the fast
* path, this sweep is the guarantee when an event is missed or a deletion failed.
*/
export async function sweepVoiceChannels(client) {
for (const guild of client.guilds.cache.values()) {
let rows = [];
@@ -329,21 +536,30 @@ export async function sweepVoiceChannels(client) {
}
for (const row of rows) {
const channel =
guild.channels.cache.get(row.channel_id) ??
(await guild.channels.fetch(row.channel_id).catch(() => null));
const channel = await resolveChannel(guild, row.channel_id);
if (!channel) {
removeVoiceChannel(row.channel_id);
panelMessages.delete(row.channel_id);
forgetVoiceChannel(row.channel_id);
continue;
}
if (channel.members.size === 0) {
await deleteVoiceChannel(channel, 'Salon vocal temporaire vide après redémarrage');
if (channel.members.size > 0) continue;
if (await deleteVoiceChannel(channel, 'Salon vocal temporaire vide')) {
log.info(`Deleted the empty temporary channel ${row.channel_id}`);
logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId: row.channel_id } });
}
}
}
}
/** Starts the periodic sweep; the returned interval can be cleared to stop it (M14-T04). */
export function startVoiceJanitor(client, intervalMs = SWEEP_INTERVAL_MS) {
const timer = setInterval(() => {
sweepVoiceChannels(client).catch((error) => log.error('Voice channel sweep failed', error));
}, intervalMs);
timer.unref?.();
return timer;
}
export function activeChannelCount(guildId) {
return countVoiceChannels(guildId);
}
@@ -362,18 +578,20 @@ export async function resolveManagedChannel(interaction, { 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`.',
'Je ne trouve pas ton salon temporaire : entre dans ton salon vocal, puis relance la commande — ou indique‑le avec 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.');
throw new PermissionDeniedError(
'C’est réservé à l’équipe : chaque personne gère son propre salon. Tu peux modifier le tien, sans option `channel`.',
);
}
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.');
forgetVoiceChannel(row.channel_id);
throw new UserFacingError('Ce salon n’existe plus — il a sûrement déjà été supprimé.');
}
return { channel, row };
}
@@ -381,7 +599,9 @@ export async function resolveManagedChannel(interaction, { channelId = null } =
/** 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}.`);
throw new PermissionDeniedError(
`Ce salon appartient à <@${row.owner_id}> : seule cette personne (ou l’équipe) peut ${action}.`,
);
}
const ephemeral = (payload) => ({ ...payload, flags: MessageFlags.Ephemeral });
@@ -395,7 +615,9 @@ export async function renameChannel(interaction, name) {
setVoiceName(channel.id, sanitized);
await refreshPanel(channel);
await interaction.reply(ephemeral({ embeds: [successEmbed(`Salon renommé en **${sanitized}**.`)] }));
await interaction.reply(
ephemeral({ embeds: [successEmbed(`Ton salon s’appelle maintenant **${sanitized}**.`)] }),
);
}
export async function setChannelLimit(interaction, limit) {
@@ -411,7 +633,9 @@ export async function setChannelLimit(interaction, limit) {
ephemeral({
embeds: [
successEmbed(
value === 0 ? 'Le salon redevient **sans limite** de places.' : `Limite : **${value} places**.`,
value === 0
? 'Ton salon n’a plus de limite de places : tout le monde peut entrer.'
: `Ton salon accueille maintenant **${value} personnes**.`,
),
],
}),
@@ -424,7 +648,11 @@ export async function toggleLock(interaction, { locked = null } = {}) {
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é.');
throw new UserFacingError(
next
? 'Ton salon est déjà verrouillé — il n’y a rien à changer.'
: 'Ton salon est déjà ouvert — il n’y a rien à changer.',
);
}
await channel.permissionOverwrites.edit(
interaction.guild.roles.everyone.id,
@@ -439,8 +667,8 @@ export async function toggleLock(interaction, { locked = null } = {}) {
embeds: [
successEmbed(
next
? '🔒 Salon verrouillé : seuls les membres autorisés peuvent le rejoindre.'
: '🔓 Salon déverrouillé : tout le monde peut rejoindre.',
? '🔒 Salon verrouillé : seules les personnes que tu autorises peuvent entrer.'
: '🔓 Salon ouvert : tout le monde peut entrer.',
),
],
}),
@@ -458,7 +686,9 @@ export async function permitUser(interaction, userId) {
reason: `Autorisé par ${interaction.user.tag}`,
},
);
await interaction.reply(ephemeral({ embeds: [successEmbed(`<@${userId}> peut rejoindre le salon.`)] }));
await interaction.reply(
ephemeral({ embeds: [successEmbed(`C’est noté : <@${userId}> peut entrer dans ton salon.`)] }),
);
}
export async function rejectUser(interaction, userId) {
@@ -476,7 +706,7 @@ export async function rejectUser(interaction, userId) {
await member?.voice.disconnect(`Refusé par ${interaction.user.tag}`).catch(() => {});
await interaction.reply(
ephemeral({ embeds: [successEmbed(`<@${userId}> ne peut plus rejoindre le salon.`)] }),
ephemeral({ embeds: [successEmbed(`C’est noté : <@${userId}> ne peut plus entrer dans ton salon.`)] }),
);
}
@@ -485,11 +715,14 @@ export async function kickUser(interaction, userId) {
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.');
if (!member) throw new UserFacingError('Ce membre n’est pas dans ton salon — il n’y a rien à faire.');
if (member.id === row.owner_id)
throw new UserFacingError('Impossible : la personne propriétaire du salon ne peut pas en être exclue.');
await member.voice.disconnect(`Exclu par ${interaction.user.tag}`);
await interaction.reply(ephemeral({ embeds: [successEmbed(`<@${userId}> a été exclu du salon.`)] }));
await interaction.reply(
ephemeral({ embeds: [successEmbed(`<@${userId}> ne fait plus partie de ton salon.`)] }),
);
}
export async function transferOwnership(interaction, userId) {
@@ -497,8 +730,12 @@ export async function transferOwnership(interaction, userId) {
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.');
if (!member)
throw new UserFacingError(
'Cette personne doit déjà être dans le salon pour en devenir propriétaire : invite‑la, puis relance la commande.',
);
if (member.id === row.owner_id)
throw new UserFacingError('Cette personne est déjà propriétaire de ce salon.');
await channel.permissionOverwrites
.edit(row.owner_id, { ManageChannels: null, MoveMembers: null }, { reason: 'Nouveau propriétaire' })
@@ -518,7 +755,9 @@ export async function transferOwnership(interaction, userId) {
await interaction.reply(
ephemeral({
embeds: [successEmbed(`<@${member.id}> est désormais propriétaire de **${channel.name}**.`)],
embeds: [
successEmbed(`<@${member.id}> est désormais propriétaire de **${channel.name}**. Bonne session !`),
],
}),
);
}
@@ -527,13 +766,17 @@ export async function transferOwnership(interaction, userId) {
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.');
throw new UserFacingError('Tu es déjà propriétaire de ce salon — tout est en ordre.');
}
if (channel.members.has(row.owner_id)) {
throw new UserFacingError('Le propriétaire est toujours dans le salon.');
throw new UserFacingError(
'La personne propriétaire est encore dans le salon : ce salon n’est pas abandonné.',
);
}
if (!channel.members.has(interaction.user.id)) {
throw new UserFacingError('Rejoins d’abord le salon pour en réclamer la propriété.');
throw new UserFacingError(
'Entre d’abord dans le salon, puis relance la commande : la propriété se réclame depuis l’intérieur.',
);
}
await channel.permissionOverwrites.edit(interaction.user.id, OWNER_OVERWRITE, {
@@ -548,7 +791,9 @@ export async function claimOwnership(interaction) {
payload: { channelId: channel.id },
});
await interaction.reply(ephemeral({ embeds: [successEmbed('Tu es désormais propriétaire de ce salon.')] }));
await interaction.reply(
ephemeral({ embeds: [successEmbed('Tu es désormais propriétaire de ce salon. Amuse‑toi bien !')] }),
);
}
export async function removeChannel(interaction, { channelId = null } = {}) {
@@ -556,7 +801,11 @@ export async function removeChannel(interaction, { channelId = null } = {}) {
assertVoiceOwner(interaction, row, 'supprimer le salon');
await interaction.reply(
ephemeral({ embeds: [successEmbed(`Le salon **${channel.name}** va être supprimé.`)] }),
ephemeral({
embeds: [
successEmbed(`Le salon **${channel.name}** disparaît dans 3 secondes. Merci pour la session !`),
],
}),
);
logEvent({
guildId: interaction.guildId,
@@ -575,33 +824,70 @@ export async function showInfo(interaction, { channelId = null } = {}) {
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)
/** Embed published in a trigger channel to explain the "join to create" flow (M14-T01). */
function triggerPanelEmbed(trigger, channel) {
return baseEmbed(COLORS.primary)
.setTitle('🎧 Salons vocaux temporaires')
.setDescription(
`Rejoins ${trigger} pour obtenir ton propre salon vocal.\n\n` +
`Rejoins ${channel} 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 });
.addFields(
{
name: 'Catégorie',
value: trigger.categoryId ? `<#${trigger.categoryId}>` : 'Celle du salon déclencheur',
inline: true,
},
{
name: 'Limite par défaut',
value: trigger.userLimit ? `${trigger.userLimit} places` : 'Illimitée',
inline: true,
},
);
}
if (!trigger.isSendable()) {
throw new UserFacingError('Je n’ai pas la permission d’écrire dans le salon déclencheur.');
/**
* Publishes the explanation panel in one trigger, or in every enabled trigger of the guild
* when no trigger is given (M14-T01).
*/
export async function postSetupPanel(interaction, { triggerId = null } = {}) {
const triggers = getVoiceTriggers(interaction.guildId).filter(
(trigger) => trigger.enabled && (!triggerId || trigger.triggerId === triggerId),
);
if (triggers.length === 0) {
throw new UserFacingError(
triggerId
? 'Ce salon n’est pas un déclencheur actif : configure‑le avec `/voice setup`.'
: 'Aucun salon vocal déclencheur n’est configuré : lance `/voice setup`.',
);
}
await trigger.send({ embeds: [embed] });
await interaction.reply(ephemeral({ embeds: [successEmbed('Panneau publié dans le salon déclencheur.')] }));
const published = [];
for (const trigger of triggers) {
const channel = await interaction.guild.channels.fetch(trigger.triggerId).catch(() => null);
if (!channel?.isVoiceBased?.() || !channel.isSendable()) {
log.warn(`Skipped the panel of ${trigger.triggerId}: not a sendable voice channel`);
continue;
}
await channel.send({ embeds: [triggerPanelEmbed(trigger, channel)] }).catch((error) => {
log.warn('Could not publish the voice panel', error);
});
published.push(trigger.triggerId);
}
if (published.length === 0) {
throw new UserFacingError(
'Aucun panneau n’a pu être publié : vérifie que je peux écrire dans les salons déclencheurs.',
);
}
await interaction.reply(
ephemeral({
embeds: [successEmbed(`Panneau publié dans ${published.map((id) => `<#${id}>`).join(', ')}.`)],
}),
);
}
/** Button and select menu routing (M14-T05). */
+40 -4
View File
@@ -1,6 +1,25 @@
import { EmbedBuilder } from 'discord.js';
import { BOT_NAME, COLORS } from '../config/constants.js';
/**
* Bot voice — one tone everywhere (M12-T02). Every user-facing string in the project follows
* these rules, so the messages stay consistent as commands are added:
*
* - Informal French, short sentences, active voice; never a reproach or irony.
* - The title states the outcome, the description says what to do next.
* - One emoji per title, never decorative inside the body.
* - No gendered agreement on a person: "tu es propriétaire", "ce membre", "l'équipe",
* "la personne" — never "il / elle", "cher / chère", "ravi·e".
* - An error explains the cause, recalls the rule and offers the way out.
* - Same vocabulary across modules: équipe, membre, salon, ticket, motif.
*/
export const TONE = Object.freeze({
success: '✅ C’est fait',
error: '❌ Oups',
warning: '⚠️ Attention',
advice: '💡 Bon à savoir',
});
/** Base embed with the shared FWS-Bot visual identity (M12-T02). */
export function baseEmbed(color = COLORS.primary) {
return new EmbedBuilder().setColor(color).setFooter({ text: BOT_NAME }).setTimestamp();
@@ -10,10 +29,27 @@ export function infoEmbed(title, description) {
return baseEmbed(COLORS.info).setTitle(title).setDescription(description);
}
export function successEmbed(description) {
return baseEmbed(COLORS.success).setTitle('Succès').setDescription(description);
export function successEmbed(description, { title = TONE.success } = {}) {
return baseEmbed(COLORS.success).setTitle(title).setDescription(description);
}
export function errorEmbed(description) {
return baseEmbed(COLORS.error).setTitle('Erreur').setDescription(description);
export function warningEmbed(description, { title = TONE.warning } = {}) {
return baseEmbed(COLORS.warning).setTitle(title).setDescription(description);
}
export function errorEmbed(description, { title = TONE.error } = {}) {
return baseEmbed(COLORS.error).setTitle(title).setDescription(description);
}
/** Uniform list marker, so every embed lists things the same way. */
export function bullets(lines) {
return lines
.filter(Boolean)
.map((line) => `• ${line}`)
.join('\n');
}
/** Adds the "what you can do now" line that most replies end with. */
export function withHint(description, hint) {
return hint ? `${description}\n\n${hint}` : description;
}
+222
View File
@@ -0,0 +1,222 @@
import assert from 'node:assert/strict';
import { after, before, beforeEach, describe, it } from 'node:test';
import { UserFacingError } from '../src/core/errors.js';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
addBotStatus as addRow,
countBotStatuses,
getBotStatus,
listBotStatuses,
listEnabledBotStatuses,
removeBotStatus,
setBotStatusEnabled,
} from '../src/database/repositories/bot-status-repository.js';
import { setSetting } from '../src/database/repositories/settings-repository.js';
import {
addBotStatus,
applyStatusIfAlone,
clampRotation,
clearBotStatusList,
FALLBACK_STATUS,
formatSeconds,
getRotationSeconds,
normalizeStatusType,
ROTATION_KEY,
ROTATION_MAX_SECONDS,
ROTATION_MIN_SECONDS,
rotateBotStatus,
sanitizeStatusText,
saveRotationSeconds,
selectNextStatus,
STATUS_MAX,
STATUS_TEXT_MAX,
statusListEmbed,
toggleBotStatus,
validateStatusUrl,
} from '../src/services/status/bot-status-service.js';
const GUILD = 'g';
describe('bot status repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM bot_statuses'));
it('stores a status and reads it back', () => {
const status = addRow({ text: 'les commandes avec /help', type: 'watching', createdBy: 'u1' });
assert.equal(status.text, 'les commandes avec /help');
assert.equal(status.type, 'watching');
assert.equal(status.enabled, 1);
assert.equal(status.created_by, 'u1');
assert.equal(getBotStatus(status.id).text, status.text);
assert.equal(countBotStatuses(), 1);
});
it('keeps the insertion order and separates the paused ones', () => {
const first = addRow({ text: 'un' });
addRow({ text: 'deux' });
const third = addRow({ text: 'trois' });
setBotStatusEnabled(third.id, false);
assert.deepEqual(
listBotStatuses().map((status) => status.text),
['un', 'deux', 'trois'],
);
assert.deepEqual(
listEnabledBotStatuses().map((status) => status.text),
['un', 'deux'],
);
assert.equal(first.id < third.id, true);
});
it('refuses the same text twice and forgets a removed status', () => {
const status = addRow({ text: 'déjà là' });
assert.throws(() => addRow({ text: 'déjà là' }), /UNIQUE constraint/i);
assert.equal(removeBotStatus(status.id), 1);
assert.equal(getBotStatus(status.id), null);
assert.equal(removeBotStatus(status.id), 0);
});
});
describe('bot status helpers', () => {
it('normalises the text and refuses what Discord would reject', () => {
assert.equal(sanitizeStatusText(' les tickets '), 'les tickets');
assert.equal(sanitizeStatusText('a\nb'), 'a b');
assert.equal(sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX)).length, STATUS_TEXT_MAX);
assert.throws(() => sanitizeStatusText(' '), UserFacingError);
assert.throws(() => sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX + 1)), UserFacingError);
});
it('accepts the known types and explains the others', () => {
assert.equal(normalizeStatusType(), 'watching');
assert.equal(normalizeStatusType('PLAYING'), 'playing');
assert.throws(() => normalizeStatusType('danse'), UserFacingError);
});
it('requires a link for a stream and validates the ones it gets', () => {
assert.throws(() => validateStatusUrl(null, 'streaming'), UserFacingError);
assert.throws(() => validateStatusUrl('twitch.tv/fws', 'streaming'), UserFacingError);
assert.equal(validateStatusUrl('https://twitch.tv/fws', 'streaming'), 'https://twitch.tv/fws');
assert.equal(validateStatusUrl(null, 'watching'), null);
assert.equal(validateStatusUrl('https://exemple.fr', 'playing'), 'https://exemple.fr');
});
it('formats a delay the way the embeds show it', () => {
assert.equal(formatSeconds(30), '30 s');
assert.equal(formatSeconds(60), '1 min');
assert.equal(formatSeconds(3600), '1 h');
assert.equal(formatSeconds(9000), '2 h 30 min');
});
});
describe('bot status rotation', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM bot_statuses');
getDatabase().exec(`DELETE FROM guild_settings WHERE key = '${ROTATION_KEY}'`);
});
const client = () => {
const presences = [];
return { presences, user: { setPresence: (payload) => presences.push(payload) } };
};
it('walks the enabled statuses one after the other, then starts over', () => {
const first = addBotStatus({ text: 'un' });
const second = addBotStatus({ text: 'deux' });
const third = addBotStatus({ text: 'trois', type: 'listening' });
setBotStatusEnabled(third.id, false);
const statuses = listEnabledBotStatuses();
assert.equal(selectNextStatus(statuses).id, first.id);
assert.equal(selectNextStatus(statuses, first.id).id, second.id);
assert.equal(selectNextStatus(statuses, second.id).id, first.id);
assert.equal(selectNextStatus([]), null);
});
it('shows the statuses in Discord with the right activity type', () => {
addBotStatus({ text: 'les tickets', type: 'listening' });
addBotStatus({ text: 'en direct', type: 'streaming', url: 'https://twitch.tv/fws' });
const fake = client();
const first = rotateBotStatus(fake);
const second = rotateBotStatus(fake, first.id);
assert.deepEqual(fake.presences[0].activities[0], { name: 'les tickets', type: 2 });
assert.equal(fake.presences[1].activities[0].url, 'https://twitch.tv/fws');
assert.equal(second.id !== first.id, true);
});
it('falls back to the default line instead of showing nothing', () => {
const fake = client();
assert.equal(rotateBotStatus(fake), FALLBACK_STATUS);
assert.equal(fake.presences[0].activities[0].name, FALLBACK_STATUS.text);
});
it('shows a lone status right away', () => {
const status = addBotStatus({ text: 'seul statut' });
const fake = client();
assert.equal(applyStatusIfAlone(fake).id, status.id);
addBotStatus({ text: 'un autre' });
assert.equal(applyStatusIfAlone(fake), null, 'with several statuses the rotation decides');
});
it('refuses the same text twice and stops at the maximum', () => {
addBotStatus({ text: 'unique' });
assert.throws(() => addBotStatus({ text: 'unique' }), UserFacingError);
for (let index = countBotStatuses(); index < STATUS_MAX; index += 1) {
addBotStatus({ text: `statut ${index}` });
}
assert.equal(countBotStatuses(), STATUS_MAX);
assert.throws(() => addBotStatus({ text: 'un de trop' }), UserFacingError);
});
it('pauses and resumes a status without losing it', () => {
const status = addBotStatus({ text: 'en pause' });
const paused = toggleBotStatus(status.id, false);
assert.equal(paused.enabled, 0);
assert.equal(listEnabledBotStatuses().length, 0);
assert.throws(() => toggleBotStatus(status.id, false), UserFacingError);
toggleBotStatus(status.id, true);
assert.equal(listEnabledBotStatuses()[0].id, status.id);
assert.throws(() => toggleBotStatus(999, true), UserFacingError);
});
it('empties the list and forgets every status', () => {
addBotStatus({ text: 'un' });
addBotStatus({ text: 'deux' });
assert.equal(clearBotStatusList(), 2);
assert.equal(countBotStatuses(), 0);
assert.equal(clearBotStatusList(), 0);
});
it('keeps the rotation delay between the allowed bounds, database first', () => {
assert.equal(clampRotation(30), 30);
assert.equal(clampRotation(ROTATION_MIN_SECONDS - 1), 60, 'an unusable value falls back to the default');
assert.equal(clampRotation(ROTATION_MAX_SECONDS + 1), 60);
assert.throws(() => clampRotation(1, { strict: true }), UserFacingError);
saveRotationSeconds(45, GUILD, 'u1');
assert.equal(getRotationSeconds(GUILD), 45);
setSetting(GUILD, ROTATION_KEY, 'pas un nombre', 'u1');
assert.equal(getRotationSeconds(GUILD), 60, 'a corrupted setting never breaks the rotation');
assert.equal(getRotationSeconds('autre-serveur'), 60);
});
it('lists the statuses with their state and the current rhythm', () => {
const empty = statusListEmbed({ guildId: GUILD, statuses: [] });
assert.match(empty.data.description, /Aucun statut personnalisé/);
const status = addBotStatus({ text: 'les commandes avec /help' });
const embed = statusListEmbed({ guildId: GUILD, statuses: listBotStatuses() });
assert.match(embed.data.description, /\*\*1\*\* statut\(s\), dont \*\*1\*\* en rotation/);
assert.equal(embed.data.fields[0].name, `#${status.id} · ✅ en rotation`);
assert.match(embed.data.fields[0].value, /les commandes avec \/help/);
});
});
+50
View File
@@ -0,0 +1,50 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { describe, it } from 'node:test';
const read = (file) => readFileSync(new URL(`../${file}`, import.meta.url), 'utf8');
const headingCount = (text, level) => (text.match(new RegExp(`^${'#'.repeat(level)} `, 'gm')) ?? []).length;
const commandNames = (text) => new Set([...text.matchAll(/`\/([a-z]+)/g)].map((match) => match[1]));
const envTokens = (text) => new Set(text.match(/\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b/g) ?? []);
/** The organisation requires both READMEs, kept in sync (`.profile/README.md`). */
describe('bilingual documentation', () => {
it('keeps README.md and README.en.md structurally in sync', () => {
const fr = read('README.md');
const en = read('README.en.md');
assert.equal(headingCount(en, 2), headingCount(fr, 2), 'a section is missing on one side');
assert.equal(headingCount(en, 3), headingCount(fr, 3), 'a subsection is missing on one side');
});
it('documents the same commands and environment variables in both languages', () => {
const fr = read('README.md');
const en = read('README.en.md');
assert.deepEqual([...commandNames(en)].sort(), [...commandNames(fr)].sort(), 'command list differs');
assert.deepEqual([...envTokens(en)].sort(), [...envTokens(fr)].sort(), 'environment list differs');
});
it('links the two versions to each other', () => {
assert.match(read('README.md'), /README\.en\.md/, 'the French README does not link the English one');
assert.match(read('README.en.md'), /README\.md/, 'the English README does not link the French one');
});
it('ships the organisation files', () => {
assert.match(read('CHANGELOG.md'), /^# Changelog/, 'the generated changelog is missing');
assert.match(read('AGENTS.md'), /Instructions pour les agents/, 'the agent instructions are missing');
assert.match(
read('.gitea/PULL_REQUEST_TEMPLATE.md'),
/Conventional Commits/,
'the pull request template is missing',
);
assert.match(
read('.gitea/ISSUE_TEMPLATE/bug.md'),
/Étapes de reproduction/,
'the bug report template is missing',
);
assert.match(read('.gitignore'), /^\.env$/m, 'the environment files are not ignored');
assert.match(read('.gitignore'), /^\.freebuff\/$/m, 'the assistant data is not ignored');
});
});
+35 -3
View File
@@ -30,11 +30,15 @@ describe('command modules', () => {
});
it('only overrides the access of declared subcommands', async () => {
/** Top-level subcommands and those nested in a subcommand group (M14). */
const subcommandNames = (options = []) =>
options.flatMap((option) =>
option.type === 1 ? [option.name] : option.type === 2 ? subcommandNames(option.options) : [],
);
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);
const subcommands = subcommandNames(command.data.toJSON().options);
for (const name of Object.keys(command.subcommandAccess)) {
assert.ok(subcommands.includes(name), `/${command.data.name} ${name} is not a subcommand`);
}
@@ -42,6 +46,34 @@ describe('command modules', () => {
});
});
describe('message tone', () => {
it('builds every embed with the shared titles, marker and hint', async () => {
const { TONE, bullets, errorEmbed, successEmbed, warningEmbed, withHint } =
await import('../src/ui/embeds.js');
assert.equal(successEmbed('x').data.title, TONE.success);
assert.equal(errorEmbed('x').data.title, TONE.error);
assert.equal(warningEmbed('x').data.title, TONE.warning);
assert.equal(bullets(['a', 'b', '']), '• a\n• b');
assert.equal(withHint('fait', 'ensuite'), 'fait\n\nensuite');
assert.equal(withHint('fait', null), 'fait');
});
it('keeps command descriptions free of gendered wording', async () => {
/** Words that would address or describe a person with a gender. */
const gendered =
/\b(utilisateur|utilisatrice|cher|chère|ravi|ravie|content|contente|bienvenu|bienvenue à (lui|elle))/i;
for (const command of await loadCommands()) {
const json = command.data.toJSON();
const texts = [json.description, ...(json.options ?? []).map((option) => option.description ?? '')];
for (const text of texts) {
assert.ok(!gendered.test(text), `/${json.name} uses gendered wording: ${text}`);
}
}
});
});
describe('webhook entry points', () => {
it('exposes the server and the dispatch functions', async () => {
const server = await import('../src/webhooks/server.js');
+3 -3
View File
@@ -9,11 +9,11 @@ describe('parseChoices', () => {
});
it('rejects a single choice', () => {
assert.throws(() => parseChoices('Oui'), /entre 2 et 10 choix/);
assert.throws(() => parseChoices('Oui'), /entre 2 et 10 propositions/);
});
it('rejects duplicated choices regardless of case', () => {
assert.throws(() => parseChoices('Oui;oui'), /différents/);
assert.throws(() => parseChoices('Oui;oui'), /Deux propositions identiques/);
});
it('rejects more choices than allowed', () => {
@@ -42,7 +42,7 @@ describe('buildPollEmbed', () => {
{ choice_index: 0, count: 3 },
{ choice_index: 1, count: 1 },
]);
assert.equal(embed.data.title, 'Sondage #3 — Quel thème ?');
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');
+391
View File
@@ -4,6 +4,7 @@ import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.
import {
addVoiceChannel,
countVoiceChannels,
countVoiceChannelsByTrigger,
getVoiceChannel,
listOwnedVoiceChannels,
listVoiceChannels,
@@ -13,13 +14,28 @@ import {
setVoiceName,
setVoiceOwner,
} from '../src/database/repositories/voice-repository.js';
import { ChannelType, Collection } from 'discord.js';
import { PermissionDeniedError, UserFacingError } from '../src/core/errors.js';
import { setSetting } from '../src/database/repositories/settings-repository.js';
import {
assertVoiceOwner,
bottomPosition,
buildChannelName,
clampLimit,
cleanupVoiceChannel,
createFromTrigger,
deleteVoiceChannel,
findTrigger,
getVoiceTrigger,
getVoiceTriggers,
isStaff,
listTriggerSummaries,
removeVoiceTriggerConfig,
sanitizeChannelName,
saveVoiceTrigger,
setTriggerEnabled,
startVoiceJanitor,
sweepVoiceChannels,
} from '../src/services/voice/voice-service.js';
const member = (roleIds = [], { id = 'u1', guildOwnerId = 'someone-else' } = {}) => ({
@@ -85,6 +101,374 @@ describe('voice repository', () => {
assert.equal(getVoiceChannel('c1'), null);
assert.equal(removeVoiceChannel('c1'), 0);
});
it('counts the channels created from one trigger only', () => {
addVoiceChannel({ channelId: 'c1', guildId: 'g', ownerId: 'u1', triggerId: 'dev', name: 'd' });
addVoiceChannel({ channelId: 'c2', guildId: 'g', ownerId: 'u2', triggerId: 'dev', name: 'd' });
addVoiceChannel({ channelId: 'c3', guildId: 'g', ownerId: 'u3', triggerId: 'sio', name: 's' });
assert.equal(countVoiceChannelsByTrigger('dev'), 2);
assert.equal(countVoiceChannelsByTrigger('sio'), 1);
assert.equal(countVoiceChannelsByTrigger('unknown'), 0);
});
});
describe('voice triggers', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM voice_triggers');
getDatabase().exec("DELETE FROM guild_settings WHERE key LIKE 'voice.%'");
});
const declared = (guildId = 'g') =>
getVoiceTriggers(guildId).filter((trigger) => trigger.source === 'database');
it('declares several triggers, each with its own category', () => {
saveVoiceTrigger('g', {
triggerId: 'dev',
label: 'Dev',
categoryId: 'cat-dev',
template: '🛠️ Salon de {user}',
userLimit: 4,
});
saveVoiceTrigger('g', { triggerId: 'sio', label: 'SIO', categoryId: 'cat-sio' });
assert.deepEqual(
declared().map((trigger) => trigger.triggerId),
['dev', 'sio'],
);
const dev = findTrigger('g', 'dev');
assert.equal(dev.categoryId, 'cat-dev');
assert.equal(dev.template, '🛠️ Salon de {user}');
assert.equal(dev.userLimit, 4);
assert.equal(findTrigger('g', 'sio').categoryId, 'cat-sio');
assert.equal(getVoiceTrigger('g', 'inconnu'), null);
});
it('keeps the stored values of the fields that are not passed again', () => {
saveVoiceTrigger('g', { triggerId: 'dev', label: 'Dev', categoryId: 'cat-dev', userLimit: 4 });
saveVoiceTrigger('g', { triggerId: 'dev', categoryId: 'cat-2' });
const dev = findTrigger('g', 'dev');
assert.equal(dev.label, 'Dev');
assert.equal(dev.categoryId, 'cat-2');
assert.equal(dev.template, '🔊 Salon de {user}');
assert.equal(dev.userLimit, 4);
});
it('falls back to the settings written by the single-trigger version', () => {
setSetting('g', 'voice.trigger', 'legacy');
setSetting('g', 'voice.category', 'cat-legacy');
const legacy = getVoiceTriggers('g').find((trigger) => trigger.triggerId === 'legacy');
assert.equal(legacy.source, 'settings');
assert.equal(legacy.categoryId, 'cat-legacy');
assert.equal(legacy.enabled, true);
saveVoiceTrigger('g', { triggerId: 'legacy', categoryId: 'cat-new' });
const matches = getVoiceTriggers('g').filter((trigger) => trigger.triggerId === 'legacy');
assert.equal(matches.length, 1, 'a declared trigger replaces the inherited one');
assert.equal(matches[0].categoryId, 'cat-new');
assert.equal(matches[0].source, 'database');
});
it('can disable a trigger inherited from the settings', () => {
setSetting('g', 'voice.trigger', 'legacy');
setTriggerEnabled('g', 'legacy', false);
const disabled = findTrigger('g', 'legacy');
assert.equal(disabled.enabled, false);
assert.equal(disabled.source, 'database', 'the inherited trigger is written before being disabled');
assert.equal(getVoiceTrigger('g', 'legacy'), null);
});
it('switches a trigger off and back on without losing its settings', () => {
saveVoiceTrigger('g', { triggerId: 'dev', label: 'Dev', categoryId: 'cat-dev' });
setTriggerEnabled('g', 'dev', false);
assert.equal(findTrigger('g', 'dev').enabled, false);
assert.equal(getVoiceTrigger('g', 'dev'), null, 'a disabled trigger creates no channel');
assert.throws(() => setTriggerEnabled('g', 'dev', false), UserFacingError);
setTriggerEnabled('g', 'dev', true);
assert.equal(getVoiceTrigger('g', 'dev').categoryId, 'cat-dev');
assert.throws(() => setTriggerEnabled('g', 'sio', true), UserFacingError);
});
it('removes a declared trigger but never an inherited one', () => {
saveVoiceTrigger('g', { triggerId: 'dev', categoryId: 'cat-dev' });
removeVoiceTriggerConfig('g', 'dev');
assert.equal(findTrigger('g', 'dev'), null);
assert.throws(() => removeVoiceTriggerConfig('g', 'dev'), UserFacingError);
});
it('reports every trigger with the channels it currently hosts', () => {
saveVoiceTrigger('g', { triggerId: 'dev', label: 'Dev', categoryId: 'cat-dev' });
addVoiceChannel({ channelId: 'c1', guildId: 'g', ownerId: 'u1', triggerId: 'dev', name: 'd' });
const summary = listTriggerSummaries('g').find((trigger) => trigger.triggerId === 'dev');
assert.equal(summary.label, 'Dev');
assert.equal(summary.activeChannels, 1);
});
});
describe('voice channel creation from a trigger', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM voice_triggers');
getDatabase().exec('DELETE FROM voice_channels');
});
const makeChannel = (id, { parentId = null, position = 0, type = ChannelType.GuildVoice } = {}) => ({
id,
name: `salon-${id}`,
type,
parentId,
position,
userLimit: 0,
members: new Collection(),
guild: null,
isSendable: () => true,
isVoiceBased: () => type === ChannelType.GuildVoice,
send: async () => ({ id: `message-${id}` }),
delete: async () => true,
setPosition: async function setPosition(target) {
this.position = target;
return this;
},
permissionOverwrites: { edit: async () => {} },
});
const makeGuild = (channels) => {
const cache = new Collection(channels.map((channel) => [channel.id, channel]));
const created = [];
const guild = {
id: 'g',
roles: { everyone: { id: 'everyone' } },
channels: {
cache,
fetch: async (id) => cache.get(id) ?? null,
create: async (options) => {
created.push(options);
const channel = makeChannel(`nouveau-${created.length}`, {
parentId: options.parent ?? null,
position: cache.size,
});
channel.name = options.name;
channel.userLimit = options.userLimit;
channel.guild = guild;
cache.set(channel.id, channel);
return channel;
},
},
};
for (const channel of cache.values()) channel.guild = guild;
return { guild, created, cache };
};
const makeMember = (guild, { id = 'u1', displayName = 'Léa' } = {}) => {
const member = {
id,
displayName,
guild,
moved: [],
user: { tag: `${displayName}#0001`, username: 'lea' },
client: { user: { id: 'bot' } },
};
member.voice = {
setChannel: async (channel) => {
member.moved.push(channel.id);
},
};
return member;
};
const guildWithTwoTriggers = () => {
const { guild, created, cache } = makeGuild([
makeChannel('cat-dev', { type: ChannelType.GuildCategory }),
makeChannel('cat-sio', { type: ChannelType.GuildCategory }),
makeChannel('trig-dev', { parentId: 'cat-dev', position: 0 }),
makeChannel('trig-sio', { parentId: 'cat-sio', position: 0 }),
]);
saveVoiceTrigger('g', {
triggerId: 'trig-dev',
label: 'Dev',
categoryId: 'cat-dev',
template: '🛠️ {user}',
userLimit: 3,
});
saveVoiceTrigger('g', { triggerId: 'trig-sio', label: 'SIO', categoryId: 'cat-sio' });
return { guild, created, cache };
};
it('creates the channel at the bottom of the category of the trigger that was joined', async () => {
const { guild, created, cache } = guildWithTwoTriggers();
const member = makeMember(guild);
await createFromTrigger(member, getVoiceTrigger('g', 'trig-dev'));
assert.equal(created.length, 1);
assert.equal(created[0].parent, 'cat-dev');
assert.equal(created[0].name, '🛠️ Léa');
assert.equal(created[0].userLimit, 3);
assert.equal(member.moved.at(-1), 'nouveau-1', 'the member is moved into their channel');
const channel = cache.get('nouveau-1');
const siblings = [...cache.values()].filter((candidate) => candidate.parentId === 'cat-dev');
assert.equal(siblings.length, 2, 'the trigger and the temporary channel share the category');
assert.equal(channel.position, siblings.length - 1, 'the channel sits below the trigger');
const row = getVoiceChannel('nouveau-1');
assert.equal(row.trigger_id, 'trig-dev');
assert.equal(row.owner_id, 'u1');
assert.equal(row.user_limit, 3);
});
it('keeps one channel per trigger and moves the member back into the existing one', async () => {
const { guild, created } = guildWithTwoTriggers();
const member = makeMember(guild);
await createFromTrigger(member, getVoiceTrigger('g', 'trig-dev'));
await createFromTrigger(member, getVoiceTrigger('g', 'trig-sio'));
assert.equal(created.length, 2, 'another trigger gets its own channel');
assert.equal(created[1].parent, 'cat-sio');
assert.equal(created[1].name, '🔊 Salon de Léa');
await createFromTrigger(member, getVoiceTrigger('g', 'trig-dev'));
assert.equal(created.length, 2, 'no third channel for a trigger already served');
assert.equal(member.moved.at(-1), 'nouveau-1');
assert.equal(countVoiceChannels('g'), 2);
});
it('creates nothing when the channel is not an enabled trigger', async () => {
const { guild, created } = guildWithTwoTriggers();
setTriggerEnabled('g', 'trig-dev', false);
assert.equal(await createFromTrigger(makeMember(guild), getVoiceTrigger('g', 'trig-dev')), null);
assert.equal(await createFromTrigger(makeMember(guild, { id: 'u2' }), null), null);
assert.equal(created.length, 0);
});
});
describe('empty generated channels', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM voice_channels');
});
const track = (channelId, ownerId = 'u1', triggerId = 'dev') =>
addVoiceChannel({ channelId, guildId: 'g', ownerId, triggerId, name: `salon-${channelId}` });
const voiceChannel = (id, { members = [] } = {}) => ({
id,
parentId: 'cat',
members: new Collection(members.map((memberId) => [memberId, { id: memberId }])),
deleted: false,
failure: null,
async delete() {
if (this.failure) throw this.failure;
this.deleted = true;
},
});
/** Guild mock whose `fetch` only knows the cached channels, like a channel deleted by hand. */
const makeGuild = (channels) => {
const cache = new Collection(channels.map((channel) => [channel.id, channel]));
const guild = { id: 'g', channels: { cache, fetch: async (id) => cache.get(id) ?? null } };
for (const channel of cache.values()) channel.guild = guild;
return guild;
};
const clientOf = (...guilds) => ({ guilds: { cache: new Collection(guilds.map((g) => [g.id, g])) } });
it('deletes a generated channel as soon as nobody is left in it', async () => {
track('c1');
const channel = voiceChannel('c1');
await cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 0 });
assert.equal(channel.deleted, true);
assert.equal(getVoiceChannel('c1'), null, 'the row is forgotten too');
});
it('keeps a channel that still has members', async () => {
track('c1');
const channel = voiceChannel('c1', { members: ['u2'] });
await cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 0 });
assert.equal(channel.deleted, false);
assert.ok(getVoiceChannel('c1'));
});
it('leaves a grace period during which the owner can come back', async () => {
track('c1');
const channel = voiceChannel('c1');
const pending = cleanupVoiceChannel(makeGuild([channel]), 'c1', { graceMs: 30 });
channel.members.set('u1', { id: 'u1' });
await pending;
await new Promise((resolve) => setTimeout(resolve, 60));
assert.equal(channel.deleted, false, 'the customised channel survives a quick move');
assert.ok(getVoiceChannel('c1'));
});
it('deletes the empty channels and forgets the vanished ones in one sweep', async () => {
track('vide');
track('occupe', 'u2');
track('disparu', 'u3', 'sio');
const empty = voiceChannel('vide');
const busy = voiceChannel('occupe', { members: ['u2'] });
await sweepVoiceChannels(clientOf(makeGuild([empty, busy])));
assert.equal(empty.deleted, true);
assert.equal(busy.deleted, false);
assert.equal(getVoiceChannel('vide'), null);
assert.equal(getVoiceChannel('disparu'), null, 'a channel deleted by hand is forgotten');
assert.ok(getVoiceChannel('occupe'));
});
it('runs that sweep on an interval', async () => {
track('c1');
const channel = voiceChannel('c1');
const timer = startVoiceJanitor(clientOf(makeGuild([channel])), 20);
await new Promise((resolve) => setTimeout(resolve, 60));
clearInterval(timer);
assert.equal(channel.deleted, true);
assert.equal(getVoiceChannel('c1'), null);
});
it('keeps the row when the deletion fails, so the sweep can retry', async () => {
track('c1');
const channel = voiceChannel('c1');
channel.failure = Object.assign(new Error('Missing Permissions'), { code: 50013, status: 403 });
makeGuild([channel]);
assert.equal(await deleteVoiceChannel(channel, 'test'), false);
assert.ok(getVoiceChannel('c1'), 'the channel is not leaked');
channel.failure = null;
assert.equal(await deleteVoiceChannel(channel, 'test'), true);
assert.equal(getVoiceChannel('c1'), null);
});
it('forgets a channel that Discord has already deleted', async () => {
track('c1');
const channel = voiceChannel('c1');
channel.failure = Object.assign(new Error('Unknown Channel'), { code: 10003 });
makeGuild([channel]);
assert.equal(await deleteVoiceChannel(channel, 'test'), true);
assert.equal(getVoiceChannel('c1'), null);
});
});
describe('voice helpers', () => {
@@ -112,6 +496,13 @@ describe('voice helpers', () => {
assert.throws(() => clampLimit(150, { strict: true }), UserFacingError);
assert.throws(() => clampLimit(-1, { strict: true }), UserFacingError);
});
it('places a new channel on the last slot of its category', () => {
assert.equal(bottomPosition(0), 0);
assert.equal(bottomPosition(1), 0);
assert.equal(bottomPosition(2), 1);
assert.equal(bottomPosition(7), 6);
});
});
describe('voice ownership', () => {