10 Commits
Author SHA1 Message Date
nocodeandClaude Opus 5 7d90a4618a docs(core): document project structure
Refs: #12
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:19:15 +02:00
nocodeandClaude Opus 5 7d3864392c chore(docs): add screenshots directory
Refs: #101
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:19:15 +02:00
nocodeandClaude Opus 5 39de988463 chore(observability): keep logs directory in repository
Refs: #17
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:19:15 +02:00
nocodeandClaude Opus 5 0880486231 chore(database): keep data directory in repository
Refs: #16
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:19:15 +02:00
nocodeandClaude Opus 5 300d5c61fb test(database): add sqlite storage tests
Refs: #16
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:19:15 +02:00
nocodeandClaude Opus 5 ae26786578 test(auth): add permission checks tests
Refs: #115
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:19:14 +02:00
nocodeandClaude Opus 5 c759423b15 feat(database): add database initialization script
Refs: #16
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:19:14 +02:00
nocodeandClaude Opus 5 faf394b22e feat(commands): add slash command deployment script
Refs: #24
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:19:14 +02:00
nocodeandClaude Opus 5 8880aa3e28 feat(core): add bot entry point
Refs: #22
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:19:14 +02:00
nocodeandClaude Opus 5 dd35a866ee feat(fun): add fun command skeleton
Refs: #88
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 12:19:14 +02:00
10 changed files with 227 additions and 0 deletions

No files matched your search

