Files
FWS-DiscordBot/src/config/guild-settings.js
T
nocodeandClaude Opus 5 52a5c50692 feat(settings): make the server settings real, and widen them
The dashboard offered seven switches that nothing read: they promised a
behaviour the bot did not have, which is worse than offering nothing.

Every setting is now declared once, with its type, its bounds and its
explanation, and the services read it: the welcome message and its wording,
the automatic role, departure notices, the private notice sent to a
sanctioned member, the default mute duration, how much history a ban erases,
whether a closed ticket is deleted or archived, and an optional role mention
on the Gitea notifications.

A test walks the sources and fails when a declared key is read nowhere, so
the list cannot drift back into decoration.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 22:31:36 +02:00

251 lines
8.4 KiB
JavaScript
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.
import { resolveSetting, setSetting } from '../database/repositories/settings-repository.js';
import { env } from './env.js';
/**
* Settings a server can change without touching the `.env` (M16-T13).
*
* Single source of truth: the form, the validation and the values the services
* read all come from here. A setting that is not read by anything has no
* business being in this list — a switch that does nothing is worse than no
* switch at all.
*/
export const SETTING_SECTIONS = Object.freeze([
{
id: 'welcome',
title: 'Arrivées et départs',
summary: 'Ce que le bot fait quand quelqu’un rejoint ou quitte.',
},
{ id: 'moderation', title: 'Modération', summary: 'Comportement par défaut des sanctions.' },
{ id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' },
{
id: 'voice',
title: 'Salons vocaux',
summary: 'Salons temporaires créés par les déclencheurs.',
},
{ id: 'notifications', title: 'Notifications', summary: 'Mise en forme des messages publiés par le bot.' },
{ id: 'interface', title: 'Tableau de bord', summary: 'Comportement de ce site.' },
]);
export const GUILD_SETTINGS = Object.freeze([
// --- Arrivées et départs ---------------------------------------------------
{
key: 'welcome.enabled',
section: 'welcome',
label: 'Message de bienvenue',
help: 'Publier un message dans le salon d’accueil à chaque arrivée.',
type: 'bool',
default: true,
},
{
key: 'welcome.message',
section: 'welcome',
label: 'Texte de bienvenue',
help: 'Phrase affichée sous la mention du nouveau membre. `{server}` est remplacé par le nom du serveur.',
type: 'text',
default: 'Bienvenue sur le serveur **{server}** !',
maxLength: 500,
},
{
key: 'welcome.showRules',
section: 'welcome',
label: 'Rappeler le règlement',
help: 'Ajoute un lien vers le salon des règles dans le message d’accueil.',
type: 'bool',
default: true,
},
{
key: 'welcome.directMessage',
section: 'welcome',
label: 'Message privé de bienvenue',
help: 'Envoyer en plus un message privé avec les liens utiles. Certains comptes refusent les MP : l’échec est silencieux.',
type: 'bool',
default: false,
},
{
key: 'members.autoRole',
section: 'welcome',
label: 'Attribuer le rôle d’arrivée',
help: 'Donne automatiquement `ROLE_MEMBER_ID` aux nouveaux membres.',
type: 'bool',
default: true,
},
{
key: 'departure.announce',
section: 'welcome',
label: 'Annoncer les départs',
help: 'Publie une ligne dans les logs quand un membre quitte le serveur.',
type: 'bool',
default: true,
},
// --- Modération ------------------------------------------------------------
{
key: 'moderation.dmTarget',
section: 'moderation',
label: 'Prévenir le membre sanctionné',
help: 'Envoie un message privé expliquant la sanction et son motif.',
type: 'bool',
default: true,
},
{
key: 'moderation.defaultMuteMinutes',
section: 'moderation',
label: 'Durée d’exclusion par défaut (min)',
help: 'Proposée quand `/mute` est lancé sans durée.',
type: 'int',
default: 60,
min: 1,
max: 40_320,
},
{
key: 'moderation.banDeleteMessageHours',
section: 'moderation',
label: 'Messages supprimés au bannissement (h)',
help: 'Discord peut effacer les messages récents de la personne bannie. `0` n’en supprime aucun.',
type: 'int',
default: 0,
min: 0,
max: 168,
advanced: true,
},
// --- Tickets ---------------------------------------------------------------
{
key: 'tickets.deleteChannelOnClose',
section: 'tickets',
label: 'Supprimer le salon à la clôture',
help: 'Décoché, le salon est conservé en lecture seule plutôt que supprimé.',
type: 'bool',
default: true,
},
// --- Salons vocaux ---------------------------------------------------------
{
key: 'voice.adoptOrphans',
section: 'voice',
label: 'Récupérer les salons orphelins',
help: 'Au démarrage, reprend en charge les salons générés que la base ne connaît plus — après une restauration ou une redéploiement — et supprime ceux restés vides.',
type: 'bool',
default: true,
},
// --- Notifications ---------------------------------------------------------
{
key: 'notifications.mentionRoleId',
section: 'notifications',
label: 'Rôle à mentionner',
help: 'Identifiant d’un rôle mentionné en tête des notifications Gitea. Vide : aucune mention.',
type: 'snowflake',
default: '',
advanced: true,
},
// --- Tableau de bord -------------------------------------------------------
{
key: 'deploy.requireConfirmation',
section: 'interface',
label: 'Confirmation avant déploiement',
help: 'Demande de retaper le nom de l’environnement avant de lancer un déploiement.',
type: 'bool',
default: true,
},
{
key: 'web.defaultMode',
section: 'interface',
label: 'Mode d’affichage par défaut',
help: 'Interface « simple » (l’essentiel) ou « avancée » (tous les réglages), pour qui n’a pas encore choisi.',
type: 'enum',
options: ['simple', 'advanced'],
default: 'simple',
},
]);
export const SETTING_BY_KEY = Object.freeze(
Object.fromEntries(GUILD_SETTINGS.map((setting) => [setting.key, setting])),
);
/** Coerces a stored value to the declared type, falling back on the default. */
function coerce(setting, value) {
if (value === null || value === undefined) return setting.default;
switch (setting.type) {
case 'bool':
return Boolean(value);
case 'int': {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed)) return setting.default;
if (setting.min !== undefined && parsed < setting.min) return setting.min;
if (setting.max !== undefined && parsed > setting.max) return setting.max;
return parsed;
}
case 'enum':
return setting.options.includes(value) ? value : setting.default;
default:
return String(value);
}
}
/**
* Reads a setting. Never throws: called from event handlers that must keep
* working even when the database is momentarily unavailable.
*/
export function readSetting(key, guildId = env.discord.guildId) {
const setting = SETTING_BY_KEY[key];
if (!setting) throw new Error(`Unknown guild setting: ${key}`);
return coerce(setting, resolveSetting(guildId, key, setting.default));
}
/** Validates then stores a setting. Returns the stored value. */
export function writeSetting(key, value, { guildId = env.discord.guildId, updatedBy = null } = {}) {
const setting = SETTING_BY_KEY[key];
if (!setting) throw new Error(`Unknown guild setting: ${key}`);
const message = validateSetting(key, value);
if (message) throw new Error(message);
const stored = coerce(setting, value);
setSetting(guildId, key, stored, updatedBy);
return stored;
}
/** Returns null when the value is acceptable, a French message otherwise. */
export function validateSetting(key, value) {
const setting = SETTING_BY_KEY[key];
if (!setting) return `Réglage inconnu : ${key}`;
switch (setting.type) {
case 'bool':
return typeof value === 'boolean' ? null : 'Valeur attendue : vrai ou faux.';
case 'int': {
const parsed = Number.parseInt(value, 10);
if (!Number.isInteger(parsed)) return 'Un nombre entier est attendu.';
if (setting.min !== undefined && parsed < setting.min) return `Minimum : ${setting.min}.`;
if (setting.max !== undefined && parsed > setting.max) return `Maximum : ${setting.max}.`;
return null;
}
case 'enum':
return setting.options.includes(value) ? null : `Valeurs possibles : ${setting.options.join(', ')}.`;
case 'snowflake': {
const text = String(value ?? '').trim();
return text === '' || /^\d{17,20}$/.test(text)
? null
: 'Un identifiant Discord est composé de 17 à 20 chiffres.';
}
default: {
const text = String(value ?? '');
if (setting.maxLength && text.length > setting.maxLength) {
return `${setting.maxLength} caractères maximum.`;
}
return null;
}
}
}
/** Every setting with its current value, for the settings page. */
export function allSettings(guildId = env.discord.guildId) {
return Object.fromEntries(
GUILD_SETTINGS.map((setting) => [setting.key, readSetting(setting.key, guildId)]),
);
}