Files
FWS-DiscordBot/README.en.md
T

474 lines
45 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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)