Compare commits
59
Commits
main
...
7d90a4618a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d90a4618a
|
||
|
|
7d3864392c
|
||
|
|
39de988463
|
||
|
|
0880486231
|
||
|
|
300d5c61fb
|
||
|
|
ae26786578
|
||
|
|
c759423b15
|
||
|
|
faf394b22e
|
||
|
|
8880aa3e28
|
||
|
|
dd35a866ee
|
||
|
|
2d7e78badb
|
||
|
|
cc516e8f8f
|
||
|
|
a08a8d98e6
|
||
|
|
2084935a22
|
||
|
|
dc1fc3423b
|
||
|
|
de97a6a4a2
|
||
|
|
830c5bc035
|
||
|
|
cf2565d88c
|
||
|
|
9bcf18323c
|
||
|
|
ed19105080
|
||
|
|
5af2bea66a
|
||
|
|
0ac105038e
|
||
|
|
1fb1ff8c79
|
||
|
|
296f3c1aa7
|
||
|
|
4c20d1d8c4
|
||
|
|
025045edf3
|
||
|
|
8a866a7f2f
|
||
|
|
d76e1a34da
|
||
|
|
64039c9d06
|
||
|
|
a54affd741
|
||
|
|
007ffc103e
|
||
|
|
df8f43a4fd
|
||
|
|
eb91348b61
|
||
|
|
dd9892baf1
|
||
|
|
71e30810b8
|
||
|
|
af5f7e0b30
|
||
|
|
55c0322217
|
||
|
|
ea7026e83c
|
||
|
|
2c9221c728
|
||
|
|
1e4bfba3cf
|
||
|
|
835e1d0edf
|
||
|
|
1914cee0eb
|
||
|
|
4c9b5c24c9
|
||
|
|
36dc63e882
|
||
|
|
228a583255
|
||
|
|
878f971809
|
||
|
|
76872df80d
|
||
|
|
0b3a9c139d
|
||
|
|
a82bc1b962
|
||
|
|
2e13919bb3
|
||
|
|
88441821fe
|
||
|
|
d3dac80520
|
||
|
|
6803d08ef7
|
||
|
|
258739faf5
|
||
|
|
5c578030d2
|
||
|
|
25e3aaeae5
|
||
|
|
54454af0f1
|
||
|
|
c17f4ead39
|
||
|
|
b1857a9047
|
No files matched your search
@@ -0,0 +1,9 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
@@ -0,0 +1,70 @@
|
||||
# =============================================================================
|
||||
# FWS-Bot — environment configuration example
|
||||
# Copy this file to `.env` and fill in the values. Never commit `.env`.
|
||||
# =============================================================================
|
||||
|
||||
# --- Runtime -----------------------------------------------------------------
|
||||
# development | production | test
|
||||
NODE_ENV=development
|
||||
# debug | info | warn | error
|
||||
LOG_LEVEL=info
|
||||
LOG_DIR=./logs
|
||||
# Number of days functional/technical logs are kept (M11-T08)
|
||||
LOG_RETENTION_DAYS=30
|
||||
|
||||
# --- Discord application (M2-T01) -------------------------------------------
|
||||
# Developer Portal > Bot > Token
|
||||
DISCORD_TOKEN=
|
||||
# Developer Portal > General Information > Application ID
|
||||
DISCORD_CLIENT_ID=
|
||||
# FWS server ID (slash commands are registered on this guild)
|
||||
DISCORD_GUILD_ID=
|
||||
|
||||
# --- FWS roles (M3-T01) — Discord role IDs ----------------------------------
|
||||
ROLE_OWNER_ID=
|
||||
ROLE_DEV_ID=
|
||||
ROLE_STAFF_ID=
|
||||
# Role given to new members on join (M7-T03)
|
||||
ROLE_MEMBER_ID=
|
||||
|
||||
# --- Discord channels (M0-T04 / M9-T01) — channel IDs -----------------------
|
||||
CHANNEL_WELCOME_ID=
|
||||
CHANNEL_RULES_ID=
|
||||
CHANNEL_ANNOUNCEMENTS_ID=
|
||||
CHANNEL_LOGS_ID=
|
||||
CHANNEL_MOD_LOGS_ID=
|
||||
CHANNEL_TICKETS_LOGS_ID=
|
||||
CHANNEL_NOTIF_ISSUES_ID=
|
||||
CHANNEL_NOTIF_PULL_REQUESTS_ID=
|
||||
CHANNEL_NOTIF_COMMITS_ID=
|
||||
CHANNEL_NOTIF_RELEASES_ID=
|
||||
CHANNEL_NOTIF_ERRORS_ID=
|
||||
# Category under which private ticket channels are created (M6)
|
||||
CATEGORY_TICKETS_ID=
|
||||
|
||||
# --- Gitea (M5-T01) ----------------------------------------------------------
|
||||
GITEA_URL=https://gitea.nocode-var.tech
|
||||
# Token with least privilege (read:repository, write:issue). Never log it.
|
||||
GITEA_TOKEN=
|
||||
GITEA_OWNER=FWS
|
||||
GITEA_REPO=FWS-Arch
|
||||
GITEA_TIMEOUT_MS=10000
|
||||
GITEA_MAX_RETRIES=2
|
||||
|
||||
# --- Gitea webhooks (M9-T02) -------------------------------------------------
|
||||
WEBHOOK_ENABLED=false
|
||||
WEBHOOK_HOST=0.0.0.0
|
||||
WEBHOOK_PORT=3000
|
||||
WEBHOOK_PATH=/webhooks/gitea
|
||||
# Shared secret configured in Gitea > Settings > Webhooks
|
||||
GITEA_WEBHOOK_SECRET=
|
||||
|
||||
# --- SQLite (M1-T05) ---------------------------------------------------------
|
||||
DATABASE_PATH=./data/fws-bot.sqlite
|
||||
BACKUP_DIR=./data/backups
|
||||
|
||||
# --- FWS links (M0-T06 / M4-T04) ---------------------------------------------
|
||||
FWS_WEBSITE_URL=
|
||||
FWS_DOCS_URL=
|
||||
FWS_DISCORD_INVITE_URL=
|
||||
FWS_ARCH_REPO_URL=
|
||||
+31
-170
@@ -1,176 +1,37 @@
|
||||
# ---> Python
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
||||
.pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
# Environment and secrets
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
.env.*
|
||||
!.env.example
|
||||
.freebuff
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
# SQLite databases and backups
|
||||
data/*
|
||||
!data/.gitkeep
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.db
|
||||
*.db-journal
|
||||
*-wal
|
||||
*-shm
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
# Logs
|
||||
logs/*
|
||||
!logs/.gitkeep
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
# Build and coverage
|
||||
dist/
|
||||
build/
|
||||
coverage/
|
||||
.cache/
|
||||
|
||||
# Editors and OS
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
data/
|
||||
logs/
|
||||
package-lock.json
|
||||
README.md
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"printWidth": 110,
|
||||
"semi": true
|
||||
}
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -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` |
|
||||
@@ -0,0 +1,21 @@
|
||||
import js from '@eslint/js';
|
||||
import prettier from 'eslint-config-prettier';
|
||||
import globals from 'globals';
|
||||
|
||||
export default [
|
||||
{ ignores: ['node_modules/', 'data/', 'logs/', 'coverage/'] },
|
||||
js.configs.recommended,
|
||||
{
|
||||
languageOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
globals: globals.node,
|
||||
},
|
||||
rules: {
|
||||
'no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
|
||||
'prefer-const': 'error',
|
||||
eqeqeq: ['error', 'always'],
|
||||
},
|
||||
},
|
||||
prettier,
|
||||
];
|
||||
Whitespace-only changes.
Generated
+1443
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "fws-discordbot",
|
||||
"version": "0.1.0",
|
||||
"description": "FWS-Bot — Discord bot for the FWS open source organization",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "src/index.js",
|
||||
"engines": {
|
||||
"node": ">=22.13.0"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node src/index.js",
|
||||
"dev": "node --watch src/index.js",
|
||||
"deploy:commands": "node scripts/deploy-commands.js",
|
||||
"db:init": "node scripts/init-database.js",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check .",
|
||||
"test": "node --test tests/"
|
||||
},
|
||||
"dependencies": {
|
||||
"discord.js": "^14.21.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.30.0",
|
||||
"eslint": "^9.30.0",
|
||||
"eslint-config-prettier": "^10.1.5",
|
||||
"globals": "^16.3.0",
|
||||
"prettier": "^3.6.2"
|
||||
}
|
||||
}
|
||||
@@ -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}.`);
|
||||
@@ -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}`);
|
||||
@@ -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')] });
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.STAFF;
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('poll')
|
||||
.setDescription('Sondages')
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('create')
|
||||
.setDescription('Créer un sondage')
|
||||
.addStringOption((option) =>
|
||||
option.setName('question').setDescription('Question').setRequired(true).setMaxLength(200),
|
||||
)
|
||||
.addStringOption((option) =>
|
||||
option.setName('choices').setDescription('Choix séparés par ";" (2 à 10)').setRequired(true),
|
||||
)
|
||||
.addIntegerOption((option) =>
|
||||
option.setName('minutes').setDescription('Durée en minutes').setMinValue(1).setMaxValue(10_080),
|
||||
),
|
||||
)
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('close')
|
||||
.setDescription('Fermer un sondage')
|
||||
.addIntegerOption((option) => option.setName('id').setDescription('ID du sondage').setRequired(true)),
|
||||
);
|
||||
|
||||
// TODO(M10-T01..T06): implement with polls / poll_votes tables.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed(`/poll ${interaction.options.getSubcommand()}`)] });
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
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('stats')
|
||||
.setDescription('Statistiques publiques')
|
||||
.addSubcommand((sub) => sub.setName('discord').setDescription('Statistiques du serveur Discord'))
|
||||
.addSubcommand((sub) => sub.setName('gitea').setDescription('Activité et indicateurs Gitea'))
|
||||
.addSubcommand((sub) => sub.setName('fws').setDescription('Indicateurs FWS / FWS Arch'));
|
||||
|
||||
// TODO(M11-T02..T04): implement per data source.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed(`/stats ${interaction.options.getSubcommand()}`)] });
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { env } from '../../config/env.js';
|
||||
import { linkButtons } from '../../ui/buttons.js';
|
||||
import { baseEmbed, notImplementedEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.USER;
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('fws')
|
||||
.setDescription('Informations sur FWS et FWS Arch')
|
||||
.addSubcommand((sub) => sub.setName('info').setDescription('Présente FWS et FWS Arch'))
|
||||
.addSubcommand((sub) => sub.setName('version').setDescription('Version actuelle de FWS Arch'))
|
||||
.addSubcommand((sub) => sub.setName('status').setDescription('État des services et projets'))
|
||||
.addSubcommand((sub) => sub.setName('links').setDescription('Ressources officielles'))
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('changelog')
|
||||
.setDescription("Changements d'une version")
|
||||
.addStringOption((option) => option.setName('version').setDescription('Version (dernière par défaut)')),
|
||||
);
|
||||
|
||||
const officialLinks = () => [
|
||||
{ label: 'Site', url: env.links.website },
|
||||
{ label: 'Documentation', url: env.links.docs },
|
||||
{ label: 'Dépôt FWS Arch', url: env.links.archRepo },
|
||||
{ label: 'Gitea', url: env.gitea.url },
|
||||
{ label: 'Discord', url: env.links.discordInvite },
|
||||
];
|
||||
|
||||
const handlers = {
|
||||
// TODO(M4-T01): content should come from guild_settings (M4-T07).
|
||||
info: (interaction) =>
|
||||
interaction.reply({
|
||||
embeds: [
|
||||
baseEmbed()
|
||||
.setTitle('FWS & FWS Arch')
|
||||
.setDescription(
|
||||
'FWS est une organisation open source multi-projets.\n' +
|
||||
"**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale.",
|
||||
),
|
||||
],
|
||||
components: linkButtons(officialLinks()),
|
||||
}),
|
||||
links: (interaction) =>
|
||||
interaction.reply({
|
||||
embeds: [baseEmbed().setTitle('Liens officiels FWS')],
|
||||
components: linkButtons(officialLinks()),
|
||||
}),
|
||||
version: (interaction) => interaction.reply({ embeds: [notImplementedEmbed('/fws version')] }),
|
||||
status: (interaction) => interaction.reply({ embeds: [notImplementedEmbed('/fws status')] }),
|
||||
changelog: (interaction) => interaction.reply({ embeds: [notImplementedEmbed('/fws changelog')] }),
|
||||
};
|
||||
|
||||
export async function execute(interaction) {
|
||||
await handlers[interaction.options.getSubcommand()](interaction);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { getAccessLevel } from '../../core/permissions.js';
|
||||
import { baseEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.USER;
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('help')
|
||||
.setDescription('Affiche les commandes accessibles selon ton rôle');
|
||||
|
||||
export async function execute(interaction) {
|
||||
const level = getAccessLevel(interaction.member);
|
||||
const lines = interaction.client.commands
|
||||
.filter((command) => (command.access ?? ACCESS_LEVELS.USER) <= level)
|
||||
.map((command) => `\`/${command.data.name}\` — ${command.data.description}`)
|
||||
.sort();
|
||||
|
||||
const embed = baseEmbed().setTitle('Commandes FWS-Bot').setDescription(lines.join('\n'));
|
||||
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
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('gitea')
|
||||
.setDescription('Activité Gitea de FWS Arch')
|
||||
.addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents'))
|
||||
.addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles'));
|
||||
|
||||
// TODO(M5-T06 / M5-T07): implement with services/gitea/gitea-client.js.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed(`/gitea ${interaction.options.getSubcommand()}`)] });
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.USER;
|
||||
|
||||
// TODO(M5-T03): make the required level for `create` configurable per guild.
|
||||
export const subcommandAccess = { create: ACCESS_LEVELS.USER };
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('issue')
|
||||
.setDescription('Issues Gitea')
|
||||
.addSubcommand((sub) => sub.setName('create').setDescription('Créer une issue Gitea'))
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('view')
|
||||
.setDescription('Afficher une issue')
|
||||
.addIntegerOption((option) =>
|
||||
option.setName('number').setDescription("Numéro de l'issue").setRequired(true).setMinValue(1),
|
||||
),
|
||||
)
|
||||
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les issues ouvertes'));
|
||||
|
||||
// TODO(M5-T02 / M5-T03): implement with services/gitea/gitea-client.js.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed(`/issue ${interaction.options.getSubcommand()}`)] });
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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 subcommandAccess = { create: ACCESS_LEVELS.DEV };
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('pr')
|
||||
.setDescription('Pull requests Gitea')
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('create')
|
||||
.setDescription('Créer une pull request')
|
||||
.addStringOption((option) => option.setName('head').setDescription('Branche source').setRequired(true))
|
||||
.addStringOption((option) => option.setName('base').setDescription('Branche cible').setRequired(true)),
|
||||
)
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('view')
|
||||
.setDescription('Afficher une pull request')
|
||||
.addIntegerOption((option) =>
|
||||
option.setName('number').setDescription('Numéro de la PR').setRequired(true).setMinValue(1),
|
||||
),
|
||||
)
|
||||
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les pull requests ouvertes'));
|
||||
|
||||
// TODO(M5-T04 / M5-T05): implement with services/gitea/gitea-client.js.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed(`/pr ${interaction.options.getSubcommand()}`)] });
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.STAFF;
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('ban')
|
||||
.setDescription('Bannir un membre')
|
||||
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
|
||||
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
|
||||
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500))
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
.setName('delete_days')
|
||||
.setDescription('Supprimer les messages des N derniers jours')
|
||||
.setMinValue(0)
|
||||
.setMaxValue(7),
|
||||
);
|
||||
|
||||
// TODO(M8-T04): ban after canActOn() check and log the sensitive action (M8-T09).
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed('/ban')] });
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.STAFF;
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('clear')
|
||||
.setDescription('Supprimer des messages')
|
||||
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages)
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
.setName('amount')
|
||||
.setDescription('Nombre de messages')
|
||||
.setRequired(true)
|
||||
.setMinValue(1)
|
||||
.setMaxValue(100),
|
||||
);
|
||||
|
||||
// TODO(M8-T05): channel.bulkDelete(amount, true) and log the action.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed('/clear')] });
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.STAFF;
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('kick')
|
||||
.setDescription('Expulser un membre du serveur')
|
||||
.setDefaultMemberPermissions(PermissionFlagsBits.KickMembers)
|
||||
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
|
||||
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500));
|
||||
|
||||
// TODO(M8-T03): kick after canActOn() check and log the action.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed('/kick')] });
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.STAFF;
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('mod')
|
||||
.setDescription('Outils de modération')
|
||||
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('logs')
|
||||
.setDescription('Consulter les actions de modération')
|
||||
.addUserOption((option) => option.setName('user').setDescription('Filtrer par membre')),
|
||||
);
|
||||
|
||||
// TODO(M8-T06): read from moderation_actions.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed('/mod logs')] });
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.STAFF;
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('mute')
|
||||
.setDescription('Restreindre temporairement un membre')
|
||||
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
|
||||
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
.setName('minutes')
|
||||
.setDescription('Durée en minutes')
|
||||
.setRequired(true)
|
||||
.setMinValue(1)
|
||||
.setMaxValue(40_320),
|
||||
)
|
||||
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500));
|
||||
|
||||
// TODO(M8-T02 / M8-T07): use member.timeout() after canActOn() check.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed('/mute')] });
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.STAFF;
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('role')
|
||||
.setDescription('Gestion des rôles')
|
||||
.setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles)
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('set')
|
||||
.setDescription('Attribuer ou retirer un rôle')
|
||||
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
|
||||
.addRoleOption((option) => option.setName('role').setDescription('Rôle').setRequired(true))
|
||||
.addStringOption((option) =>
|
||||
option
|
||||
.setName('action')
|
||||
.setDescription('Action')
|
||||
.setRequired(true)
|
||||
.addChoices({ name: 'Ajouter', value: 'add' }, { name: 'Retirer', value: 'remove' }),
|
||||
),
|
||||
);
|
||||
|
||||
// TODO(M7-T05 / M7-T06): enforce role hierarchy (M3-T05) and log the change.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed('/role set')] });
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.STAFF;
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('warn')
|
||||
.setDescription('Avertir un membre')
|
||||
.setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers)
|
||||
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
|
||||
.addStringOption((option) =>
|
||||
option.setName('reason').setDescription('Raison').setRequired(true).setMaxLength(500),
|
||||
);
|
||||
|
||||
// TODO(M8-T01): record in moderation_actions and log (M8-T06).
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed('/warn')] });
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.USER;
|
||||
// `close` is also allowed for the ticket author: checked in the ticket service.
|
||||
export const subcommandAccess = { claim: ACCESS_LEVELS.STAFF, add: ACCESS_LEVELS.STAFF };
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('ticket')
|
||||
.setDescription('Tickets de support privés')
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('create')
|
||||
.setDescription('Ouvrir un ticket')
|
||||
.addStringOption((option) =>
|
||||
option
|
||||
.setName('category')
|
||||
.setDescription('Catégorie du ticket')
|
||||
.setRequired(true)
|
||||
.addChoices(...TICKET_CATEGORIES.map(({ id, label }) => ({ name: label, value: id }))),
|
||||
),
|
||||
)
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('close')
|
||||
.setDescription('Fermer le ticket')
|
||||
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500)),
|
||||
)
|
||||
.addSubcommand((sub) => sub.setName('claim').setDescription('Prendre le ticket en charge'))
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('add')
|
||||
.setDescription('Ajouter un participant')
|
||||
.addUserOption((option) => option.setName('user').setDescription('Membre à ajouter').setRequired(true)),
|
||||
);
|
||||
|
||||
// TODO(M6-T03..T09): implement with a ticket service backed by the tickets table.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({
|
||||
embeds: [notImplementedEmbed(`/ticket ${interaction.options.getSubcommand()}`)],
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
export const BOT_NAME = 'FWS-Bot';
|
||||
|
||||
/** Embed colors by category (M12-T01). */
|
||||
export const COLORS = Object.freeze({
|
||||
primary: 0x1793d1,
|
||||
success: 0x2ecc71,
|
||||
warning: 0xf1c40f,
|
||||
error: 0xe74c3c,
|
||||
info: 0x3498db,
|
||||
gitea: 0x609926,
|
||||
moderation: 0xe67e22,
|
||||
ticket: 0x9b59b6,
|
||||
});
|
||||
|
||||
/** Ordered from least to most privileged (M3-T01). */
|
||||
export const ACCESS_LEVELS = Object.freeze({
|
||||
USER: 0,
|
||||
STAFF: 1,
|
||||
DEV: 2,
|
||||
OWNER: 3,
|
||||
});
|
||||
|
||||
/** Ticket categories and who can see them (M0-T05 / M6-T01). */
|
||||
export const TICKET_CATEGORIES = Object.freeze([
|
||||
{ id: 'support', label: 'Support utilisateur', scope: ['staff', 'owner'] },
|
||||
{ id: 'bug', label: 'Bug', scope: ['staff', 'dev', 'owner'] },
|
||||
{ id: 'dev-question', label: 'Question de développement', scope: ['dev', 'owner'] },
|
||||
{ id: 'report', label: 'Signalement', scope: ['staff', 'owner'] },
|
||||
{ id: 'internal', label: 'Demande interne', scope: ['owner'] },
|
||||
]);
|
||||
|
||||
export const NOTIFICATION_TYPES = Object.freeze([
|
||||
'issues',
|
||||
'pull_requests',
|
||||
'commits',
|
||||
'releases',
|
||||
'announcements',
|
||||
'errors',
|
||||
'community',
|
||||
]);
|
||||
@@ -0,0 +1,86 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
|
||||
if (existsSync('.env')) {
|
||||
process.loadEnvFile('.env');
|
||||
}
|
||||
|
||||
const read = (key, fallback = '') => process.env[key]?.trim() || fallback;
|
||||
const readInt = (key, fallback) => Number.parseInt(read(key), 10) || fallback;
|
||||
const readBool = (key, fallback = false) => {
|
||||
const value = read(key);
|
||||
return value === '' ? fallback : value === 'true';
|
||||
};
|
||||
|
||||
export const env = Object.freeze({
|
||||
nodeEnv: read('NODE_ENV', 'development'),
|
||||
logLevel: read('LOG_LEVEL', 'info'),
|
||||
logDir: read('LOG_DIR', './logs'),
|
||||
logRetentionDays: readInt('LOG_RETENTION_DAYS', 30),
|
||||
|
||||
discord: {
|
||||
token: read('DISCORD_TOKEN'),
|
||||
clientId: read('DISCORD_CLIENT_ID'),
|
||||
guildId: read('DISCORD_GUILD_ID'),
|
||||
},
|
||||
|
||||
roles: {
|
||||
owner: read('ROLE_OWNER_ID'),
|
||||
dev: read('ROLE_DEV_ID'),
|
||||
staff: read('ROLE_STAFF_ID'),
|
||||
member: read('ROLE_MEMBER_ID'),
|
||||
},
|
||||
|
||||
channels: {
|
||||
welcome: read('CHANNEL_WELCOME_ID'),
|
||||
rules: read('CHANNEL_RULES_ID'),
|
||||
announcements: read('CHANNEL_ANNOUNCEMENTS_ID'),
|
||||
logs: read('CHANNEL_LOGS_ID'),
|
||||
modLogs: read('CHANNEL_MOD_LOGS_ID'),
|
||||
ticketLogs: read('CHANNEL_TICKETS_LOGS_ID'),
|
||||
notifIssues: read('CHANNEL_NOTIF_ISSUES_ID'),
|
||||
notifPullRequests: read('CHANNEL_NOTIF_PULL_REQUESTS_ID'),
|
||||
notifCommits: read('CHANNEL_NOTIF_COMMITS_ID'),
|
||||
notifReleases: read('CHANNEL_NOTIF_RELEASES_ID'),
|
||||
notifErrors: read('CHANNEL_NOTIF_ERRORS_ID'),
|
||||
ticketCategory: read('CATEGORY_TICKETS_ID'),
|
||||
},
|
||||
|
||||
gitea: {
|
||||
url: read('GITEA_URL').replace(/\/+$/, ''),
|
||||
token: read('GITEA_TOKEN'),
|
||||
owner: read('GITEA_OWNER'),
|
||||
repo: read('GITEA_REPO'),
|
||||
timeoutMs: readInt('GITEA_TIMEOUT_MS', 10_000),
|
||||
maxRetries: readInt('GITEA_MAX_RETRIES', 2),
|
||||
},
|
||||
|
||||
webhook: {
|
||||
enabled: readBool('WEBHOOK_ENABLED'),
|
||||
host: read('WEBHOOK_HOST', '0.0.0.0'),
|
||||
port: readInt('WEBHOOK_PORT', 3000),
|
||||
path: read('WEBHOOK_PATH', '/webhooks/gitea'),
|
||||
secret: read('GITEA_WEBHOOK_SECRET'),
|
||||
},
|
||||
|
||||
database: {
|
||||
path: read('DATABASE_PATH', './data/fws-bot.sqlite'),
|
||||
backupDir: read('BACKUP_DIR', './data/backups'),
|
||||
},
|
||||
|
||||
links: {
|
||||
website: read('FWS_WEBSITE_URL'),
|
||||
docs: read('FWS_DOCS_URL'),
|
||||
discordInvite: read('FWS_DISCORD_INVITE_URL'),
|
||||
archRepo: read('FWS_ARCH_REPO_URL'),
|
||||
},
|
||||
});
|
||||
|
||||
/** Values that must never appear in Discord messages or logs. */
|
||||
export const secrets = [env.discord.token, env.gitea.token, env.webhook.secret].filter(Boolean);
|
||||
|
||||
export function assertRequiredEnv(keys) {
|
||||
const missing = keys.filter((key) => !read(key));
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Client, Collection, GatewayIntentBits, Partials } from 'discord.js';
|
||||
|
||||
/**
|
||||
* Only the intents required by the bot (M2-T02):
|
||||
* - Guilds: slash commands, channels, roles
|
||||
* - GuildMembers (privileged): welcome, departures, role assignment
|
||||
* - GuildModeration: ban/kick audit events
|
||||
* - GuildMessages: /clear and ticket channels
|
||||
* MessageContent is intentionally not requested.
|
||||
*/
|
||||
export function createClient() {
|
||||
const client = new Client({
|
||||
intents: [
|
||||
GatewayIntentBits.Guilds,
|
||||
GatewayIntentBits.GuildMembers,
|
||||
GatewayIntentBits.GuildModeration,
|
||||
GatewayIntentBits.GuildMessages,
|
||||
],
|
||||
partials: [Partials.GuildMember],
|
||||
});
|
||||
|
||||
client.commands = new Collection();
|
||||
return client;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
const commandsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'commands');
|
||||
|
||||
/**
|
||||
* Loads every command module from src/commands/<category>/<name>.js.
|
||||
* A command module exports: `data` (SlashCommandBuilder), `access` (ACCESS_LEVELS) and `execute`.
|
||||
*/
|
||||
export async function loadCommands() {
|
||||
const entries = await readdir(commandsDir, { recursive: true, withFileTypes: true });
|
||||
const commands = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile() || !entry.name.endsWith('.js')) continue;
|
||||
|
||||
const filePath = path.join(entry.parentPath, entry.name);
|
||||
const command = await import(pathToFileURL(filePath).href);
|
||||
|
||||
if (!command.data || typeof command.execute !== 'function') {
|
||||
throw new Error(`Invalid command module: ${path.relative(commandsDir, filePath)}`);
|
||||
}
|
||||
commands.push(command);
|
||||
}
|
||||
|
||||
return commands;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/** Error whose message is safe to show to Discord users. */
|
||||
export class UserFacingError extends Error {
|
||||
constructor(message, options) {
|
||||
super(message, options);
|
||||
this.name = 'UserFacingError';
|
||||
}
|
||||
}
|
||||
|
||||
export class PermissionDeniedError extends UserFacingError {
|
||||
constructor(message = "Tu n'as pas la permission d'utiliser cette commande.") {
|
||||
super(message);
|
||||
this.name = 'PermissionDeniedError';
|
||||
}
|
||||
}
|
||||
|
||||
export class ExternalApiError extends Error {
|
||||
constructor(service, message, options) {
|
||||
super(`[${service}] ${message}`, options);
|
||||
this.name = 'ExternalApiError';
|
||||
this.service = service;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { createLogger } from './logger.js';
|
||||
|
||||
const eventsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'events');
|
||||
const log = createLogger('events');
|
||||
|
||||
/**
|
||||
* Registers every event module from src/events.
|
||||
* An event module exports: `name`, optional `once` and `execute(client, ...args)`.
|
||||
*/
|
||||
export async function registerEvents(client) {
|
||||
const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js'));
|
||||
|
||||
for (const file of files) {
|
||||
const event = await import(pathToFileURL(path.join(eventsDir, file)).href);
|
||||
const handler = async (...args) => {
|
||||
try {
|
||||
await event.execute(client, ...args);
|
||||
} catch (error) {
|
||||
log.error(`Event handler failed: ${event.name}`, error);
|
||||
}
|
||||
};
|
||||
|
||||
client[event.once ? 'once' : 'on'](event.name, handler);
|
||||
log.debug(`Registered event ${event.name}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { appendFileSync, mkdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { env, secrets } from '../config/env.js';
|
||||
|
||||
const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
|
||||
const threshold = LEVELS[env.logLevel] ?? LEVELS.info;
|
||||
|
||||
mkdirSync(env.logDir, { recursive: true });
|
||||
|
||||
export function maskSecrets(text) {
|
||||
return secrets.reduce((masked, secret) => masked.replaceAll(secret, '***'), String(text));
|
||||
}
|
||||
|
||||
function serialize(meta) {
|
||||
if (meta instanceof Error) {
|
||||
return { name: meta.name, message: meta.message, stack: meta.stack };
|
||||
}
|
||||
return meta;
|
||||
}
|
||||
|
||||
function write(level, scope, message, meta) {
|
||||
if (LEVELS[level] < threshold) return;
|
||||
|
||||
const entry = {
|
||||
time: new Date().toISOString(),
|
||||
level,
|
||||
scope,
|
||||
message,
|
||||
...(meta !== undefined && { meta: serialize(meta) }),
|
||||
};
|
||||
const line = maskSecrets(JSON.stringify(entry));
|
||||
|
||||
const output = level === 'error' || level === 'warn' ? console.error : console.log;
|
||||
output(line);
|
||||
|
||||
// Technical logs are split per day to simplify retention (M11-T08).
|
||||
const file = path.join(env.logDir, `${entry.time.slice(0, 10)}.log`);
|
||||
appendFileSync(file, `${line}\n`);
|
||||
}
|
||||
|
||||
export function createLogger(scope) {
|
||||
return {
|
||||
debug: (message, meta) => write('debug', scope, message, meta),
|
||||
info: (message, meta) => write('info', scope, message, meta),
|
||||
warn: (message, meta) => write('warn', scope, message, meta),
|
||||
error: (message, meta) => write('error', scope, message, meta),
|
||||
};
|
||||
}
|
||||
|
||||
export const logger = createLogger('app');
|
||||
@@ -0,0 +1,33 @@
|
||||
import { ACCESS_LEVELS } from '../config/constants.js';
|
||||
import { env } from '../config/env.js';
|
||||
|
||||
/**
|
||||
* Resolves the highest FWS access level of a guild member (M3-T02).
|
||||
* @param {import('discord.js').GuildMember} member
|
||||
*/
|
||||
export function getAccessLevel(member, roles = env.roles) {
|
||||
if (!member) return ACCESS_LEVELS.USER;
|
||||
if (member.guild?.ownerId === member.id) return ACCESS_LEVELS.OWNER;
|
||||
|
||||
const has = (roleId) => Boolean(roleId) && member.roles.cache.has(roleId);
|
||||
if (has(roles.owner)) return ACCESS_LEVELS.OWNER;
|
||||
if (has(roles.dev)) return ACCESS_LEVELS.DEV;
|
||||
if (has(roles.staff)) return ACCESS_LEVELS.STAFF;
|
||||
return ACCESS_LEVELS.USER;
|
||||
}
|
||||
|
||||
export function hasAccess(member, requiredLevel = ACCESS_LEVELS.USER, roles = env.roles) {
|
||||
return getAccessLevel(member, roles) >= requiredLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevents acting on a member whose top role is equal or higher (M3-T05 / M8-T08).
|
||||
* @param {import('discord.js').GuildMember} actor
|
||||
* @param {import('discord.js').GuildMember} target
|
||||
*/
|
||||
export function canActOn(actor, target) {
|
||||
if (!actor || !target || actor.id === target.id) return false;
|
||||
if (target.guild.ownerId === target.id) return false;
|
||||
if (actor.guild.ownerId === actor.id) return true;
|
||||
return actor.roles.highest.comparePositionTo(target.roles.highest) > 0;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { env } from '../config/env.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
|
||||
const log = createLogger('database');
|
||||
const migrationsDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'migrations');
|
||||
|
||||
let db;
|
||||
|
||||
function runMigrations(database) {
|
||||
database.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
name TEXT PRIMARY KEY,
|
||||
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)`);
|
||||
|
||||
const applied = new Set(
|
||||
database
|
||||
.prepare('SELECT name FROM schema_migrations')
|
||||
.all()
|
||||
.map((row) => row.name),
|
||||
);
|
||||
const pending = readdirSync(migrationsDir)
|
||||
.filter((file) => file.endsWith('.sql') && !applied.has(file))
|
||||
.sort();
|
||||
|
||||
for (const file of pending) {
|
||||
database.exec('BEGIN');
|
||||
try {
|
||||
database.exec(readFileSync(path.join(migrationsDir, file), 'utf8'));
|
||||
database.prepare('INSERT INTO schema_migrations (name) VALUES (?)').run(file);
|
||||
database.exec('COMMIT');
|
||||
log.info(`Applied migration ${file}`);
|
||||
} catch (error) {
|
||||
database.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function initDatabase(filePath = env.database.path) {
|
||||
if (db) return db;
|
||||
|
||||
if (filePath !== ':memory:') {
|
||||
mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
}
|
||||
db = new DatabaseSync(filePath);
|
||||
db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;');
|
||||
runMigrations(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
export function getDatabase() {
|
||||
if (!db) throw new Error('Database not initialized. Call initDatabase() first.');
|
||||
return db;
|
||||
}
|
||||
|
||||
export function closeDatabase() {
|
||||
db?.close();
|
||||
db = undefined;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
-- Server settings, isolated per guild (M3-T06)
|
||||
CREATE TABLE IF NOT EXISTS guild_settings (
|
||||
guild_id TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT,
|
||||
updated_by TEXT,
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (guild_id, key)
|
||||
);
|
||||
|
||||
-- Notification type -> channel mapping (M9-T01)
|
||||
CREATE TABLE IF NOT EXISTS notification_channels (
|
||||
guild_id TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
channel_id TEXT NOT NULL,
|
||||
detail_level TEXT NOT NULL DEFAULT 'normal',
|
||||
PRIMARY KEY (guild_id, type)
|
||||
);
|
||||
|
||||
-- Ticket categories (M6-T01) and tickets (M6)
|
||||
CREATE TABLE IF NOT EXISTS ticket_categories (
|
||||
guild_id TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
label TEXT NOT NULL,
|
||||
description TEXT,
|
||||
scope TEXT NOT NULL,
|
||||
PRIMARY KEY (guild_id, id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tickets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT NOT NULL,
|
||||
channel_id TEXT UNIQUE,
|
||||
category_id TEXT NOT NULL,
|
||||
author_id TEXT NOT NULL,
|
||||
claimed_by TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
closed_at TEXT,
|
||||
closed_by TEXT
|
||||
);
|
||||
-- Prevents duplicate open tickets per author and category (M6-T08)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tickets_open_unique
|
||||
ON tickets (guild_id, author_id, category_id) WHERE status = 'open';
|
||||
|
||||
-- Moderation actions (M8)
|
||||
CREATE TABLE IF NOT EXISTS moderation_actions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT NOT NULL,
|
||||
action TEXT NOT NULL CHECK (action IN ('warn', 'mute', 'kick', 'ban', 'clear', 'role')),
|
||||
target_id TEXT,
|
||||
moderator_id TEXT NOT NULL,
|
||||
reason TEXT,
|
||||
duration_ms INTEGER,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_moderation_target ON moderation_actions (guild_id, target_id);
|
||||
|
||||
-- Polls (M10)
|
||||
CREATE TABLE IF NOT EXISTS polls (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT NOT NULL,
|
||||
channel_id TEXT NOT NULL,
|
||||
message_id TEXT UNIQUE,
|
||||
creator_id TEXT NOT NULL,
|
||||
question TEXT NOT NULL,
|
||||
choices TEXT NOT NULL,
|
||||
ends_at TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'closed')),
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS poll_votes (
|
||||
poll_id INTEGER NOT NULL REFERENCES polls (id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL,
|
||||
choice_index INTEGER NOT NULL,
|
||||
voted_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (poll_id, user_id)
|
||||
);
|
||||
|
||||
-- Functional event log (M11-T05)
|
||||
CREATE TABLE IF NOT EXISTS event_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
guild_id TEXT,
|
||||
type TEXT NOT NULL,
|
||||
actor_id TEXT,
|
||||
payload TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_event_logs_created ON event_logs (created_at);
|
||||
|
||||
-- Delivered Gitea webhook deliveries, to avoid duplicate notifications (M9-T08)
|
||||
CREATE TABLE IF NOT EXISTS webhook_deliveries (
|
||||
delivery_id TEXT PRIMARY KEY,
|
||||
event TEXT NOT NULL,
|
||||
received_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
@@ -0,0 +1,13 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function logEvent({ guildId = null, type, actorId = null, payload = null }) {
|
||||
getDatabase()
|
||||
.prepare('INSERT INTO event_logs (guild_id, type, actor_id, payload) VALUES (?, ?, ?, ?)')
|
||||
.run(guildId, type, actorId, payload ? JSON.stringify(payload) : null);
|
||||
}
|
||||
|
||||
export function purgeEventsOlderThan(days) {
|
||||
return getDatabase()
|
||||
.prepare("DELETE FROM event_logs WHERE created_at < datetime('now', ?)")
|
||||
.run(`-${days} days`).changes;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
export function getSetting(guildId, key, fallback = null) {
|
||||
const row = getDatabase()
|
||||
.prepare('SELECT value FROM guild_settings WHERE guild_id = ? AND key = ?')
|
||||
.get(guildId, key);
|
||||
return row ? JSON.parse(row.value) : fallback;
|
||||
}
|
||||
|
||||
export function setSetting(guildId, key, value, updatedBy = null) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO guild_settings (guild_id, key, value, updated_by)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (guild_id, key) DO UPDATE SET
|
||||
value = excluded.value,
|
||||
updated_by = excluded.updated_by,
|
||||
updated_at = datetime('now')`,
|
||||
)
|
||||
.run(guildId, key, JSON.stringify(value), updatedBy);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Events } from 'discord.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
|
||||
const log = createLogger('discord');
|
||||
|
||||
export const name = Events.Error;
|
||||
|
||||
export async function execute(_client, error) {
|
||||
log.error('Discord client error', error);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { ActivityType, Events } from 'discord.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
|
||||
const log = createLogger('discord');
|
||||
|
||||
export const name = Events.ClientReady;
|
||||
export const once = true;
|
||||
|
||||
export async function execute(client) {
|
||||
client.user.setActivity('FWS Arch', { type: ActivityType.Watching });
|
||||
log.info(`Connected as ${client.user.tag}`, {
|
||||
guilds: client.guilds.cache.size,
|
||||
commands: client.commands.size,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Events } from 'discord.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
|
||||
const log = createLogger('members');
|
||||
|
||||
export const name = Events.GuildMemberAdd;
|
||||
|
||||
// TODO(M7-T01..T04): welcome message, rules and resources, initial role.
|
||||
export async function execute(_client, member) {
|
||||
log.info('Member joined', { userId: member.id, guildId: member.guild.id });
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Events } from 'discord.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
|
||||
const log = createLogger('members');
|
||||
|
||||
export const name = Events.GuildMemberRemove;
|
||||
|
||||
// TODO(M7-T04): log departures in the configured channel.
|
||||
export async function execute(_client, member) {
|
||||
log.info('Member left', { userId: member.id, guildId: member.guild.id });
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Events, MessageFlags } from 'discord.js';
|
||||
import { PermissionDeniedError, UserFacingError } from '../core/errors.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
import { hasAccess } from '../core/permissions.js';
|
||||
import { errorEmbed } from '../ui/embeds.js';
|
||||
|
||||
const log = createLogger('interactions');
|
||||
|
||||
export const name = Events.InteractionCreate;
|
||||
|
||||
async function replyError(interaction, message) {
|
||||
const payload = { embeds: [errorEmbed(message)], flags: MessageFlags.Ephemeral };
|
||||
if (interaction.deferred || interaction.replied) {
|
||||
await interaction.followUp(payload);
|
||||
} else {
|
||||
await interaction.reply(payload);
|
||||
}
|
||||
}
|
||||
|
||||
export async function execute(client, interaction) {
|
||||
if (!interaction.isChatInputCommand() && !interaction.isAutocomplete()) return;
|
||||
|
||||
const command = client.commands.get(interaction.commandName);
|
||||
if (!command) return;
|
||||
|
||||
if (interaction.isAutocomplete()) {
|
||||
await command.autocomplete?.(interaction);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const subcommand = interaction.options.getSubcommand(false);
|
||||
const requiredLevel = command.subcommandAccess?.[subcommand] ?? command.access;
|
||||
if (!hasAccess(interaction.member, requiredLevel)) {
|
||||
throw new PermissionDeniedError();
|
||||
}
|
||||
await command.execute(interaction);
|
||||
} catch (error) {
|
||||
if (error instanceof UserFacingError) {
|
||||
await replyError(interaction, error.message);
|
||||
return;
|
||||
}
|
||||
|
||||
log.error(`Command failed: /${interaction.commandName}`, error);
|
||||
await replyError(interaction, 'Une erreur inattendue est survenue. Réessaie plus tard.').catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Events } from 'discord.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
|
||||
const log = createLogger('discord');
|
||||
|
||||
// discord.js reconnects automatically with backoff; we only log the lifecycle (M2-T04 / M2-T08).
|
||||
export const name = Events.ShardDisconnect;
|
||||
|
||||
export async function execute(_client, closeEvent, shardId) {
|
||||
log.warn('Shard disconnected', { shardId, code: closeEvent?.code });
|
||||
}
|
||||
@@ -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);
|
||||
@@ -0,0 +1,51 @@
|
||||
import { env } from '../../config/env.js';
|
||||
import { ExternalApiError } from '../../core/errors.js';
|
||||
import { withRetry } from '../../utils/retry.js';
|
||||
|
||||
const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500;
|
||||
|
||||
/** Minimal Gitea REST API client (M5-T01). */
|
||||
export async function giteaRequest(endpoint, { method = 'GET', body } = {}) {
|
||||
if (!env.gitea.url || !env.gitea.token) {
|
||||
throw new ExternalApiError('gitea', 'Gitea is not configured');
|
||||
}
|
||||
|
||||
return withRetry(
|
||||
async () => {
|
||||
const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `token ${env.gitea.token}`,
|
||||
Accept: 'application/json',
|
||||
...(body && { 'Content-Type': 'application/json' }),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
signal: AbortSignal.timeout(env.gitea.timeoutMs),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = new ExternalApiError('gitea', `${method} ${endpoint} failed with ${response.status}`);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return response.status === 204 ? null : response.json();
|
||||
},
|
||||
{ retries: env.gitea.maxRetries, shouldRetry: isTransient },
|
||||
);
|
||||
}
|
||||
|
||||
const repoPath = () => `/repos/${env.gitea.owner}/${env.gitea.repo}`;
|
||||
|
||||
export const gitea = {
|
||||
listIssues: (params = 'state=open&type=issues&limit=10') => giteaRequest(`${repoPath()}/issues?${params}`),
|
||||
getIssue: (number) => giteaRequest(`${repoPath()}/issues/${number}`),
|
||||
createIssue: ({ title, body }) =>
|
||||
giteaRequest(`${repoPath()}/issues`, { method: 'POST', body: { title, body } }),
|
||||
listPullRequests: (params = 'state=open&limit=10') => giteaRequest(`${repoPath()}/pulls?${params}`),
|
||||
getPullRequest: (number) => giteaRequest(`${repoPath()}/pulls/${number}`),
|
||||
createPullRequest: ({ title, body, head, base }) =>
|
||||
giteaRequest(`${repoPath()}/pulls`, { method: 'POST', body: { title, body, head, base } }),
|
||||
listCommits: (limit = 10) => giteaRequest(`${repoPath()}/commits?limit=${limit}`),
|
||||
listReleases: (limit = 5) => giteaRequest(`${repoPath()}/releases?limit=${limit}`),
|
||||
getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`),
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
import { env } from '../../config/env.js';
|
||||
import { createLogger } from '../../core/logger.js';
|
||||
|
||||
const log = createLogger('notifications');
|
||||
|
||||
const defaultChannels = {
|
||||
issues: env.channels.notifIssues,
|
||||
pull_request: env.channels.notifPullRequests,
|
||||
push: env.channels.notifCommits,
|
||||
release: env.channels.notifReleases,
|
||||
errors: env.channels.notifErrors,
|
||||
};
|
||||
|
||||
// TODO(M9-T01): resolve channels from notification_channels in SQLite first.
|
||||
export function resolveChannelId(type) {
|
||||
return defaultChannels[type] ?? null;
|
||||
}
|
||||
|
||||
/** Sends a notification payload to the channel configured for its type (M9). */
|
||||
export async function notify(client, type, payload) {
|
||||
const channelId = resolveChannelId(type);
|
||||
if (!channelId) {
|
||||
log.debug(`No channel configured for notification type ${type}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const channel = await client.channels.fetch(channelId).catch(() => null);
|
||||
if (!channel?.isSendable()) {
|
||||
log.warn(`Notification channel unavailable for ${type}`, { channelId });
|
||||
return;
|
||||
}
|
||||
await channel.send(payload);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js';
|
||||
|
||||
/** Builds a row of link buttons, skipping links without a URL (M12-T03). */
|
||||
export function linkButtons(links) {
|
||||
const buttons = links
|
||||
.filter((link) => link.url)
|
||||
.slice(0, 5)
|
||||
.map((link) => new ButtonBuilder().setStyle(ButtonStyle.Link).setLabel(link.label).setURL(link.url));
|
||||
|
||||
return buttons.length > 0 ? [new ActionRowBuilder().addComponents(buttons)] : [];
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { EmbedBuilder } from 'discord.js';
|
||||
import { BOT_NAME, COLORS } from '../config/constants.js';
|
||||
|
||||
/** Base embed with the shared FWS-Bot visual identity (M12-T02). */
|
||||
export function baseEmbed(color = COLORS.primary) {
|
||||
return new EmbedBuilder().setColor(color).setFooter({ text: BOT_NAME }).setTimestamp();
|
||||
}
|
||||
|
||||
export function infoEmbed(title, description) {
|
||||
return baseEmbed(COLORS.info).setTitle(title).setDescription(description);
|
||||
}
|
||||
|
||||
export function successEmbed(description) {
|
||||
return baseEmbed(COLORS.success).setTitle('Succès').setDescription(description);
|
||||
}
|
||||
|
||||
export function errorEmbed(description) {
|
||||
return baseEmbed(COLORS.error).setTitle('Erreur').setDescription(description);
|
||||
}
|
||||
|
||||
export function notImplementedEmbed(feature) {
|
||||
return baseEmbed(COLORS.warning)
|
||||
.setTitle('Bientôt disponible')
|
||||
.setDescription(`La fonctionnalité **${feature}** n'est pas encore implémentée.`);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/** In-memory guard against duplicate actions within a time window (M13-T08). */
|
||||
export function createCooldown(windowMs) {
|
||||
const entries = new Map();
|
||||
|
||||
return {
|
||||
/** Returns true when the key is free, and locks it for `windowMs`. */
|
||||
acquire(key) {
|
||||
const now = Date.now();
|
||||
const expiresAt = entries.get(key);
|
||||
if (expiresAt && expiresAt > now) return false;
|
||||
entries.set(key, now + windowMs);
|
||||
return true;
|
||||
},
|
||||
release(key) {
|
||||
entries.delete(key);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
/**
|
||||
* Retries an async operation with exponential backoff (M13-T05).
|
||||
* `shouldRetry` decides whether an error is transient.
|
||||
*/
|
||||
export async function withRetry(
|
||||
operation,
|
||||
{ retries = 2, baseDelayMs = 500, shouldRetry = () => true } = {},
|
||||
) {
|
||||
for (let attempt = 0; ; attempt += 1) {
|
||||
try {
|
||||
return await operation(attempt);
|
||||
} catch (error) {
|
||||
if (attempt >= retries || !shouldRetry(error)) throw error;
|
||||
await sleep(baseDelayMs * 2 ** attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto';
|
||||
import { env } from '../config/env.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
import { getDatabase } from '../database/index.js';
|
||||
|
||||
const log = createLogger('webhooks');
|
||||
|
||||
export function isValidSignature(rawBody, signature, secret = env.webhook.secret) {
|
||||
if (!secret || !signature) return false;
|
||||
const expected = Buffer.from(createHmac('sha256', secret).update(rawBody).digest('hex'));
|
||||
const received = Buffer.from(signature);
|
||||
return expected.length === received.length && timingSafeEqual(expected, received);
|
||||
}
|
||||
|
||||
/** Returns true the first time a delivery id is seen (M9-T08). */
|
||||
function markDelivered(deliveryId, event) {
|
||||
const result = getDatabase()
|
||||
.prepare('INSERT OR IGNORE INTO webhook_deliveries (delivery_id, event) VALUES (?, ?)')
|
||||
.run(deliveryId, event);
|
||||
return result.changes > 0;
|
||||
}
|
||||
|
||||
/** Validates and dispatches a Gitea webhook. Returns the HTTP status code. */
|
||||
export async function handleGiteaWebhook(_client, headers, rawBody) {
|
||||
if (!isValidSignature(rawBody, headers['x-gitea-signature'])) {
|
||||
log.warn('Rejected webhook with invalid signature');
|
||||
return 401;
|
||||
}
|
||||
|
||||
const event = headers['x-gitea-event'];
|
||||
const deliveryId = headers['x-gitea-delivery'];
|
||||
if (!event || !deliveryId) return 400;
|
||||
if (!markDelivered(deliveryId, event)) return 200;
|
||||
|
||||
const payload = JSON.parse(rawBody.toString('utf8'));
|
||||
log.info(`Received Gitea event ${event}`, { deliveryId, repository: payload.repository?.full_name });
|
||||
|
||||
// TODO(M9-T03..T07): filter events and publish embeds through notification-service.
|
||||
return 202;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { createServer } from 'node:http';
|
||||
import { env } from '../config/env.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
import { handleGiteaWebhook } from './gitea-webhook.js';
|
||||
|
||||
const log = createLogger('webhooks');
|
||||
const MAX_BODY_BYTES = 1024 * 1024;
|
||||
|
||||
function readBody(request) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
request.on('data', (chunk) => {
|
||||
size += chunk.length;
|
||||
if (size > MAX_BODY_BYTES) {
|
||||
reject(new Error('Payload too large'));
|
||||
request.destroy();
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
request.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
request.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
/** HTTP server receiving Gitea webhook events (M9-T02). */
|
||||
export function startWebhookServer(client) {
|
||||
const server = createServer(async (request, response) => {
|
||||
if (request.method !== 'POST' || request.url !== env.webhook.path) {
|
||||
response.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const rawBody = await readBody(request);
|
||||
const status = await handleGiteaWebhook(client, request.headers, rawBody);
|
||||
response.writeHead(status).end();
|
||||
} catch (error) {
|
||||
log.error('Webhook handling failed', error);
|
||||
response.writeHead(500).end();
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(env.webhook.port, env.webhook.host, () => {
|
||||
log.info(`Webhook server listening on ${env.webhook.host}:${env.webhook.port}${env.webhook.path}`);
|
||||
});
|
||||
return server;
|
||||
}
|
||||
@@ -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/);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user