refactor(all): uniformisation
This commit is contained in:
89 files changed
+10215
-10215
No files matched your search
+26
-26
@@ -1,26 +1,26 @@
|
||||
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
|
||||
* - GuildVoiceStates: temporary voice channels (M14)
|
||||
* MessageContent is intentionally not requested.
|
||||
*/
|
||||
export function createClient() {
|
||||
const client = new Client({
|
||||
intents: [
|
||||
GatewayIntentBits.Guilds,
|
||||
GatewayIntentBits.GuildMembers,
|
||||
GatewayIntentBits.GuildModeration,
|
||||
GatewayIntentBits.GuildMessages,
|
||||
GatewayIntentBits.GuildVoiceStates,
|
||||
],
|
||||
partials: [Partials.GuildMember],
|
||||
});
|
||||
|
||||
client.commands = new Collection();
|
||||
return client;
|
||||
}
|
||||
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
|
||||
* - GuildVoiceStates: temporary voice channels (M14)
|
||||
* MessageContent is intentionally not requested.
|
||||
*/
|
||||
export function createClient() {
|
||||
const client = new Client({
|
||||
intents: [
|
||||
GatewayIntentBits.Guilds,
|
||||
GatewayIntentBits.GuildMembers,
|
||||
GatewayIntentBits.GuildModeration,
|
||||
GatewayIntentBits.GuildMessages,
|
||||
GatewayIntentBits.GuildVoiceStates,
|
||||
],
|
||||
partials: [Partials.GuildMember],
|
||||
});
|
||||
|
||||
client.commands = new Collection();
|
||||
return client;
|
||||
}
|
||||
+28
-28
@@ -1,28 +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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
+24
-24
@@ -1,24 +1,24 @@
|
||||
/** 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 = 'Cette action est réservée à l’équipe pour l’instant. Demande à une personne du staff si tu en as besoin.',
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'PermissionDeniedError';
|
||||
}
|
||||
}
|
||||
|
||||
export class ExternalApiError extends Error {
|
||||
constructor(service, message, options) {
|
||||
super(`[${service}] ${message}`, options);
|
||||
this.name = 'ExternalApiError';
|
||||
this.service = service;
|
||||
}
|
||||
}
|
||||
/** 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 = 'Cette action est réservée à l’équipe pour l’instant. Demande à une personne du staff si tu en as besoin.',
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'PermissionDeniedError';
|
||||
}
|
||||
}
|
||||
|
||||
export class ExternalApiError extends Error {
|
||||
constructor(service, message, options) {
|
||||
super(`[${service}] ${message}`, options);
|
||||
this.name = 'ExternalApiError';
|
||||
this.service = service;
|
||||
}
|
||||
}
|
||||
+29
-29
@@ -1,29 +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}`);
|
||||
}
|
||||
}
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
+50
-50
@@ -1,50 +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');
|
||||
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');
|
||||
+33
-33
@@ -1,33 +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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user