View File
Whitespace-only changes.
View File
Whitespace-only changes.
+88
View File
@@ -0,0 +1,88 @@
# Architecture — FWS-Bot
Stack : **Node.js ≥ 22.13** (JavaScript ESM), **discord.js v14**, **SQLite** via le module natif `node:sqlite` (aucune dépendance native à compiler).
## Arborescence
```text
fws-discordbot/
├── .env.example # Modèle de configuration (sans secret)
├── assets/screenshots/ # Captures référencées dans la documentation
├── data/ # Base SQLite et sauvegardes (ignoré par git)
├── docs/ # Documentation technique
├── logs/ # Logs techniques journaliers (ignoré par git)
├── scripts/
│ ├── deploy-commands.js # Enregistre les commandes slash sur le serveur
│ └── init-database.js # Crée la base et applique les migrations
├── src/
│ ├── index.js # Point d'entrée
│ ├── config/
│ │ ├── env.js # Lecture et validation des variables d'environnement
│ │ └── constants.js # Couleurs, niveaux d'accès, catégories de tickets
│ ├── core/
│ │ ├── client.js # Client Discord et intents
│ │ ├── command-loader.js # Chargement automatique de src/commands/**
│ │ ├── event-loader.js # Chargement automatique de src/events/*
│ │ ├── permissions.js # Contrôle central des accès et de la hiérarchie
│ │ ├── logger.js # Logs JSON avec masquage des secrets
│ │ └── errors.js # Erreurs typées (utilisateur, permission, API)
│ ├── commands/<catégorie>/<commande>.js
│ ├── events/ # Un fichier par événement Discord
│ ├── services/ # Logique métier et intégrations (Gitea, notifications…)
│ ├── database/
│ │ ├── index.js # Connexion et migrations
│ │ ├── migrations/ # Fichiers SQL numérotés
│ │ └── repositories/ # Accès aux tables
│ ├── webhooks/ # Serveur HTTP et réception des webhooks Gitea
│ ├── ui/ # Embeds et boutons standardisés
│ └── utils/ # Retry, cooldown…
└── tests/ # Tests node:test
```
## Contrat d'une commande
```js
export const access = ACCESS_LEVELS.STAFF; // niveau minimum
export const subcommandAccess = { create: ACCESS_LEVELS.DEV }; // optionnel
export const data = new SlashCommandBuilder()...;
export async function execute(interaction) {}
```
Le contrôle d'accès est appliqué dans `events/interaction-create.js` avant l'exécution. Une `UserFacingError` est affichée telle quelle ; toute autre erreur est journalisée et remplacée par un message générique.
## Contrat d'un événement
```js
export const name = Events.GuildMemberAdd;
export const once = false; // optionnel
export async function execute(client, ...args) {}
```
## Intents Discord
| Intent | Usage | Privilégié |
| ----------------- | -------------------------------- | ----------------------------------- |
| `Guilds` | Commandes, salons, rôles | Non |
| `GuildMembers` | Bienvenue, départs, rôle initial | **Oui** (à activer dans le portail) |
| `GuildModeration` | Événements de ban | Non |
| `GuildMessages` | `/clear`, salons de tickets | Non |
`MessageContent` n'est pas demandé.
## Lancement local
```bash
npm install
cp .env.example .env # puis remplir les valeurs
npm run db:init
npm run deploy:commands
npm run dev
```
## Qualité
| Commande | Rôle |
| ---------------------- | ----------------- |
| `npm run lint` | ESLint |
| `npm run format:check` | Prettier |
| `npm test` | Tests `node:test` |
View File
Whitespace-only changes.
+13
View File
@@ -0,0 +1,13 @@
import { REST, Routes } from 'discord.js';
import { assertRequiredEnv, env } from '../src/config/env.js';
import { loadCommands } from '../src/core/command-loader.js';
assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']);
const body = (await loadCommands()).map((command) => command.data.toJSON());
const rest = new REST().setToken(env.discord.token);
// Guild commands update instantly, which suits a single-server bot (M2-T05).
await rest.put(Routes.applicationGuildCommands(env.discord.clientId, env.discord.guildId), { body });
console.log(`Registered ${body.length} slash commands on guild ${env.discord.guildId}.`);
+7
View File
@@ -0,0 +1,7 @@
import { env } from '../src/config/env.js';
import { closeDatabase, initDatabase } from '../src/database/index.js';
initDatabase();
closeDatabase();
console.log(`Database ready at ${env.database.path}`);
+12
View File
@@ -0,0 +1,12 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const data = new SlashCommandBuilder().setName('fun').setDescription('Commandes de divertissement');
// TODO(M10-T07): add fun subcommands.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/fun')] });
}
+35
View File
@@ -0,0 +1,35 @@
import { assertRequiredEnv, env } from './config/env.js';
import { createClient } from './core/client.js';
import { loadCommands } from './core/command-loader.js';
import { registerEvents } from './core/event-loader.js';
import { logger } from './core/logger.js';
import { closeDatabase, initDatabase } from './database/index.js';
import { startWebhookServer } from './webhooks/server.js';
assertRequiredEnv(['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID']);
initDatabase();
const client = createClient();
for (const command of await loadCommands()) {
client.commands.set(command.data.name, command);
}
await registerEvents(client);
const webhookServer = env.webhook.enabled ? startWebhookServer(client) : null;
process.on('unhandledRejection', (reason) => logger.error('Unhandled promise rejection', reason));
process.on('uncaughtException', (error) => logger.error('Uncaught exception', error));
async function shutdown(signal) {
logger.info(`Received ${signal}, shutting down`);
webhookServer?.close();
await client.destroy();
closeDatabase();
process.exit(0);
}
process.once('SIGINT', shutdown);
process.once('SIGTERM', shutdown);
await client.login(env.discord.token);
+32
View File
@@ -0,0 +1,32 @@
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import { getSetting, setSetting } from '../src/database/repositories/settings-repository.js';
describe('database', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
it('applies the initial migration', () => {
const tables = getDatabase()
.prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
.all()
.map((row) => row.name);
assert.ok(tables.includes('tickets'));
assert.ok(tables.includes('guild_settings'));
});
it('isolates settings per guild', () => {
setSetting('guild-a', 'welcome', { enabled: true });
assert.deepEqual(getSetting('guild-a', 'welcome'), { enabled: true });
assert.equal(getSetting('guild-b', 'welcome'), null);
});
it('prevents two open tickets for the same author and category', () => {
const insert = getDatabase().prepare(
"INSERT INTO tickets (guild_id, category_id, author_id) VALUES ('g', 'bug', 'u')",
);
insert.run();
assert.throws(() => insert.run(), /UNIQUE/);
});
});
+40
View File
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { ACCESS_LEVELS } from '../src/config/constants.js';
import { getAccessLevel, hasAccess } from '../src/core/permissions.js';
const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff', member: 'r-member' };
const fakeMember = (roleIds, { id = 'u1', ownerId = 'someone-else' } = {}) => ({
id,
guild: { ownerId },
roles: { cache: new Set(roleIds) },
});
describe('getAccessLevel', () => {
it('returns USER for a member without FWS roles', () => {
assert.equal(getAccessLevel(fakeMember(['r-member']), roles), ACCESS_LEVELS.USER);
});
it('returns the highest level when a member has several roles', () => {
assert.equal(getAccessLevel(fakeMember(['r-staff', 'r-dev']), roles), ACCESS_LEVELS.DEV);
});
it('returns OWNER for the guild owner', () => {
assert.equal(getAccessLevel(fakeMember([], { id: 'u1', ownerId: 'u1' }), roles), ACCESS_LEVELS.OWNER);
});
it('ignores unconfigured role ids', () => {
assert.equal(getAccessLevel(fakeMember(['']), { owner: '', dev: '', staff: '' }), ACCESS_LEVELS.USER);
});
});
describe('hasAccess', () => {
it('denies a staff command to a regular user', () => {
assert.equal(hasAccess(fakeMember([]), ACCESS_LEVELS.STAFF, roles), false);
});
it('allows a staff command to an owner', () => {
assert.equal(hasAccess(fakeMember(['r-owner']), ACCESS_LEVELS.STAFF, roles), true);
});
});