From 9bbe9cb0b4cf987940b7115517516143753fd0e7 Mon Sep 17 00:00:00 2001 From: BlackAngelTVdev Date: Tue, 15 Sep 2026 16:15:00 +0200 Subject: [PATCH] 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. --- .gitea/ISSUE_TEMPLATE/bug.md | 39 +++ .gitea/ISSUE_TEMPLATE/enhancement.md | 29 ++ .gitea/PULL_REQUEST_TEMPLATE.md | 28 ++ README.en.md | 473 +++++++++++++++++++++++++++ README.md | 117 +++++-- tests/docs.test.js | 50 +++ 6 files changed, 713 insertions(+), 23 deletions(-) create mode 100644 .gitea/ISSUE_TEMPLATE/bug.md create mode 100644 .gitea/ISSUE_TEMPLATE/enhancement.md create mode 100644 .gitea/PULL_REQUEST_TEMPLATE.md create mode 100644 README.en.md create mode 100644 tests/docs.test.js diff --git a/.gitea/ISSUE_TEMPLATE/bug.md b/.gitea/ISSUE_TEMPLATE/bug.md new file mode 100644 index 0000000..dcd3d8e --- /dev/null +++ b/.gitea/ISSUE_TEMPLATE/bug.md @@ -0,0 +1,39 @@ +--- +name: Bug +about: Signaler un comportement inattendu +title: "[bug] " +labels: bug +--- + +## Description + + + +## Étapes de reproduction + +1. +2. +3. + +## Comportement attendu + + + +## Comportement observé + + + +## Environnement + +- OS : +- Node.js (`node -v`) : +- Version du bot (`version` dans `package.json`) : +- Serveur / salon concerné : + +## Logs + + + +## Contexte + + diff --git a/.gitea/ISSUE_TEMPLATE/enhancement.md b/.gitea/ISSUE_TEMPLATE/enhancement.md new file mode 100644 index 0000000..2e7fa1d --- /dev/null +++ b/.gitea/ISSUE_TEMPLATE/enhancement.md @@ -0,0 +1,29 @@ +--- +name: Demande / amélioration +about: Proposer une fonctionnalité ou une amélioration +title: "[enhancement] " +labels: enhancement +--- + +## Besoin + + + +## Proposition + + + +## Alternatives envisagées + + + +## 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 + + diff --git a/.gitea/PULL_REQUEST_TEMPLATE.md b/.gitea/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..67b2059 --- /dev/null +++ b/.gitea/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,28 @@ +## Objectif + + + +Fixes # + +## Ce que fait la pull request + + + +## Comment tester + + + +## 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 (`(): `) +- [ ] 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) diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..06ceed7 --- /dev/null +++ b/README.en.md @@ -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 `. 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// # 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: `(): `. +- 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) diff --git a/README.md b/README.md index 462462b..889495a 100644 --- a/README.md +++ b/README.md @@ -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** : `(): ` — 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** : `(): `. +- 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) diff --git a/tests/docs.test.js b/tests/docs.test.js new file mode 100644 index 0000000..478ed80 --- /dev/null +++ b/tests/docs.test.js @@ -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'); + }); +});