refactor(all): uniformisation

This commit is contained in:
BlackAngelTV committed 2026-09-23 18:25:28 +02:00
1 parent ee538cb943
commit 50665c8edd
89 files changed
+10215 -10215

No files matched your search

+107 -107
View File
@@ -1,107 +1,107 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { parseChoices } from '../../services/polls/poll-service.js';
import { baseEmbed, bullets } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
const EIGHT_BALL_ANSWERS = Object.freeze([
'Oui, sans aucun doute.',
'Compte là-dessus et bois de l’eau.',
'Les signes disent que oui.',
'Impossible de le prédire pour le moment.',
'Concentre-toi et redemande.',
'Ma réponse est non.',
'Très probablement.',
'Mes sources disent non.',
'La réponse est floue, réessaie.',
'Absolument !',
'Pas dans un avenir proche.',
'Oui, mais fais attention à toi.',
]);
const pick = (list) => list[Math.floor(Math.random() * list.length)];
export const data = new SlashCommandBuilder()
.setName('fun')
.setDescription('Commandes de divertissement')
.addSubcommand((sub) => sub.setName('coinflip').setDescription('Pile ou face'))
.addSubcommand((sub) =>
sub
.setName('dice')
.setDescription('Lancer un dé')
.addIntegerOption((option) =>
option
.setName('sides')
.setDescription('Nombre de faces (6 par défaut)')
.setMinValue(2)
.setMaxValue(1000),
),
)
.addSubcommand((sub) =>
sub
.setName('8ball')
.setDescription('Poser une question à la boule magique')
.addStringOption((option) =>
option.setName('question').setDescription('Ta question').setRequired(true).setMaxLength(300),
),
)
.addSubcommand((sub) =>
sub
.setName('choose')
.setDescription('Choisir au hasard parmi plusieurs options')
.addStringOption((option) =>
option.setName('options').setDescription('Options séparées par ";" (2 à 10)').setRequired(true),
),
);
/** Lightweight, stateless fun commands (M10-T07). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'coinflip') {
const result = pick(['Pile', 'Face']);
await interaction.reply({
embeds: [baseEmbed(COLORS.info).setTitle('🪙 Pile ou face').setDescription(`**${result}** !`)],
});
return;
}
if (subcommand === 'dice') {
const sides = interaction.options.getInteger('sides') ?? 6;
const roll = 1 + Math.floor(Math.random() * sides);
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle(`🎲 Lancer de dé (d${sides})`)
.setDescription(`Tu obtiens **${roll}** !`),
],
});
return;
}
if (subcommand === '8ball') {
const question = interaction.options.getString('question', true);
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle('🎱 Boule magique')
.addFields(
{ name: 'Question', value: question },
{ name: 'Réponse', value: pick(EIGHT_BALL_ANSWERS) },
),
],
});
return;
}
const options = parseChoices(interaction.options.getString('options', true));
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle('🎯 Choix aléatoire')
.addFields({ name: 'Options', value: bullets(options) })
.setDescription(`Je choisis : **${pick(options)}**`),
],
});
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { parseChoices } from '../../services/polls/poll-service.js';
import { baseEmbed, bullets } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
const EIGHT_BALL_ANSWERS = Object.freeze([
'Oui, sans aucun doute.',
'Compte là-dessus et bois de l’eau.',
'Les signes disent que oui.',
'Impossible de le prédire pour le moment.',
'Concentre-toi et redemande.',
'Ma réponse est non.',
'Très probablement.',
'Mes sources disent non.',
'La réponse est floue, réessaie.',
'Absolument !',
'Pas dans un avenir proche.',
'Oui, mais fais attention à toi.',
]);
const pick = (list) => list[Math.floor(Math.random() * list.length)];
export const data = new SlashCommandBuilder()
.setName('fun')
.setDescription('Commandes de divertissement')
.addSubcommand((sub) => sub.setName('coinflip').setDescription('Pile ou face'))
.addSubcommand((sub) =>
sub
.setName('dice')
.setDescription('Lancer un dé')
.addIntegerOption((option) =>
option
.setName('sides')
.setDescription('Nombre de faces (6 par défaut)')
.setMinValue(2)
.setMaxValue(1000),
),
)
.addSubcommand((sub) =>
sub
.setName('8ball')
.setDescription('Poser une question à la boule magique')
.addStringOption((option) =>
option.setName('question').setDescription('Ta question').setRequired(true).setMaxLength(300),
),
)
.addSubcommand((sub) =>
sub
.setName('choose')
.setDescription('Choisir au hasard parmi plusieurs options')
.addStringOption((option) =>
option.setName('options').setDescription('Options séparées par ";" (2 à 10)').setRequired(true),
),
);
/** Lightweight, stateless fun commands (M10-T07). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'coinflip') {
const result = pick(['Pile', 'Face']);
await interaction.reply({
embeds: [baseEmbed(COLORS.info).setTitle('🪙 Pile ou face').setDescription(`**${result}** !`)],
});
return;
}
if (subcommand === 'dice') {
const sides = interaction.options.getInteger('sides') ?? 6;
const roll = 1 + Math.floor(Math.random() * sides);
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle(`🎲 Lancer de dé (d${sides})`)
.setDescription(`Tu obtiens **${roll}** !`),
],
});
return;
}
if (subcommand === '8ball') {
const question = interaction.options.getString('question', true);
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle('🎱 Boule magique')
.addFields(
{ name: 'Question', value: question },
{ name: 'Réponse', value: pick(EIGHT_BALL_ANSWERS) },
),
],
});
return;
}
const options = parseChoices(interaction.options.getString('options', true));
await interaction.reply({
embeds: [
baseEmbed(COLORS.info)
.setTitle('🎯 Choix aléatoire')
.addFields({ name: 'Options', value: bullets(options) })
.setDescription(`Je choisis : **${pick(options)}**`),
],
});
}
+62 -62
View File
@@ -1,62 +1,62 @@
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { buildPollEmbed, closePollById, createPoll } from '../../services/polls/poll-service.js';
import { successEmbed } 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 posée').setRequired(true).setMaxLength(200),
)
.addStringOption((option) =>
option
.setName('choices')
.setDescription('Propositions séparées par des « ; » (2 à 10)')
.setRequired(true),
)
.addIntegerOption((option) =>
option
.setName('minutes')
.setDescription('Durée avant fermeture automatique, en minutes')
.setMinValue(1)
.setMaxValue(10_080),
),
)
.addSubcommand((sub) =>
sub
.setName('close')
.setDescription('Fermer un sondage')
.addIntegerOption((option) =>
option.setName('id').setDescription('Numéro du sondage (affiché dans l’embed)').setRequired(true),
),
);
/** Polls are published in the current channel and voted with buttons (M10). */
export async function execute(interaction) {
if (interaction.options.getSubcommand() === 'close') {
const poll = await closePollById(interaction.client, interaction.options.getInteger('id', true));
await interaction.reply({ embeds: [buildPollEmbed(poll)] });
return;
}
const question = interaction.options.getString('question', true);
const choicesInput = interaction.options.getString('choices', true);
const minutes = interaction.options.getInteger('minutes');
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const pollId = await createPoll(interaction, { question, choicesInput, minutes });
await interaction.editReply({
embeds: [
successEmbed(
`Ton sondage **#${pollId}** est en ligne dans <#${interaction.channelId}> : tout le monde vote avec les boutons.`,
),
],
});
}
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { buildPollEmbed, closePollById, createPoll } from '../../services/polls/poll-service.js';
import { successEmbed } 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 posée').setRequired(true).setMaxLength(200),
)
.addStringOption((option) =>
option
.setName('choices')
.setDescription('Propositions séparées par des « ; » (2 à 10)')
.setRequired(true),
)
.addIntegerOption((option) =>
option
.setName('minutes')
.setDescription('Durée avant fermeture automatique, en minutes')
.setMinValue(1)
.setMaxValue(10_080),
),
)
.addSubcommand((sub) =>
sub
.setName('close')
.setDescription('Fermer un sondage')
.addIntegerOption((option) =>
option.setName('id').setDescription('Numéro du sondage (affiché dans l’embed)').setRequired(true),
),
);
/** Polls are published in the current channel and voted with buttons (M10). */
export async function execute(interaction) {
if (interaction.options.getSubcommand() === 'close') {
const poll = await closePollById(interaction.client, interaction.options.getInteger('id', true));
await interaction.reply({ embeds: [buildPollEmbed(poll)] });
return;
}
const question = interaction.options.getString('question', true);
const choicesInput = interaction.options.getString('choices', true);
const minutes = interaction.options.getInteger('minutes');
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const pollId = await createPoll(interaction, { question, choicesInput, minutes });
await interaction.editReply({
embeds: [
successEmbed(
`Ton sondage **#${pollId}** est en ligne dans <#${interaction.channelId}> : tout le monde vote avec les boutons.`,
),
],
});
}
+116 -116
View File
@@ -1,116 +1,116 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { createLogger } from '../../core/logger.js';
import { countByAction } from '../../database/repositories/moderation-repository.js';
import { countPolls } from '../../database/repositories/poll-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { baseEmbed, errorEmbed } from '../../ui/embeds.js';
const log = createLogger('stats');
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'));
const discordStatsEmbed = (interaction) => {
const guild = interaction.guild;
return baseEmbed()
.setTitle(`📊 Statistiques — ${guild.name}`)
.setThumbnail(guild.iconURL({ size: 128 }))
.addFields(
{ name: 'Membres', value: String(guild.memberCount), inline: true },
{ name: 'Salons', value: String(guild.channels.cache.size), inline: true },
{ name: 'Rôles', value: String(guild.roles.cache.size), inline: true },
{ name: 'Boosts', value: String(guild.premiumSubscriptionCount ?? 0), inline: true },
{ name: 'Créé', value: `<t:${Math.floor(guild.createdTimestamp / 1000)}:R>`, inline: true },
{ name: 'Latence', value: `${Math.round(interaction.client.ws.ping)} ms`, inline: true },
);
};
async function giteaStatsEmbed() {
const [issues, pulls, commits, releases] = await Promise.all([
gitea.listIssues('state=open&type=issues&limit=50'),
gitea.listPullRequests('state=open&limit=50'),
gitea.listCommits(5),
gitea.listReleases(1),
]);
const latestCommits = asList(commits)
.slice(0, 5)
.map((commit) => `\`${commit.sha?.slice(0, 7)}\` ${commit.commit?.message?.split('\n')[0] ?? ''}`)
.join('\n');
const release = asList(releases)[0];
const embed = baseEmbed(COLORS.gitea)
.setTitle('📈 Activité Gitea')
.setURL(repositoryUrl())
.setDescription(latestCommits || 'Aucun commit récent pour le moment.')
.addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
);
if (release)
embed.addFields({ name: 'Dernière release', value: release.tag_name ?? 'inconnue', inline: true });
return embed;
}
/** Community activity stored locally, independent from Gitea availability (M11). */
function fwsStatsEmbed(interaction) {
const actions = countByAction(interaction.guildId);
const total = actions.reduce((sum, row) => sum + row.count, 0);
return baseEmbed(COLORS.gitea)
.setTitle('📈 Indicateurs FWS')
.addFields(
{ name: 'Tickets ouverts', value: String(countOpenTickets(interaction.guildId)), inline: true },
{ name: 'Sondages créés', value: String(countPolls(interaction.guildId)), inline: true },
{ name: 'Actions de modération', value: String(total), inline: true },
{ name: 'Dépôt', value: repositoryUrl() || 'Non configuré' },
)
.setFooter({ text: 'Statistiques locales · FWS-Bot' });
}
/** `/stats` never fails because of Gitea: the API errors are caught (M11-T03). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
await interaction.deferReply();
if (subcommand === 'discord') {
await interaction.editReply({ embeds: [discordStatsEmbed(interaction)] });
return;
}
if (subcommand === 'fws') {
try {
const releases = asList(await gitea.listReleases(1));
const embed = fwsStatsEmbed(interaction);
if (releases[0])
embed.addFields({ name: 'Version FWS Arch', value: releases[0].tag_name ?? 'inconnue' });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
log.warn('Gitea unavailable while building /stats fws', error);
await interaction.editReply({ embeds: [fwsStatsEmbed(interaction)] });
}
return;
}
try {
await interaction.editReply({ embeds: [await giteaStatsEmbed()] });
} catch (error) {
log.error('Could not read Gitea stats', error);
await interaction.editReply({
embeds: [
errorEmbed(
'Les statistiques Gitea ne répondent pas. Réessaie dans un instant — si ça continue, l’équipe peut vérifier `GITEA_URL` et `GITEA_TOKEN`. Le reste du bot fonctionne normalement.',
),
],
});
}
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { createLogger } from '../../core/logger.js';
import { countByAction } from '../../database/repositories/moderation-repository.js';
import { countPolls } from '../../database/repositories/poll-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { baseEmbed, errorEmbed } from '../../ui/embeds.js';
const log = createLogger('stats');
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'));
const discordStatsEmbed = (interaction) => {
const guild = interaction.guild;
return baseEmbed()
.setTitle(`📊 Statistiques — ${guild.name}`)
.setThumbnail(guild.iconURL({ size: 128 }))
.addFields(
{ name: 'Membres', value: String(guild.memberCount), inline: true },
{ name: 'Salons', value: String(guild.channels.cache.size), inline: true },
{ name: 'Rôles', value: String(guild.roles.cache.size), inline: true },
{ name: 'Boosts', value: String(guild.premiumSubscriptionCount ?? 0), inline: true },
{ name: 'Créé', value: `<t:${Math.floor(guild.createdTimestamp / 1000)}:R>`, inline: true },
{ name: 'Latence', value: `${Math.round(interaction.client.ws.ping)} ms`, inline: true },
);
};
async function giteaStatsEmbed() {
const [issues, pulls, commits, releases] = await Promise.all([
gitea.listIssues('state=open&type=issues&limit=50'),
gitea.listPullRequests('state=open&limit=50'),
gitea.listCommits(5),
gitea.listReleases(1),
]);
const latestCommits = asList(commits)
.slice(0, 5)
.map((commit) => `\`${commit.sha?.slice(0, 7)}\` ${commit.commit?.message?.split('\n')[0] ?? ''}`)
.join('\n');
const release = asList(releases)[0];
const embed = baseEmbed(COLORS.gitea)
.setTitle('📈 Activité Gitea')
.setURL(repositoryUrl())
.setDescription(latestCommits || 'Aucun commit récent pour le moment.')
.addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
);
if (release)
embed.addFields({ name: 'Dernière release', value: release.tag_name ?? 'inconnue', inline: true });
return embed;
}
/** Community activity stored locally, independent from Gitea availability (M11). */
function fwsStatsEmbed(interaction) {
const actions = countByAction(interaction.guildId);
const total = actions.reduce((sum, row) => sum + row.count, 0);
return baseEmbed(COLORS.gitea)
.setTitle('📈 Indicateurs FWS')
.addFields(
{ name: 'Tickets ouverts', value: String(countOpenTickets(interaction.guildId)), inline: true },
{ name: 'Sondages créés', value: String(countPolls(interaction.guildId)), inline: true },
{ name: 'Actions de modération', value: String(total), inline: true },
{ name: 'Dépôt', value: repositoryUrl() || 'Non configuré' },
)
.setFooter({ text: 'Statistiques locales · FWS-Bot' });
}
/** `/stats` never fails because of Gitea: the API errors are caught (M11-T03). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
await interaction.deferReply();
if (subcommand === 'discord') {
await interaction.editReply({ embeds: [discordStatsEmbed(interaction)] });
return;
}
if (subcommand === 'fws') {
try {
const releases = asList(await gitea.listReleases(1));
const embed = fwsStatsEmbed(interaction);
if (releases[0])
embed.addFields({ name: 'Version FWS Arch', value: releases[0].tag_name ?? 'inconnue' });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
log.warn('Gitea unavailable while building /stats fws', error);
await interaction.editReply({ embeds: [fwsStatsEmbed(interaction)] });
}
return;
}
try {
await interaction.editReply({ embeds: [await giteaStatsEmbed()] });
} catch (error) {
log.error('Could not read Gitea stats', error);
await interaction.editReply({
embeds: [
errorEmbed(
'Les statistiques Gitea ne répondent pas. Réessaie dans un instant — si ça continue, l’équipe peut vérifier `GITEA_URL` et `GITEA_TOKEN`. Le reste du bot fonctionne normalement.',
),
],
});
}
}
+238 -238
View File
@@ -1,238 +1,238 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { getSetting } from '../../database/repositories/settings-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { asList, gitea, isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { releaseEmbed } from '../../services/gitea/gitea-embeds.js';
import { replyGiteaFailure } from '../../services/gitea/gitea-modals.js';
import { linkButtons } from '../../ui/buttons.js';
import { baseEmbed, errorEmbed, infoEmbed } from '../../ui/embeds.js';
const log = createLogger('fws');
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('Nouveautés d’une version')
.addStringOption((option) =>
option.setName('version').setDescription('Version souhaitée (la 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 },
];
/** Guild settings are stored as JSON in SQLite; a failure falls back to the default (M4-T07). */
function readSetting(guildId, key, fallback = null) {
try {
return getSetting(guildId, key, fallback);
} catch (error) {
log.debug(`Could not read setting ${key}`, error);
return fallback;
}
}
const DEFAULT_PRESENTATION =
'FWS est une organisation open source multi-projets.\n' +
"**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale.";
async function latestRelease() {
try {
return await gitea.getLatestRelease();
} catch {
return asList(await gitea.listReleases(1))[0] ?? null;
}
}
async function showInfo(interaction) {
const configured = readSetting(interaction.guildId, 'fws.info', DEFAULT_PRESENTATION);
const description = typeof configured === 'string' && configured ? configured : DEFAULT_PRESENTATION;
await interaction.reply({
embeds: [baseEmbed().setTitle('🚀 FWS & FWS Arch').setDescription(description)],
components: linkButtons(officialLinks()),
});
}
async function showVersion(interaction) {
const fallback = readSetting(interaction.guildId, 'fws.version', null);
if (!isGiteaConfigured()) {
await interaction.reply({
embeds: [
fallback
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: errorEmbed(
'La partie Gitea n’est pas encore configurée : je ne peux pas lire la dernière version. L’équipe peut la renseigner dans le `.env`.',
),
],
});
return;
}
await interaction.deferReply();
try {
const release = await latestRelease();
if (!release) {
await interaction.editReply({
embeds: [
fallback
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: infoEmbed('📦 Version FWS Arch', 'Aucune release publiée pour le moment.'),
],
});
return;
}
await interaction.editReply({
embeds: [releaseEmbed(release, { withNotes: false })],
components: release.html_url ? linkButtons([{ label: 'Notes de version', url: release.html_url }]) : [],
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
async function showStatus(interaction) {
await interaction.deferReply();
const giteaConfigured = isGiteaConfigured();
const giteaReachable = giteaConfigured
? await gitea
.listReleases(1)
.then(() => true)
.catch(() => false)
: false;
let openTickets = null;
try {
openTickets = countOpenTickets(interaction.guildId);
} catch (error) {
log.warn('Database unavailable while building /fws status', error);
}
const uptime = Math.floor(process.uptime());
const embed = baseEmbed(COLORS.info)
.setTitle('🩺 État des services')
.addFields(
{
name: 'API Gitea',
value: !giteaConfigured
? '⚙️ Pas encore configurée'
: giteaReachable
? `✅ En ligne — ${repositoryUrl()}`
: '❌ Injoignable pour le moment',
inline: false,
},
{
name: 'Webhooks Gitea',
value: env.webhook.enabled ? '✅ Actifs' : '⚙️ Désactivés (`WEBHOOK_ENABLED=false`)',
inline: false,
},
{
name: 'Base SQLite',
value:
openTickets === null
? '❌ Indisponible pour le moment'
: `✅ Accessible — ${openTickets} ticket(s) ouvert(s)`,
inline: false,
},
{
name: 'Discord',
value: `✅ Connecté — ${Math.round(interaction.client.ws.ping)} ms`,
inline: false,
},
{ name: 'En ligne depuis', value: `<t:${Math.floor((Date.now() - uptime * 1000) / 1000)}:R>` },
);
await interaction.editReply({ embeds: [embed] });
}
async function showChangelog(interaction) {
const version = interaction.options.getString('version');
if (!isGiteaConfigured()) {
await interaction.reply({
embeds: [
errorEmbed(
'La partie Gitea n’est pas encore configurée : le changelog arrivera dès qu’elle sera branchée.',
),
],
});
return;
}
await interaction.deferReply();
try {
const release = version ? await gitea.getReleaseByTag(version) : await latestRelease();
if (!release) {
await interaction.editReply({
embeds: [
infoEmbed(
'📜 Changelog',
`Je ne trouve aucune release pour **${version}** : \`/gitea release\` liste les versions existantes.`,
),
],
});
return;
}
await interaction.editReply({
embeds: [releaseEmbed(release)],
components: release.html_url ? linkButtons([{ label: 'Ouvrir sur Gitea', url: release.html_url }]) : [],
});
} catch (error) {
if (version) {
log.warn(`Release ${version} not found`, error);
await interaction.editReply({
embeds: [
infoEmbed(
'📜 Changelog',
`Cette version **${version}** n’existe pas dans les releases Gitea : \`/gitea release\` liste celles qui existent.`,
),
],
});
return;
}
await replyGiteaFailure(interaction, error);
}
}
/** Static presentation plus live data from Gitea (M4). */
export async function execute(interaction) {
switch (interaction.options.getSubcommand()) {
case 'info':
await showInfo(interaction);
return;
case 'links':
await interaction.reply({
embeds: [baseEmbed().setTitle('🔗 Liens officiels FWS')],
components: linkButtons(officialLinks()),
});
return;
case 'version':
await showVersion(interaction);
return;
case 'status':
await showStatus(interaction);
return;
case 'changelog':
await showChangelog(interaction);
return;
default:
return;
}
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { getSetting } from '../../database/repositories/settings-repository.js';
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
import { asList, gitea, isGiteaConfigured, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { releaseEmbed } from '../../services/gitea/gitea-embeds.js';
import { replyGiteaFailure } from '../../services/gitea/gitea-modals.js';
import { linkButtons } from '../../ui/buttons.js';
import { baseEmbed, errorEmbed, infoEmbed } from '../../ui/embeds.js';
const log = createLogger('fws');
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('Nouveautés d’une version')
.addStringOption((option) =>
option.setName('version').setDescription('Version souhaitée (la 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 },
];
/** Guild settings are stored as JSON in SQLite; a failure falls back to the default (M4-T07). */
function readSetting(guildId, key, fallback = null) {
try {
return getSetting(guildId, key, fallback);
} catch (error) {
log.debug(`Could not read setting ${key}`, error);
return fallback;
}
}
const DEFAULT_PRESENTATION =
'FWS est une organisation open source multi-projets.\n' +
"**FWS Arch** est un fork d'Arch Linux avec une surcouche conviviale.";
async function latestRelease() {
try {
return await gitea.getLatestRelease();
} catch {
return asList(await gitea.listReleases(1))[0] ?? null;
}
}
async function showInfo(interaction) {
const configured = readSetting(interaction.guildId, 'fws.info', DEFAULT_PRESENTATION);
const description = typeof configured === 'string' && configured ? configured : DEFAULT_PRESENTATION;
await interaction.reply({
embeds: [baseEmbed().setTitle('🚀 FWS & FWS Arch').setDescription(description)],
components: linkButtons(officialLinks()),
});
}
async function showVersion(interaction) {
const fallback = readSetting(interaction.guildId, 'fws.version', null);
if (!isGiteaConfigured()) {
await interaction.reply({
embeds: [
fallback
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: errorEmbed(
'La partie Gitea n’est pas encore configurée : je ne peux pas lire la dernière version. L’équipe peut la renseigner dans le `.env`.',
),
],
});
return;
}
await interaction.deferReply();
try {
const release = await latestRelease();
if (!release) {
await interaction.editReply({
embeds: [
fallback
? infoEmbed('📦 Version FWS Arch', `Dernière version publiée : **${fallback}**`)
: infoEmbed('📦 Version FWS Arch', 'Aucune release publiée pour le moment.'),
],
});
return;
}
await interaction.editReply({
embeds: [releaseEmbed(release, { withNotes: false })],
components: release.html_url ? linkButtons([{ label: 'Notes de version', url: release.html_url }]) : [],
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
async function showStatus(interaction) {
await interaction.deferReply();
const giteaConfigured = isGiteaConfigured();
const giteaReachable = giteaConfigured
? await gitea
.listReleases(1)
.then(() => true)
.catch(() => false)
: false;
let openTickets = null;
try {
openTickets = countOpenTickets(interaction.guildId);
} catch (error) {
log.warn('Database unavailable while building /fws status', error);
}
const uptime = Math.floor(process.uptime());
const embed = baseEmbed(COLORS.info)
.setTitle('🩺 État des services')
.addFields(
{
name: 'API Gitea',
value: !giteaConfigured
? '⚙️ Pas encore configurée'
: giteaReachable
? `✅ En ligne — ${repositoryUrl()}`
: '❌ Injoignable pour le moment',
inline: false,
},
{
name: 'Webhooks Gitea',
value: env.webhook.enabled ? '✅ Actifs' : '⚙️ Désactivés (`WEBHOOK_ENABLED=false`)',
inline: false,
},
{
name: 'Base SQLite',
value:
openTickets === null
? '❌ Indisponible pour le moment'
: `✅ Accessible — ${openTickets} ticket(s) ouvert(s)`,
inline: false,
},
{
name: 'Discord',
value: `✅ Connecté — ${Math.round(interaction.client.ws.ping)} ms`,
inline: false,
},
{ name: 'En ligne depuis', value: `<t:${Math.floor((Date.now() - uptime * 1000) / 1000)}:R>` },
);
await interaction.editReply({ embeds: [embed] });
}
async function showChangelog(interaction) {
const version = interaction.options.getString('version');
if (!isGiteaConfigured()) {
await interaction.reply({
embeds: [
errorEmbed(
'La partie Gitea n’est pas encore configurée : le changelog arrivera dès qu’elle sera branchée.',
),
],
});
return;
}
await interaction.deferReply();
try {
const release = version ? await gitea.getReleaseByTag(version) : await latestRelease();
if (!release) {
await interaction.editReply({
embeds: [
infoEmbed(
'📜 Changelog',
`Je ne trouve aucune release pour **${version}** : \`/gitea release\` liste les versions existantes.`,
),
],
});
return;
}
await interaction.editReply({
embeds: [releaseEmbed(release)],
components: release.html_url ? linkButtons([{ label: 'Ouvrir sur Gitea', url: release.html_url }]) : [],
});
} catch (error) {
if (version) {
log.warn(`Release ${version} not found`, error);
await interaction.editReply({
embeds: [
infoEmbed(
'📜 Changelog',
`Cette version **${version}** n’existe pas dans les releases Gitea : \`/gitea release\` liste celles qui existent.`,
),
],
});
return;
}
await replyGiteaFailure(interaction, error);
}
}
/** Static presentation plus live data from Gitea (M4). */
export async function execute(interaction) {
switch (interaction.options.getSubcommand()) {
case 'info':
await showInfo(interaction);
return;
case 'links':
await interaction.reply({
embeds: [baseEmbed().setTitle('🔗 Liens officiels FWS')],
components: linkButtons(officialLinks()),
});
return;
case 'version':
await showVersion(interaction);
return;
case 'status':
await showStatus(interaction);
return;
case 'changelog':
await showChangelog(interaction);
return;
default:
return;
}
}
+25 -25
View File
@@ -1,25 +1,25 @@
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js';
import { getAccessLevel } from '../../core/permissions.js';
import { baseEmbed, bullets } 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('🤖 Tes commandes')
.setDescription(
`Tu es au niveau **${ACCESS_LABELS[level]}**. Voici ce que tu peux lancer :\n\n${bullets(lines)}`,
);
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
}
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js';
import { getAccessLevel } from '../../core/permissions.js';
import { baseEmbed, bullets } 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('🤖 Tes commandes')
.setDescription(
`Tu es au niveau **${ACCESS_LABELS[level]}**. Voici ce que tu peux lancer :\n\n${bullets(lines)}`,
);
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
}
+153 -153
View File
@@ -1,153 +1,153 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
addBotStatus,
applyBotStatus,
applyStatusIfAlone,
clearBotStatusList,
FALLBACK_STATUS,
formatSeconds,
removeBotStatus,
ROTATION_MAX_SECONDS,
ROTATION_MIN_SECONDS,
saveRotationSeconds,
STATUS_TYPE_CHOICES,
statusAddedEmbed,
statusListEmbed,
toggleBotStatus,
} from '../../services/status/bot-status-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const idOption = (option) =>
option.setName('id').setDescription('Numéro affiché par /status list').setRequired(true).setMinValue(1);
export const data = new SlashCommandBuilder()
.setName('status')
.setDescription('Statuts affichés sous le nom du bot')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addSubcommand((sub) =>
sub
.setName('add')
.setDescription('Ajouter un statut à la rotation')
.addStringOption((option) =>
option
.setName('text')
.setDescription('Texte affiché, par exemple « les tickets ouverts en un clic »')
.setRequired(true)
.setMaxLength(128),
)
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type d’activité (regarde par défaut)')
.addChoices(...STATUS_TYPE_CHOICES),
)
.addStringOption((option) =>
option.setName('url').setDescription('Lien exigé par le type « en direct »'),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Voir les statuts enregistrés'))
.addSubcommand((sub) =>
sub.setName('remove').setDescription('Retirer un statut de la rotation').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub.setName('enable').setDescription('Remettre un statut en rotation').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub.setName('disable').setDescription('Mettre un statut en pause').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub
.setName('interval')
.setDescription('Rythme de la rotation')
.addIntegerOption((option) =>
option
.setName('seconds')
.setDescription('Secondes entre deux changements')
.setRequired(true)
.setMinValue(ROTATION_MIN_SECONDS)
.setMaxValue(ROTATION_MAX_SECONDS),
),
)
.addSubcommand((sub) =>
sub.setName('clear').setDescription('Vider la liste et revenir au statut par défaut'),
);
const reply = (interaction, embed) => interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
/** The bot presence is global, but the rotation delay is stored per guild like other settings (M15). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'list') {
await reply(interaction, statusListEmbed({ guildId: interaction.guildId }));
return;
}
if (subcommand === 'add') {
const status = addBotStatus({
text: interaction.options.getString('text', true),
type: interaction.options.getString('type') ?? 'watching',
url: interaction.options.getString('url'),
createdBy: interaction.user.id,
});
// A single status is shown right away: an addition should never wait for the next turn.
const applied = applyStatusIfAlone(interaction.client) !== null;
await reply(interaction, statusAddedEmbed(status, { applied }));
return;
}
if (subcommand === 'interval') {
const seconds = saveRotationSeconds(
interaction.options.getInteger('seconds', true),
interaction.guildId,
interaction.user.id,
);
await reply(
interaction,
successEmbed(
`C’est noté : les statuts changeront toutes les **${formatSeconds(seconds)}**. Ça prend effet tout de suite, sans redémarrage.`,
),
);
return;
}
if (subcommand === 'clear') {
const removed = clearBotStatusList();
applyBotStatus(interaction.client);
await reply(
interaction,
successEmbed(
removed === 0
? `La liste était déjà vide : j’affiche « ${FALLBACK_STATUS.text} ».`
: `C’est fait : ${removed} statut(s) supprimé(s). J’affiche de nouveau « ${FALLBACK_STATUS.text} » en attendant les prochains.`,
),
);
return;
}
const id = interaction.options.getInteger('id', true);
if (subcommand === 'remove') {
const status = removeBotStatus(id);
await reply(
interaction,
successEmbed(`C’est fait : « ${status.text} » ne fait plus partie de la rotation.`),
);
return;
}
const enabled = subcommand === 'enable';
const status = toggleBotStatus(id, enabled);
if (enabled) applyStatusIfAlone(interaction.client);
await reply(
interaction,
successEmbed(
enabled
? `« ${status.text} » reprend sa place dans la rotation.`
: `« ${status.text} » est en pause : il reste dans la liste, mais ne s’affiche plus.`,
),
);
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
addBotStatus,
applyBotStatus,
applyStatusIfAlone,
clearBotStatusList,
FALLBACK_STATUS,
formatSeconds,
removeBotStatus,
ROTATION_MAX_SECONDS,
ROTATION_MIN_SECONDS,
saveRotationSeconds,
STATUS_TYPE_CHOICES,
statusAddedEmbed,
statusListEmbed,
toggleBotStatus,
} from '../../services/status/bot-status-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const idOption = (option) =>
option.setName('id').setDescription('Numéro affiché par /status list').setRequired(true).setMinValue(1);
export const data = new SlashCommandBuilder()
.setName('status')
.setDescription('Statuts affichés sous le nom du bot')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addSubcommand((sub) =>
sub
.setName('add')
.setDescription('Ajouter un statut à la rotation')
.addStringOption((option) =>
option
.setName('text')
.setDescription('Texte affiché, par exemple « les tickets ouverts en un clic »')
.setRequired(true)
.setMaxLength(128),
)
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type d’activité (regarde par défaut)')
.addChoices(...STATUS_TYPE_CHOICES),
)
.addStringOption((option) =>
option.setName('url').setDescription('Lien exigé par le type « en direct »'),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Voir les statuts enregistrés'))
.addSubcommand((sub) =>
sub.setName('remove').setDescription('Retirer un statut de la rotation').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub.setName('enable').setDescription('Remettre un statut en rotation').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub.setName('disable').setDescription('Mettre un statut en pause').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub
.setName('interval')
.setDescription('Rythme de la rotation')
.addIntegerOption((option) =>
option
.setName('seconds')
.setDescription('Secondes entre deux changements')
.setRequired(true)
.setMinValue(ROTATION_MIN_SECONDS)
.setMaxValue(ROTATION_MAX_SECONDS),
),
)
.addSubcommand((sub) =>
sub.setName('clear').setDescription('Vider la liste et revenir au statut par défaut'),
);
const reply = (interaction, embed) => interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
/** The bot presence is global, but the rotation delay is stored per guild like other settings (M15). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'list') {
await reply(interaction, statusListEmbed({ guildId: interaction.guildId }));
return;
}
if (subcommand === 'add') {
const status = addBotStatus({
text: interaction.options.getString('text', true),
type: interaction.options.getString('type') ?? 'watching',
url: interaction.options.getString('url'),
createdBy: interaction.user.id,
});
// A single status is shown right away: an addition should never wait for the next turn.
const applied = applyStatusIfAlone(interaction.client) !== null;
await reply(interaction, statusAddedEmbed(status, { applied }));
return;
}
if (subcommand === 'interval') {
const seconds = saveRotationSeconds(
interaction.options.getInteger('seconds', true),
interaction.guildId,
interaction.user.id,
);
await reply(
interaction,
successEmbed(
`C’est noté : les statuts changeront toutes les **${formatSeconds(seconds)}**. Ça prend effet tout de suite, sans redémarrage.`,
),
);
return;
}
if (subcommand === 'clear') {
const removed = clearBotStatusList();
applyBotStatus(interaction.client);
await reply(
interaction,
successEmbed(
removed === 0
? `La liste était déjà vide : j’affiche « ${FALLBACK_STATUS.text} ».`
: `C’est fait : ${removed} statut(s) supprimé(s). J’affiche de nouveau « ${FALLBACK_STATUS.text} » en attendant les prochains.`,
),
);
return;
}
const id = interaction.options.getInteger('id', true);
if (subcommand === 'remove') {
const status = removeBotStatus(id);
await reply(
interaction,
successEmbed(`C’est fait : « ${status.text} » ne fait plus partie de la rotation.`),
);
return;
}
const enabled = subcommand === 'enable';
const status = toggleBotStatus(id, enabled);
if (enabled) applyStatusIfAlone(interaction.client);
await reply(
interaction,
successEmbed(
enabled
? `« ${status.text} » reprend sa place dans la rotation.`
: `« ${status.text} » est en pause : il reste dans la liste, mais ne s’affiche plus.`,
),
);
}
+74 -74
View File
@@ -1,74 +1,74 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { replyGiteaFailure, assertGiteaConfigured } from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } 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'));
const commitLines = (commits) =>
bullets(
asList(commits)
.slice(0, 5)
.map((commit) => {
const message = commit.commit?.message?.split('\n')[0] ?? '(sans message)';
return `\`${commit.sha?.slice(0, 7)}\` ${message} — *${commit.commit?.author?.name ?? 'un compte inconnu'}*`;
}),
);
/** Read-only summaries of the repository (M5-T06 / M5-T07). */
export async function execute(interaction) {
assertGiteaConfigured();
await interaction.deferReply();
try {
if (interaction.options.getSubcommand() === 'release') {
const releases = asList(await gitea.listReleases(5));
if (releases.length === 0) {
await interaction.editReply({ embeds: [successEmbed('Aucune release publiée pour le moment.')] });
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('📦 Releases FWS Arch')
.setURL(repositoryUrl())
.setDescription(
releases
.map((release) => {
const date = release.published_at
? `<t:${Math.floor(new Date(release.published_at).getTime() / 1000)}:D>`
: 'date inconnue';
const tag = release.html_url ? `[${release.tag_name}](${release.html_url})` : release.tag_name;
return `${release.prerelease ? '🧪' : '📦'} **${tag}** — ${release.name || 'sans titre'} · ${date}`;
})
.join('\n'),
);
await interaction.editReply({ embeds: [embed] });
return;
}
const [issues, pulls, commits] = await Promise.all([
gitea.listIssues('state=open&type=issues&limit=50'),
gitea.listPullRequests('state=open&limit=50'),
gitea.listCommits(5),
]);
const embed = baseEmbed(COLORS.gitea)
.setTitle('📈 Activité récente')
.setURL(repositoryUrl())
.setDescription(commitLines(commits) || 'Aucun commit récent pour le moment.')
.addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
);
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { replyGiteaFailure, assertGiteaConfigured } from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } 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'));
const commitLines = (commits) =>
bullets(
asList(commits)
.slice(0, 5)
.map((commit) => {
const message = commit.commit?.message?.split('\n')[0] ?? '(sans message)';
return `\`${commit.sha?.slice(0, 7)}\` ${message} — *${commit.commit?.author?.name ?? 'un compte inconnu'}*`;
}),
);
/** Read-only summaries of the repository (M5-T06 / M5-T07). */
export async function execute(interaction) {
assertGiteaConfigured();
await interaction.deferReply();
try {
if (interaction.options.getSubcommand() === 'release') {
const releases = asList(await gitea.listReleases(5));
if (releases.length === 0) {
await interaction.editReply({ embeds: [successEmbed('Aucune release publiée pour le moment.')] });
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('📦 Releases FWS Arch')
.setURL(repositoryUrl())
.setDescription(
releases
.map((release) => {
const date = release.published_at
? `<t:${Math.floor(new Date(release.published_at).getTime() / 1000)}:D>`
: 'date inconnue';
const tag = release.html_url ? `[${release.tag_name}](${release.html_url})` : release.tag_name;
return `${release.prerelease ? '🧪' : '📦'} **${tag}** — ${release.name || 'sans titre'} · ${date}`;
})
.join('\n'),
);
await interaction.editReply({ embeds: [embed] });
return;
}
const [issues, pulls, commits] = await Promise.all([
gitea.listIssues('state=open&type=issues&limit=50'),
gitea.listPullRequests('state=open&limit=50'),
gitea.listCommits(5),
]);
const embed = baseEmbed(COLORS.gitea)
.setTitle('📈 Activité récente')
.setURL(repositoryUrl())
.setDescription(commitLines(commits) || 'Aucun commit récent pour le moment.')
.addFields(
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
);
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
+80 -80
View File
@@ -1,80 +1,80 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { issueEmbed } from '../../services/gitea/gitea-embeds.js';
import {
assertGiteaConfigured,
openIssueModal,
replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } 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'));
/** Issues can be browsed and created straight from Discord (M5-T02 / M5-T03). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'create') {
await openIssueModal(interaction);
return;
}
assertGiteaConfigured();
await interaction.deferReply();
try {
if (subcommand === 'view') {
const issue = await gitea.getIssue(interaction.options.getInteger('number', true));
if (!issue?.number) {
throw new UserFacingError(
'Je ne trouve pas cette issue sur Gitea : vérifie son numéro avec `/issue list`.',
);
}
await interaction.editReply({ embeds: [issueEmbed(issue)] });
return;
}
const issues = asList(await gitea.listIssues('state=open&type=issues&limit=15'));
if (issues.length === 0) {
await interaction.editReply({
embeds: [successEmbed('Aucune issue ouverte : rien en attente, tout est traité 🎉')],
});
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('🐙 Issues ouvertes')
.setURL(`${repositoryUrl()}/issues`)
.setDescription(
bullets(
issues.map(
(issue) =>
`**#${issue.number}** ${issue.title} — ouverte par *${issue.user?.login ?? 'un compte inconnu'}*`,
),
),
)
.setFooter({ text: `${issues.length} issue(s) affichée(s)` });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { issueEmbed } from '../../services/gitea/gitea-embeds.js';
import {
assertGiteaConfigured,
openIssueModal,
replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } 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'));
/** Issues can be browsed and created straight from Discord (M5-T02 / M5-T03). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'create') {
await openIssueModal(interaction);
return;
}
assertGiteaConfigured();
await interaction.deferReply();
try {
if (subcommand === 'view') {
const issue = await gitea.getIssue(interaction.options.getInteger('number', true));
if (!issue?.number) {
throw new UserFacingError(
'Je ne trouve pas cette issue sur Gitea : vérifie son numéro avec `/issue list`.',
);
}
await interaction.editReply({ embeds: [issueEmbed(issue)] });
return;
}
const issues = asList(await gitea.listIssues('state=open&type=issues&limit=15'));
if (issues.length === 0) {
await interaction.editReply({
embeds: [successEmbed('Aucune issue ouverte : rien en attente, tout est traité 🎉')],
});
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('🐙 Issues ouvertes')
.setURL(`${repositoryUrl()}/issues`)
.setDescription(
bullets(
issues.map(
(issue) =>
`**#${issue.number}** ${issue.title} — ouverte par *${issue.user?.login ?? 'un compte inconnu'}*`,
),
),
)
.setFooter({ text: `${issues.length} issue(s) affichée(s)` });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
+95 -95
View File
@@ -1,95 +1,95 @@
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { pullRequestEmbed } from '../../services/gitea/gitea-embeds.js';
import {
assertGiteaConfigured,
openPullRequestModal,
replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } 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, celle qui apporte les changements')
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('base')
.setDescription('Branche cible, celle qui reçoit les changements')
.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'));
/** The title and description are collected through a modal (M5-T04 / M5-T05). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'create') {
await openPullRequestModal(interaction);
return;
}
assertGiteaConfigured();
await interaction.deferReply();
try {
if (subcommand === 'view') {
const pull = await gitea.getPullRequest(interaction.options.getInteger('number', true));
if (!pull?.number) {
throw new UserFacingError(
'Je ne trouve pas cette pull request sur Gitea : vérifie son numéro avec `/pr list`.',
);
}
await interaction.editReply({ embeds: [pullRequestEmbed(pull)] });
return;
}
const pulls = asList(await gitea.listPullRequests('state=open&limit=15'));
if (pulls.length === 0) {
await interaction.editReply({
embeds: [successEmbed('Aucune pull request ouverte : rien à relire pour le moment 🎉')],
});
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('🐙 Pull requests ouvertes')
.setURL(`${repositoryUrl()}/pulls`)
.setDescription(
bullets(
pulls.map(
(pull) =>
`**#${pull.number}** ${pull.title} — ${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'} ` +
`(proposée par *${pull.user?.login ?? 'un compte inconnu'}*)`,
),
),
)
.setFooter({ text: `${pulls.length} PR affichée(s)` });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
import { SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
import { pullRequestEmbed } from '../../services/gitea/gitea-embeds.js';
import {
assertGiteaConfigured,
openPullRequestModal,
replyGiteaFailure,
} from '../../services/gitea/gitea-modals.js';
import { baseEmbed, bullets, successEmbed } 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, celle qui apporte les changements')
.setRequired(true),
)
.addStringOption((option) =>
option
.setName('base')
.setDescription('Branche cible, celle qui reçoit les changements')
.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'));
/** The title and description are collected through a modal (M5-T04 / M5-T05). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'create') {
await openPullRequestModal(interaction);
return;
}
assertGiteaConfigured();
await interaction.deferReply();
try {
if (subcommand === 'view') {
const pull = await gitea.getPullRequest(interaction.options.getInteger('number', true));
if (!pull?.number) {
throw new UserFacingError(
'Je ne trouve pas cette pull request sur Gitea : vérifie son numéro avec `/pr list`.',
);
}
await interaction.editReply({ embeds: [pullRequestEmbed(pull)] });
return;
}
const pulls = asList(await gitea.listPullRequests('state=open&limit=15'));
if (pulls.length === 0) {
await interaction.editReply({
embeds: [successEmbed('Aucune pull request ouverte : rien à relire pour le moment 🎉')],
});
return;
}
const embed = baseEmbed(COLORS.gitea)
.setTitle('🐙 Pull requests ouvertes')
.setURL(`${repositoryUrl()}/pulls`)
.setDescription(
bullets(
pulls.map(
(pull) =>
`**#${pull.number}** ${pull.title} — ${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'} ` +
`(proposée par *${pull.user?.login ?? 'un compte inconnu'}*)`,
),
),
)
.setFooter({ text: `${pulls.length} PR affichée(s)` });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
+56 -56
View File
@@ -1,56 +1,56 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
assertModerationTarget,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } 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('Motif').setMaxLength(500))
.addIntegerOption((option) =>
option
.setName('delete_days')
.setDescription('Supprimer aussi les messages des N derniers jours (0 à 7)')
.setMinValue(0)
.setMaxValue(7),
);
/** Bans the user, whether or not they are still on the server (M8-T04 / M8-T09). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
const deleteDays = interaction.options.getInteger('delete_days') ?? 0;
const member = await interaction.guild.members.fetch(user.id).catch(() => null);
if (member) {
assertModerationTarget(interaction, member);
await member
.send({
embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })],
})
.catch(() => {});
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await interaction.guild.bans.create(user.id, {
reason: reason ?? `Bannissement demandé par ${interaction.user.tag}`,
deleteMessageSeconds: deleteDays * 86_400,
});
await logModerationAction(interaction, { action: 'ban', targetId: user.id, reason });
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${user.tag}** ne peut plus revenir sur le serveur. L’historique reste consultable avec \`/mod logs\`.`,
),
],
});
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
assertModerationTarget,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } 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('Motif').setMaxLength(500))
.addIntegerOption((option) =>
option
.setName('delete_days')
.setDescription('Supprimer aussi les messages des N derniers jours (0 à 7)')
.setMinValue(0)
.setMaxValue(7),
);
/** Bans the user, whether or not they are still on the server (M8-T04 / M8-T09). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
const deleteDays = interaction.options.getInteger('delete_days') ?? 0;
const member = await interaction.guild.members.fetch(user.id).catch(() => null);
if (member) {
assertModerationTarget(interaction, member);
await member
.send({
embeds: [targetNoticeEmbed({ action: 'ban', guildName: interaction.guild.name, reason })],
})
.catch(() => {});
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await interaction.guild.bans.create(user.id, {
reason: reason ?? `Bannissement demandé par ${interaction.user.tag}`,
deleteMessageSeconds: deleteDays * 86_400,
});
await logModerationAction(interaction, { action: 'ban', targetId: user.id, reason });
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${user.tag}** ne peut plus revenir sur le serveur. L’historique reste consultable avec \`/mod logs\`.`,
),
],
});
}
+49 -49
View File
@@ -1,49 +1,49 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { logModerationAction } from '../../services/moderation/moderation-service.js';
import { successEmbed } 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 à supprimer (1 à 100)')
.setRequired(true)
.setMinValue(1)
.setMaxValue(100),
);
/** Bulk deletes messages in the current channel and logs it (M8-T05). */
export async function execute(interaction) {
const amount = interaction.options.getInteger('amount', true);
if (!interaction.channel?.isTextBased() || !interaction.channel.bulkDelete) {
throw new UserFacingError(
'Je ne peux pas supprimer plusieurs messages d’un coup ici : lance la commande dans un salon textuel.',
);
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const deleted = await interaction.channel.bulkDelete(amount, true);
await logModerationAction(interaction, {
action: 'clear',
targetId: null,
reason: `${deleted.size} message(s) supprimé(s) dans #${interaction.channel.name}`,
});
await interaction.editReply({
embeds: [
successEmbed(
`C’est nettoyé : ${deleted.size} message(s) supprimé(s) dans <#${interaction.channelId}>.` +
(deleted.size < amount
? '\n_Discord conserve les messages de plus de 14 jours : ils n’ont pas pu être retirés._'
: ''),
),
],
});
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { logModerationAction } from '../../services/moderation/moderation-service.js';
import { successEmbed } 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 à supprimer (1 à 100)')
.setRequired(true)
.setMinValue(1)
.setMaxValue(100),
);
/** Bulk deletes messages in the current channel and logs it (M8-T05). */
export async function execute(interaction) {
const amount = interaction.options.getInteger('amount', true);
if (!interaction.channel?.isTextBased() || !interaction.channel.bulkDelete) {
throw new UserFacingError(
'Je ne peux pas supprimer plusieurs messages d’un coup ici : lance la commande dans un salon textuel.',
);
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const deleted = await interaction.channel.bulkDelete(amount, true);
await logModerationAction(interaction, {
action: 'clear',
targetId: null,
reason: `${deleted.size} message(s) supprimé(s) dans #${interaction.channel.name}`,
});
await interaction.editReply({
embeds: [
successEmbed(
`C’est nettoyé : ${deleted.size} message(s) supprimé(s) dans <#${interaction.channelId}>.` +
(deleted.size < amount
? '\n_Discord conserve les messages de plus de 14 jours : ils n’ont pas pu être retirés._'
: ''),
),
],
});
}
+44 -44
View File
@@ -1,44 +1,44 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
assertModerationTarget,
fetchTargetMember,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } 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('Motif').setMaxLength(500));
/** Expels the member after the hierarchy checks (M8-T03 / M8-T06). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await target
.send({
embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })],
})
.catch(() => {});
await target.kick(reason ?? `Expulsion demandée par ${interaction.user.tag}`);
await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason });
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** ne fait plus partie du serveur. La personne peut revenir avec une nouvelle invitation.`,
),
],
});
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
assertModerationTarget,
fetchTargetMember,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } 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('Motif').setMaxLength(500));
/** Expels the member after the hierarchy checks (M8-T03 / M8-T06). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason');
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await target
.send({
embeds: [targetNoticeEmbed({ action: 'kick', guildName: interaction.guild.name, reason })],
})
.catch(() => {});
await target.kick(reason ?? `Expulsion demandée par ${interaction.user.tag}`);
await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason });
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** ne fait plus partie du serveur. La personne peut revenir avec une nouvelle invitation.`,
),
],
});
}
+55 -55
View File
@@ -1,55 +1,55 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
import { listActions } from '../../database/repositories/moderation-repository.js';
import { formatDuration } from '../../services/moderation/moderation-service.js';
import { baseEmbed, infoEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const HISTORY_LIMIT = 15;
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')),
);
function formatEntry(row) {
const meta = MODERATION_ACTIONS[row.action];
const target = row.target_id ? `<@${row.target_id}>` : 'salon';
const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : '';
return (
`\`${row.created_at}\` **${meta?.label ?? row.action}** — ${target}${duration}\n` +
`↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}`
);
}
/** Reads the moderation history from SQLite (M8-T06). */
export async function execute(interaction) {
const user = interaction.options.getUser('user');
const actions = listActions({
guildId: interaction.guildId,
targetId: user?.id ?? null,
limit: HISTORY_LIMIT,
});
const embed =
actions.length === 0
? infoEmbed(
'📜 Historique de modération',
user
? `Rien à signaler concernant ${user} : aucune action de modération enregistrée.`
: 'Aucune action de modération enregistrée sur ce serveur, tout est calme.',
)
: baseEmbed(COLORS.moderation)
.setTitle(user ? `📜 Historique de ${user.tag}` : '📜 Dernières actions de modération')
.setDescription(actions.map(formatEntry).join('\n\n'))
.setFooter({ text: `${actions.length} action(s) affichée(s)` });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
import { listActions } from '../../database/repositories/moderation-repository.js';
import { formatDuration } from '../../services/moderation/moderation-service.js';
import { baseEmbed, infoEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const HISTORY_LIMIT = 15;
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')),
);
function formatEntry(row) {
const meta = MODERATION_ACTIONS[row.action];
const target = row.target_id ? `<@${row.target_id}>` : 'salon';
const duration = row.duration_ms ? ` pendant ${formatDuration(row.duration_ms)}` : '';
return (
`\`${row.created_at}\` **${meta?.label ?? row.action}** — ${target}${duration}\n` +
`↳ par <@${row.moderator_id}> · ${row.reason || 'sans motif'}`
);
}
/** Reads the moderation history from SQLite (M8-T06). */
export async function execute(interaction) {
const user = interaction.options.getUser('user');
const actions = listActions({
guildId: interaction.guildId,
targetId: user?.id ?? null,
limit: HISTORY_LIMIT,
});
const embed =
actions.length === 0
? infoEmbed(
'📜 Historique de modération',
user
? `Rien à signaler concernant ${user} : aucune action de modération enregistrée.`
: 'Aucune action de modération enregistrée sur ce serveur, tout est calme.',
)
: baseEmbed(COLORS.moderation)
.setTitle(user ? `📜 Historique de ${user.tag}` : '📜 Dernières actions de modération')
.setDescription(actions.map(formatEntry).join('\n\n'))
.setFooter({ text: `${actions.length} action(s) affichée(s)` });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
}
+61 -61
View File
@@ -1,61 +1,61 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
assertModerationTarget,
fetchTargetMember,
formatDuration,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } 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 de la sanction, en minutes')
.setRequired(true)
.setMinValue(1)
.setMaxValue(40_320),
)
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const minutes = interaction.options.getInteger('minutes', true);
const reason = interaction.options.getString('reason');
const durationMs = minutes * 60_000;
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await target.timeout(durationMs, reason ?? `Exclusion temporaire de ${minutes} minutes`);
await logModerationAction(interaction, {
action: 'mute',
targetId: target.id,
reason,
durationMs,
});
await target
.send({
embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })],
})
.catch(() => {});
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** est en exclusion temporaire pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`,
),
],
});
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
assertModerationTarget,
fetchTargetMember,
formatDuration,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } 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 de la sanction, en minutes')
.setRequired(true)
.setMinValue(1)
.setMaxValue(40_320),
)
.addStringOption((option) => option.setName('reason').setDescription('Motif').setMaxLength(500));
/** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const minutes = interaction.options.getInteger('minutes', true);
const reason = interaction.options.getString('reason');
const durationMs = minutes * 60_000;
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await target.timeout(durationMs, reason ?? `Exclusion temporaire de ${minutes} minutes`);
await logModerationAction(interaction, {
action: 'mute',
targetId: target.id,
reason,
durationMs,
});
await target
.send({
embeds: [targetNoticeEmbed({ action: 'mute', guildName: interaction.guild.name, reason, durationMs })],
})
.catch(() => {});
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** est en exclusion temporaire pour **${formatDuration(durationMs)}**, la personne ne peut plus écrire pendant ce temps.`,
),
],
});
}
+105 -105
View File
@@ -1,105 +1,105 @@
import { ChannelType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, NOTIFICATION_TYPES } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
listNotificationChannels,
removeNotificationChannel,
setNotificationChannel,
} from '../../database/repositories/notification-repository.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const TYPE_CHOICES = NOTIFICATION_TYPES.map((type) => ({ name: type, value: type }));
export const data = new SlashCommandBuilder()
.setName('notify')
.setDescription('Configuration des salons de notification')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addSubcommand((sub) =>
sub
.setName('set')
.setDescription('Associer un salon à un type de notification')
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type de notification')
.setRequired(true)
.addChoices(...TYPE_CHOICES),
)
.addChannelOption((option) =>
option
.setName('channel')
.setDescription('Salon de destination')
.setRequired(true)
.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement),
),
)
.addSubcommand((sub) =>
sub
.setName('remove')
.setDescription('Revenir au salon par défaut de la configuration')
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type de notification')
.setRequired(true)
.addChoices(...TYPE_CHOICES),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Afficher la configuration actuelle'));
/** Per-guild notification routing stored in SQLite (M9-T01). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'set') {
const type = interaction.options.getString('type', true);
const channel = interaction.options.getChannel('channel', true);
setNotificationChannel({ guildId: interaction.guildId, type, channelId: channel.id });
await interaction.reply({
embeds: [
successEmbed(`C’est noté : les notifications **${type}** partent maintenant dans <#${channel.id}>.`),
],
flags: MessageFlags.Ephemeral,
});
return;
}
if (subcommand === 'remove') {
const type = interaction.options.getString('type', true);
const removed = removeNotificationChannel(interaction.guildId, type);
if (!removed) {
throw new UserFacingError(
`Le type **${type}** utilise déjà la configuration par défaut : il n’y a rien à retirer.`,
);
}
await interaction.reply({
embeds: [
successEmbed(`C’est fait : les notifications **${type}** repassent à la configuration par défaut.`),
],
flags: MessageFlags.Ephemeral,
});
return;
}
const overrides = new Map(
listNotificationChannels(interaction.guildId).map((row) => [row.type, row.channel_id]),
);
const lines = NOTIFICATION_TYPES.map((type) => {
const channelId = overrides.get(type);
return channelId
? `\`${type}\` → <#${channelId}> _(choisi sur ce serveur)_`
: `\`${type}\` → _configuration par défaut_`;
});
await interaction.reply({
embeds: [
baseEmbed()
.setTitle('🔔 Salons de notification')
.setDescription(`${bullets(lines)}\n\nPour changer une destination : \`/notify set\`.`)
.setFooter({ text: `Serveur ${interaction.guildId}` }),
],
flags: MessageFlags.Ephemeral,
});
}
import { ChannelType, MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, NOTIFICATION_TYPES } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
listNotificationChannels,
removeNotificationChannel,
setNotificationChannel,
} from '../../database/repositories/notification-repository.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const TYPE_CHOICES = NOTIFICATION_TYPES.map((type) => ({ name: type, value: type }));
export const data = new SlashCommandBuilder()
.setName('notify')
.setDescription('Configuration des salons de notification')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addSubcommand((sub) =>
sub
.setName('set')
.setDescription('Associer un salon à un type de notification')
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type de notification')
.setRequired(true)
.addChoices(...TYPE_CHOICES),
)
.addChannelOption((option) =>
option
.setName('channel')
.setDescription('Salon de destination')
.setRequired(true)
.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement),
),
)
.addSubcommand((sub) =>
sub
.setName('remove')
.setDescription('Revenir au salon par défaut de la configuration')
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type de notification')
.setRequired(true)
.addChoices(...TYPE_CHOICES),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Afficher la configuration actuelle'));
/** Per-guild notification routing stored in SQLite (M9-T01). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'set') {
const type = interaction.options.getString('type', true);
const channel = interaction.options.getChannel('channel', true);
setNotificationChannel({ guildId: interaction.guildId, type, channelId: channel.id });
await interaction.reply({
embeds: [
successEmbed(`C’est noté : les notifications **${type}** partent maintenant dans <#${channel.id}>.`),
],
flags: MessageFlags.Ephemeral,
});
return;
}
if (subcommand === 'remove') {
const type = interaction.options.getString('type', true);
const removed = removeNotificationChannel(interaction.guildId, type);
if (!removed) {
throw new UserFacingError(
`Le type **${type}** utilise déjà la configuration par défaut : il n’y a rien à retirer.`,
);
}
await interaction.reply({
embeds: [
successEmbed(`C’est fait : les notifications **${type}** repassent à la configuration par défaut.`),
],
flags: MessageFlags.Ephemeral,
});
return;
}
const overrides = new Map(
listNotificationChannels(interaction.guildId).map((row) => [row.type, row.channel_id]),
);
const lines = NOTIFICATION_TYPES.map((type) => {
const channelId = overrides.get(type);
return channelId
? `\`${type}\` → <#${channelId}> _(choisi sur ce serveur)_`
: `\`${type}\` → _configuration par défaut_`;
});
await interaction.reply({
embeds: [
baseEmbed()
.setTitle('🔔 Salons de notification')
.setDescription(`${bullets(lines)}\n\nPour changer une destination : \`/notify set\`.`)
.setFooter({ text: `Serveur ${interaction.guildId}` }),
],
flags: MessageFlags.Ephemeral,
});
}
+91 -91
View File
@@ -1,91 +1,91 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { fetchTargetMember, logModerationAction } from '../../services/moderation/moderation-service.js';
import { successEmbed } 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('Ajouter ou retirer le rôle')
.setRequired(true)
.addChoices(
{ name: 'Ajouter le rôle', value: 'add' },
{ name: 'Retirer le rôle', value: 'remove' },
),
),
);
/** Adds or removes a role after checking both hierarchies (M7-T05 / M3-T05). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const role = interaction.options.getRole('role', true);
const action = interaction.options.getString('action', true);
const adding = action === 'add';
if (role.id === interaction.guild.roles.everyone.id) {
throw new UserFacingError(
'Le rôle @everyone ne s’attribue pas : il est porté par tout le monde à la fois.',
);
}
if (role.managed) {
throw new UserFacingError(
'Ce rôle appartient à une intégration : Discord le gère tout seul, je ne peux pas le modifier.',
);
}
const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(role) <= 0) {
throw new UserFacingError(
'Je ne peux pas gérer ce rôle : il est placé plus haut que le mien. Remonte mon rôle dans la hiérarchie du serveur, et je m’en occupe.',
);
}
const target = await fetchTargetMember(interaction, user.id);
const hasRole = target.roles.cache.has(role.id);
if (adding && hasRole) {
throw new UserFacingError(`Rien à faire : **${target.user.tag}** porte déjà le rôle ${role}.`);
}
if (!adding && !hasRole) {
throw new UserFacingError(`Rien à retirer : **${target.user.tag}** n’a pas le rôle ${role}.`);
}
const isGuildOwner = interaction.guild.ownerId === interaction.user.id;
if (!isGuildOwner && interaction.member.roles.highest.comparePositionTo(role) <= 0) {
throw new UserFacingError(
'Ce rôle est au même niveau (ou plus haut) que le tien : je ne peux pas y toucher. Demande à quelqu’un de plus haut dans la hiérarchie.',
);
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
if (adding) {
await target.roles.add(role, `Ajouté par ${interaction.user.tag}`);
} else {
await target.roles.remove(role, `Retiré par ${interaction.user.tag}`);
}
await logModerationAction(interaction, {
action: 'role',
targetId: target.id,
reason: `${adding ? 'Ajout' : 'Retrait'} du rôle ${role.name} (${role.id})`,
});
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : le rôle ${role} a été ${adding ? 'ajouté à' : 'retiré de'} **${target.user.tag}**.`,
),
],
});
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { fetchTargetMember, logModerationAction } from '../../services/moderation/moderation-service.js';
import { successEmbed } 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('Ajouter ou retirer le rôle')
.setRequired(true)
.addChoices(
{ name: 'Ajouter le rôle', value: 'add' },
{ name: 'Retirer le rôle', value: 'remove' },
),
),
);
/** Adds or removes a role after checking both hierarchies (M7-T05 / M3-T05). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const role = interaction.options.getRole('role', true);
const action = interaction.options.getString('action', true);
const adding = action === 'add';
if (role.id === interaction.guild.roles.everyone.id) {
throw new UserFacingError(
'Le rôle @everyone ne s’attribue pas : il est porté par tout le monde à la fois.',
);
}
if (role.managed) {
throw new UserFacingError(
'Ce rôle appartient à une intégration : Discord le gère tout seul, je ne peux pas le modifier.',
);
}
const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(role) <= 0) {
throw new UserFacingError(
'Je ne peux pas gérer ce rôle : il est placé plus haut que le mien. Remonte mon rôle dans la hiérarchie du serveur, et je m’en occupe.',
);
}
const target = await fetchTargetMember(interaction, user.id);
const hasRole = target.roles.cache.has(role.id);
if (adding && hasRole) {
throw new UserFacingError(`Rien à faire : **${target.user.tag}** porte déjà le rôle ${role}.`);
}
if (!adding && !hasRole) {
throw new UserFacingError(`Rien à retirer : **${target.user.tag}** n’a pas le rôle ${role}.`);
}
const isGuildOwner = interaction.guild.ownerId === interaction.user.id;
if (!isGuildOwner && interaction.member.roles.highest.comparePositionTo(role) <= 0) {
throw new UserFacingError(
'Ce rôle est au même niveau (ou plus haut) que le tien : je ne peux pas y toucher. Demande à quelqu’un de plus haut dans la hiérarchie.',
);
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
if (adding) {
await target.roles.add(role, `Ajouté par ${interaction.user.tag}`);
} else {
await target.roles.remove(role, `Retiré par ${interaction.user.tag}`);
}
await logModerationAction(interaction, {
action: 'role',
targetId: target.id,
reason: `${adding ? 'Ajout' : 'Retrait'} du rôle ${role.name} (${role.id})`,
});
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : le rôle ${role} a été ${adding ? 'ajouté à' : 'retiré de'} **${target.user.tag}**.`,
),
],
});
}
+53 -53
View File
@@ -1,53 +1,53 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { countActions } from '../../database/repositories/moderation-repository.js';
import {
assertModerationTarget,
fetchTargetMember,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } 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('Motif').setRequired(true).setMaxLength(500),
);
/** Records the warning, notifies the member and logs it (M8-T01 / M8-T06). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason', true);
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await logModerationAction(interaction, { action: 'warn', targetId: target.id, reason });
const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' });
await target
.send({
embeds: [
targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({
name: 'Avertissements',
value: String(total),
}),
],
})
.catch(() => {});
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** reçoit un avertissement (${total} au total). La personne a aussi reçu un message privé quand c’était possible.`,
),
],
});
}
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { countActions } from '../../database/repositories/moderation-repository.js';
import {
assertModerationTarget,
fetchTargetMember,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } 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('Motif').setRequired(true).setMaxLength(500),
);
/** Records the warning, notifies the member and logs it (M8-T01 / M8-T06). */
export async function execute(interaction) {
const user = interaction.options.getUser('user', true);
const reason = interaction.options.getString('reason', true);
const target = await fetchTargetMember(interaction, user.id);
assertModerationTarget(interaction, target);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await logModerationAction(interaction, { action: 'warn', targetId: target.id, reason });
const total = countActions({ guildId: interaction.guildId, targetId: target.id, action: 'warn' });
await target
.send({
embeds: [
targetNoticeEmbed({ action: 'warn', guildName: interaction.guild.name, reason }).addFields({
name: 'Avertissements',
value: String(total),
}),
],
})
.catch(() => {});
await interaction.editReply({
embeds: [
successEmbed(
`C’est fait : **${target.user.tag}** reçoit un avertissement (${total} au total). La personne a aussi reçu un message privé quand c’était possible.`,
),
],
});
}
+72 -72
View File
@@ -1,72 +1,72 @@
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js';
import {
addParticipant,
claimTicket,
closeTicket,
createTicket,
} from '../../services/tickets/ticket-service.js';
import { successEmbed } 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('Motif').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)),
);
/** Ticket lifecycle: each subcommand acts on a private channel (M6-T03..T09). */
export async function execute(interaction) {
switch (interaction.options.getSubcommand()) {
case 'create': {
const categoryId = interaction.options.getString('category', true);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const channel = await createTicket(interaction, categoryId);
await interaction.editReply({
embeds: [
successEmbed(
`Ton ticket est ouvert : <#${channel.id}>. Décris ta demande dedans, une personne de l’équipe te répond dès que possible.`,
),
],
});
return;
}
case 'close':
await closeTicket(interaction, interaction.options.getString('reason'));
return;
case 'claim':
await claimTicket(interaction);
return;
case 'add':
await addParticipant(interaction, interaction.options.getUser('user', true).id);
return;
default:
return;
}
}
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, TICKET_CATEGORIES } from '../../config/constants.js';
import {
addParticipant,
claimTicket,
closeTicket,
createTicket,
} from '../../services/tickets/ticket-service.js';
import { successEmbed } 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('Motif').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)),
);
/** Ticket lifecycle: each subcommand acts on a private channel (M6-T03..T09). */
export async function execute(interaction) {
switch (interaction.options.getSubcommand()) {
case 'create': {
const categoryId = interaction.options.getString('category', true);
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const channel = await createTicket(interaction, categoryId);
await interaction.editReply({
embeds: [
successEmbed(
`Ton ticket est ouvert : <#${channel.id}>. Décris ta demande dedans, une personne de l’équipe te répond dès que possible.`,
),
],
});
return;
}
case 'close':
await closeTicket(interaction, interaction.options.getString('reason'));
return;
case 'claim':
await claimTicket(interaction);
return;
case 'add':
await addParticipant(interaction, interaction.options.getUser('user', true).id);
return;
default:
return;
}
}
+373 -373
View File
@@ -1,373 +1,373 @@
import { ChannelType, MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
activeChannelCount,
claimOwnership,
findTrigger,
kickUser,
listTriggerSummaries,
NAME_MAX,
permitUser,
postSetupPanel,
rejectUser,
removeChannel,
removeVoiceTriggerConfig,
renameChannel,
saveVoiceTrigger,
setChannelLimit,
setTriggerEnabled,
showInfo,
toggleLock,
transferOwnership,
} from '../../services/voice/voice-service.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = {
setup: ACCESS_LEVELS.STAFF,
panel: ACCESS_LEVELS.STAFF,
list: ACCESS_LEVELS.STAFF,
remove: ACCESS_LEVELS.STAFF,
enable: ACCESS_LEVELS.STAFF,
disable: ACCESS_LEVELS.STAFF,
};
const voiceChannelOption = (option) => option.addChannelTypes(ChannelType.GuildVoice);
/** Longest embed listing worth sending before it gets unreadable. */
const MAX_LISTED_TRIGGERS = 20;
export const data = new SlashCommandBuilder()
.setName('voice')
.setDescription('Gestion des salons vocaux temporaires')
.addSubcommand((sub) =>
sub
.setName('setup')
.setDescription('Ajouter ou modifier un salon déclencheur')
.addChannelOption((option) =>
voiceChannelOption(
option
.setName('trigger')
.setDescription('Salon vocal à rejoindre pour créer un salon')
.setRequired(true),
),
)
.addStringOption((option) =>
option.setName('label').setDescription('Nom du déclencheur (ex. « Dev », « SIO »)').setMaxLength(40),
)
.addChannelOption((option) =>
option
.setName('category')
.setDescription('Catégorie d’accueil des salons créés (défaut : celle du déclencheur)')
.addChannelTypes(ChannelType.GuildCategory),
)
.addStringOption((option) =>
option
.setName('template')
.setDescription('Modèle du nom, avec {user} (ex. « 🔊 Salon de {user} »)')
.setMaxLength(NAME_MAX),
)
.addIntegerOption((option) =>
option
.setName('limit')
.setDescription('Places par défaut (0 = illimité)')
.setMinValue(0)
.setMaxValue(99),
)
.addBooleanOption((option) =>
option.setName('panel').setDescription('Publier le panneau d’explication dans le salon'),
),
)
.addSubcommand((sub) => sub.setName('config').setDescription('Afficher les déclencheurs configurés'))
.addSubcommand((sub) =>
sub
.setName('panel')
.setDescription('Republier le panneau d’explication dans les salons déclencheurs')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Un seul déclencheur (défaut : tous)')),
),
)
.addSubcommandGroup((group) =>
group
.setName('triggers')
.setDescription('Gérer les salons déclencheurs')
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les déclencheurs'))
.addSubcommand((sub) =>
sub
.setName('remove')
.setDescription('Supprimer un déclencheur')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
)
.addSubcommand((sub) =>
sub
.setName('disable')
.setDescription('Désactiver un déclencheur sans le supprimer')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
)
.addSubcommand((sub) =>
sub
.setName('enable')
.setDescription('Réactiver un déclencheur')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
),
)
.addSubcommand((sub) =>
sub
.setName('name')
.setDescription('Renommer ton salon')
.addStringOption((option) =>
option.setName('name').setDescription('Nouveau nom').setRequired(true).setMaxLength(NAME_MAX),
),
)
.addSubcommand((sub) =>
sub
.setName('limit')
.setDescription('Limiter le nombre de places (0 = illimité)')
.addIntegerOption((option) =>
option
.setName('limit')
.setDescription('Nombre de places')
.setRequired(true)
.setMinValue(0)
.setMaxValue(99),
),
)
.addSubcommand((sub) => sub.setName('lock').setDescription('Verrouiller ton salon'))
.addSubcommand((sub) => sub.setName('unlock').setDescription('Déverrouiller ton salon'))
.addSubcommand((sub) =>
sub
.setName('permit')
.setDescription('Autoriser un membre à rejoindre ton salon')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('reject')
.setDescription('Interdire l’accès à un membre')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('kick')
.setDescription('Exclure un membre du salon')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('transfer')
.setDescription('Transférer la propriété du salon')
.addUserOption((option) =>
option.setName('user').setDescription('Nouveau propriétaire').setRequired(true),
),
)
.addSubcommand((sub) => sub.setName('claim').setDescription('Récupérer un salon abandonné'))
.addSubcommand((sub) =>
sub
.setName('delete')
.setDescription('Supprimer un salon temporaire')
.addChannelOption((option) =>
voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')),
),
)
.addSubcommand((sub) =>
sub
.setName('info')
.setDescription('Détails du salon temporaire')
.addChannelOption((option) =>
voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')),
),
);
const ORIGIN_LABELS = {
env: 'variables d’environnement',
settings: 'anciens réglages du bot',
};
/** One embed field per trigger, shared by `/voice config`, `/voice triggers list` and `/voice setup`. */
function describeTrigger(trigger, index = null) {
const lines = [
`**Salon :** <#${trigger.triggerId}>`,
`**Catégorie :** ${trigger.categoryId ? `<#${trigger.categoryId}>` : 'celle du salon déclencheur'}`,
`**Modèle :** \`${trigger.template}\``,
`**Limite :** ${trigger.userLimit ? `${trigger.userLimit} places` : 'illimitée'}`,
`**Salons en cours :** ${trigger.activeChannels ?? 0}`,
];
const origin = ORIGIN_LABELS[trigger.source];
if (origin) lines.push(`**Origine :** ${origin}`);
return {
name: `${index === null ? '' : `${index + 1}. `}${trigger.label ? `${trigger.label} · ` : ''}${
trigger.enabled ? '✅ Actif' : '⛔ Désactivé'
}`,
value: lines.join('\n'),
};
}
function configEmbed(guildId) {
const triggers = listTriggerSummaries(guildId);
const embed = baseEmbed(COLORS.primary).setTitle('🎧 Salons vocaux temporaires');
if (triggers.length === 0) {
return embed.setDescription(
'Aucun déclencheur pour le moment : tu peux en ajouter un avec `/voice setup` (un par thème, ex. « Dev », « SIO »).',
);
}
embed.setDescription(
`**${triggers.length}** déclencheur(s) · **${activeChannelCount(guildId)}** salon(s) temporaire(s) en cours\n` +
'Chaque déclencheur crée ses salons en bas de sa propre catégorie, et ils disparaissent dès qu’ils se vident.',
);
embed.addFields(triggers.slice(0, MAX_LISTED_TRIGGERS).map((trigger, i) => describeTrigger(trigger, i)));
if (triggers.length > MAX_LISTED_TRIGGERS) {
embed.addFields({
name: 'Autres déclencheurs',
value: `… et ${triggers.length - MAX_LISTED_TRIGGERS} autre(s), visibles sur le serveur.`,
});
}
return embed;
}
async function runSetup(interaction) {
const channel = interaction.options.getChannel('trigger', true);
if (channel.type !== ChannelType.GuildVoice) {
throw new UserFacingError('Le salon déclencheur doit être un salon **vocal**.');
}
const category = interaction.options.getChannel('category');
if (category && category.type !== ChannelType.GuildCategory) {
throw new UserFacingError('La catégorie d’accueil doit être une **catégorie**.');
}
const existing = findTrigger(interaction.guildId, channel.id);
const template = interaction.options.getString('template');
const limit = interaction.options.getInteger('limit');
const label = interaction.options.getString('label');
const trigger = saveVoiceTrigger(
interaction.guildId,
{
triggerId: channel.id,
...(label !== null && { label }),
// A trigger with no explicit category hosts its channels in its own category.
categoryId: category?.id ?? existing?.categoryId ?? channel.parentId ?? null,
...(template !== null && { template }),
...(limit !== null && { userLimit: limit }),
},
interaction.user.id,
);
if (!trigger) {
throw new UserFacingError('Le déclencheur n’a pas pu être enregistré, réessaie.');
}
const embed = baseEmbed(COLORS.success)
.setTitle(existing ? '✅ Déclencheur mis à jour' : '✅ Déclencheur ajouté')
.addFields(describeTrigger(trigger))
.setFooter({ text: 'Les salons créés depuis ce déclencheur apparaîtront en bas de sa catégorie.' });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
const wantsPanel = interaction.options.getBoolean('panel') ?? true;
if (wantsPanel) await postSetupPanel(interaction, { triggerId: channel.id }).catch(() => {});
}
/** `/voice triggers …` — declaration and lifecycle of the trigger channels (M14-T01). */
async function runTriggerGroup(interaction, subcommand) {
const guildId = interaction.guildId;
if (subcommand === 'list') {
await interaction.reply({ embeds: [configEmbed(guildId)], flags: MessageFlags.Ephemeral });
return;
}
const target = interaction.options.getChannel('trigger', true);
if (subcommand === 'remove') {
removeVoiceTriggerConfig(guildId, target.id);
await interaction.reply({
embeds: [
successEmbed(
`C’est fait : <#${target.id}> n’est plus un déclencheur. Les salons déjà créés depuis lui restent en place jusqu’à ce qu’ils se vident.`,
),
],
flags: MessageFlags.Ephemeral,
});
return;
}
const trigger = setTriggerEnabled(guildId, target.id, subcommand === 'enable');
await interaction.reply({
embeds: [
successEmbed(
trigger.enabled
? `Bon retour ! Le déclencheur <#${trigger.triggerId}> crée à nouveau des salons.`
: `Le déclencheur <#${trigger.triggerId}> est en pause : y entrer ne crée plus de salon, et sa configuration est conservée.`,
),
],
flags: MessageFlags.Ephemeral,
});
}
/** Every subcommand acts on the caller's temporary channel, checked by the service (M14-T06). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
const channel = interaction.options.getChannel('channel');
if (interaction.options.getSubcommandGroup(false) === 'triggers') {
await runTriggerGroup(interaction, subcommand);
return;
}
switch (subcommand) {
case 'setup':
await runSetup(interaction);
return;
case 'panel':
await postSetupPanel(interaction, {
triggerId: interaction.options.getChannel('trigger')?.id ?? null,
});
return;
case 'config':
await interaction.reply({ embeds: [configEmbed(interaction.guildId)], flags: MessageFlags.Ephemeral });
return;
case 'name':
await renameChannel(interaction, interaction.options.getString('name', true));
return;
case 'limit':
await setChannelLimit(interaction, interaction.options.getInteger('limit', true));
return;
case 'lock':
case 'unlock':
await toggleLock(interaction, { locked: subcommand === 'lock' });
return;
case 'permit':
await permitUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'reject':
await rejectUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'kick':
await kickUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'transfer':
await transferOwnership(interaction, interaction.options.getUser('user', true).id);
return;
case 'claim':
await claimOwnership(interaction);
return;
case 'delete':
await removeChannel(interaction, { channelId: channel?.id ?? null });
return;
case 'info':
await showInfo(interaction, { channelId: channel?.id ?? null });
return;
default:
return;
}
}
import { ChannelType, MessageFlags, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import {
activeChannelCount,
claimOwnership,
findTrigger,
kickUser,
listTriggerSummaries,
NAME_MAX,
permitUser,
postSetupPanel,
rejectUser,
removeChannel,
removeVoiceTriggerConfig,
renameChannel,
saveVoiceTrigger,
setChannelLimit,
setTriggerEnabled,
showInfo,
toggleLock,
transferOwnership,
} from '../../services/voice/voice-service.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.USER;
export const subcommandAccess = {
setup: ACCESS_LEVELS.STAFF,
panel: ACCESS_LEVELS.STAFF,
list: ACCESS_LEVELS.STAFF,
remove: ACCESS_LEVELS.STAFF,
enable: ACCESS_LEVELS.STAFF,
disable: ACCESS_LEVELS.STAFF,
};
const voiceChannelOption = (option) => option.addChannelTypes(ChannelType.GuildVoice);
/** Longest embed listing worth sending before it gets unreadable. */
const MAX_LISTED_TRIGGERS = 20;
export const data = new SlashCommandBuilder()
.setName('voice')
.setDescription('Gestion des salons vocaux temporaires')
.addSubcommand((sub) =>
sub
.setName('setup')
.setDescription('Ajouter ou modifier un salon déclencheur')
.addChannelOption((option) =>
voiceChannelOption(
option
.setName('trigger')
.setDescription('Salon vocal à rejoindre pour créer un salon')
.setRequired(true),
),
)
.addStringOption((option) =>
option.setName('label').setDescription('Nom du déclencheur (ex. « Dev », « SIO »)').setMaxLength(40),
)
.addChannelOption((option) =>
option
.setName('category')
.setDescription('Catégorie d’accueil des salons créés (défaut : celle du déclencheur)')
.addChannelTypes(ChannelType.GuildCategory),
)
.addStringOption((option) =>
option
.setName('template')
.setDescription('Modèle du nom, avec {user} (ex. « 🔊 Salon de {user} »)')
.setMaxLength(NAME_MAX),
)
.addIntegerOption((option) =>
option
.setName('limit')
.setDescription('Places par défaut (0 = illimité)')
.setMinValue(0)
.setMaxValue(99),
)
.addBooleanOption((option) =>
option.setName('panel').setDescription('Publier le panneau d’explication dans le salon'),
),
)
.addSubcommand((sub) => sub.setName('config').setDescription('Afficher les déclencheurs configurés'))
.addSubcommand((sub) =>
sub
.setName('panel')
.setDescription('Republier le panneau d’explication dans les salons déclencheurs')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Un seul déclencheur (défaut : tous)')),
),
)
.addSubcommandGroup((group) =>
group
.setName('triggers')
.setDescription('Gérer les salons déclencheurs')
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les déclencheurs'))
.addSubcommand((sub) =>
sub
.setName('remove')
.setDescription('Supprimer un déclencheur')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
)
.addSubcommand((sub) =>
sub
.setName('disable')
.setDescription('Désactiver un déclencheur sans le supprimer')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
)
.addSubcommand((sub) =>
sub
.setName('enable')
.setDescription('Réactiver un déclencheur')
.addChannelOption((option) =>
voiceChannelOption(option.setName('trigger').setDescription('Salon').setRequired(true)),
),
),
)
.addSubcommand((sub) =>
sub
.setName('name')
.setDescription('Renommer ton salon')
.addStringOption((option) =>
option.setName('name').setDescription('Nouveau nom').setRequired(true).setMaxLength(NAME_MAX),
),
)
.addSubcommand((sub) =>
sub
.setName('limit')
.setDescription('Limiter le nombre de places (0 = illimité)')
.addIntegerOption((option) =>
option
.setName('limit')
.setDescription('Nombre de places')
.setRequired(true)
.setMinValue(0)
.setMaxValue(99),
),
)
.addSubcommand((sub) => sub.setName('lock').setDescription('Verrouiller ton salon'))
.addSubcommand((sub) => sub.setName('unlock').setDescription('Déverrouiller ton salon'))
.addSubcommand((sub) =>
sub
.setName('permit')
.setDescription('Autoriser un membre à rejoindre ton salon')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('reject')
.setDescription('Interdire l’accès à un membre')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('kick')
.setDescription('Exclure un membre du salon')
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true)),
)
.addSubcommand((sub) =>
sub
.setName('transfer')
.setDescription('Transférer la propriété du salon')
.addUserOption((option) =>
option.setName('user').setDescription('Nouveau propriétaire').setRequired(true),
),
)
.addSubcommand((sub) => sub.setName('claim').setDescription('Récupérer un salon abandonné'))
.addSubcommand((sub) =>
sub
.setName('delete')
.setDescription('Supprimer un salon temporaire')
.addChannelOption((option) =>
voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')),
),
)
.addSubcommand((sub) =>
sub
.setName('info')
.setDescription('Détails du salon temporaire')
.addChannelOption((option) =>
voiceChannelOption(option.setName('channel').setDescription('Salon (staff uniquement)')),
),
);
const ORIGIN_LABELS = {
env: 'variables d’environnement',
settings: 'anciens réglages du bot',
};
/** One embed field per trigger, shared by `/voice config`, `/voice triggers list` and `/voice setup`. */
function describeTrigger(trigger, index = null) {
const lines = [
`**Salon :** <#${trigger.triggerId}>`,
`**Catégorie :** ${trigger.categoryId ? `<#${trigger.categoryId}>` : 'celle du salon déclencheur'}`,
`**Modèle :** \`${trigger.template}\``,
`**Limite :** ${trigger.userLimit ? `${trigger.userLimit} places` : 'illimitée'}`,
`**Salons en cours :** ${trigger.activeChannels ?? 0}`,
];
const origin = ORIGIN_LABELS[trigger.source];
if (origin) lines.push(`**Origine :** ${origin}`);
return {
name: `${index === null ? '' : `${index + 1}. `}${trigger.label ? `${trigger.label} · ` : ''}${
trigger.enabled ? '✅ Actif' : '⛔ Désactivé'
}`,
value: lines.join('\n'),
};
}
function configEmbed(guildId) {
const triggers = listTriggerSummaries(guildId);
const embed = baseEmbed(COLORS.primary).setTitle('🎧 Salons vocaux temporaires');
if (triggers.length === 0) {
return embed.setDescription(
'Aucun déclencheur pour le moment : tu peux en ajouter un avec `/voice setup` (un par thème, ex. « Dev », « SIO »).',
);
}
embed.setDescription(
`**${triggers.length}** déclencheur(s) · **${activeChannelCount(guildId)}** salon(s) temporaire(s) en cours\n` +
'Chaque déclencheur crée ses salons en bas de sa propre catégorie, et ils disparaissent dès qu’ils se vident.',
);
embed.addFields(triggers.slice(0, MAX_LISTED_TRIGGERS).map((trigger, i) => describeTrigger(trigger, i)));
if (triggers.length > MAX_LISTED_TRIGGERS) {
embed.addFields({
name: 'Autres déclencheurs',
value: `… et ${triggers.length - MAX_LISTED_TRIGGERS} autre(s), visibles sur le serveur.`,
});
}
return embed;
}
async function runSetup(interaction) {
const channel = interaction.options.getChannel('trigger', true);
if (channel.type !== ChannelType.GuildVoice) {
throw new UserFacingError('Le salon déclencheur doit être un salon **vocal**.');
}
const category = interaction.options.getChannel('category');
if (category && category.type !== ChannelType.GuildCategory) {
throw new UserFacingError('La catégorie d’accueil doit être une **catégorie**.');
}
const existing = findTrigger(interaction.guildId, channel.id);
const template = interaction.options.getString('template');
const limit = interaction.options.getInteger('limit');
const label = interaction.options.getString('label');
const trigger = saveVoiceTrigger(
interaction.guildId,
{
triggerId: channel.id,
...(label !== null && { label }),
// A trigger with no explicit category hosts its channels in its own category.
categoryId: category?.id ?? existing?.categoryId ?? channel.parentId ?? null,
...(template !== null && { template }),
...(limit !== null && { userLimit: limit }),
},
interaction.user.id,
);
if (!trigger) {
throw new UserFacingError('Le déclencheur n’a pas pu être enregistré, réessaie.');
}
const embed = baseEmbed(COLORS.success)
.setTitle(existing ? '✅ Déclencheur mis à jour' : '✅ Déclencheur ajouté')
.addFields(describeTrigger(trigger))
.setFooter({ text: 'Les salons créés depuis ce déclencheur apparaîtront en bas de sa catégorie.' });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
const wantsPanel = interaction.options.getBoolean('panel') ?? true;
if (wantsPanel) await postSetupPanel(interaction, { triggerId: channel.id }).catch(() => {});
}
/** `/voice triggers …` — declaration and lifecycle of the trigger channels (M14-T01). */
async function runTriggerGroup(interaction, subcommand) {
const guildId = interaction.guildId;
if (subcommand === 'list') {
await interaction.reply({ embeds: [configEmbed(guildId)], flags: MessageFlags.Ephemeral });
return;
}
const target = interaction.options.getChannel('trigger', true);
if (subcommand === 'remove') {
removeVoiceTriggerConfig(guildId, target.id);
await interaction.reply({
embeds: [
successEmbed(
`C’est fait : <#${target.id}> n’est plus un déclencheur. Les salons déjà créés depuis lui restent en place jusqu’à ce qu’ils se vident.`,
),
],
flags: MessageFlags.Ephemeral,
});
return;
}
const trigger = setTriggerEnabled(guildId, target.id, subcommand === 'enable');
await interaction.reply({
embeds: [
successEmbed(
trigger.enabled
? `Bon retour ! Le déclencheur <#${trigger.triggerId}> crée à nouveau des salons.`
: `Le déclencheur <#${trigger.triggerId}> est en pause : y entrer ne crée plus de salon, et sa configuration est conservée.`,
),
],
flags: MessageFlags.Ephemeral,
});
}
/** Every subcommand acts on the caller's temporary channel, checked by the service (M14-T06). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
const channel = interaction.options.getChannel('channel');
if (interaction.options.getSubcommandGroup(false) === 'triggers') {
await runTriggerGroup(interaction, subcommand);
return;
}
switch (subcommand) {
case 'setup':
await runSetup(interaction);
return;
case 'panel':
await postSetupPanel(interaction, {
triggerId: interaction.options.getChannel('trigger')?.id ?? null,
});
return;
case 'config':
await interaction.reply({ embeds: [configEmbed(interaction.guildId)], flags: MessageFlags.Ephemeral });
return;
case 'name':
await renameChannel(interaction, interaction.options.getString('name', true));
return;
case 'limit':
await setChannelLimit(interaction, interaction.options.getInteger('limit', true));
return;
case 'lock':
case 'unlock':
await toggleLock(interaction, { locked: subcommand === 'lock' });
return;
case 'permit':
await permitUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'reject':
await rejectUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'kick':
await kickUser(interaction, interaction.options.getUser('user', true).id);
return;
case 'transfer':
await transferOwnership(interaction, interaction.options.getUser('user', true).id);
return;
case 'claim':
await claimOwnership(interaction);
return;
case 'delete':
await removeChannel(interaction, { channelId: channel?.id ?? null });
return;
case 'info':
await showInfo(interaction, { channelId: channel?.id ?? null });
return;
default:
return;
}
}