Build/project structure #142

Merged
BlackAngelTV merged 80 commits from build/project-structure into main 2026-09-23 14:31:21 +02:00
9 changed files with 460 additions and 30 deletions
Showing only changes of commit c49c60071d - Show all commits

No files matched your search

+32 -4
View File
@@ -1,6 +1,11 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
import {
assertModerationTarget,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
@@ -18,7 +23,30 @@ export const data = new SlashCommandBuilder()
.setMaxValue(7),
);
// TODO(M8-T04): ban after canActOn() check and log the sensitive action (M8-T09).
/** Bans the user, whether or not they are still on the server (M8-T04 / M8-T09). */
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/ban')] });
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 ?? `Banni par ${interaction.user.tag}`,
deleteMessageSeconds: deleteDays * 86_400,
});
await logModerationAction(interaction, { action: 'ban', targetId: user.id, reason });
await interaction.editReply({
embeds: [successEmbed(`**${user.tag}** a été banni du serveur.`)],
});
}
+26 -4
View File
@@ -1,6 +1,8 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.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;
@@ -17,7 +19,27 @@ export const data = new SlashCommandBuilder()
.setMaxValue(100),
);
// TODO(M8-T05): channel.bulkDelete(amount, true) and log the action.
/** Bulk deletes messages in the current channel and logs it (M8-T05). */
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/clear')] });
const amount = interaction.options.getInteger('amount', true);
if (!interaction.channel?.isTextBased() || !interaction.channel.bulkDelete) {
throw new UserFacingError('La suppression groupée n’est pas possible dans ce salon.');
}
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(
`${deleted.size} message(s) supprimé(s) dans <#${interaction.channelId}>.` +
(deleted.size < amount ? '\n_Les messages de plus de 14 jours sont conservés par Discord._' : ''),
),
],
});
}
+27 -4
View File
@@ -1,6 +1,12 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
import {
assertModerationTarget,
fetchTargetMember,
logModerationAction,
targetNoticeEmbed,
} from '../../services/moderation/moderation-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
@@ -11,7 +17,24 @@ export const data = new SlashCommandBuilder()
.addUserOption((option) => option.setName('user').setDescription('Membre').setRequired(true))
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500));
// TODO(M8-T03): kick after canActOn() check and log the action.
/** Expels the member after the hierarchy checks (M8-T03 / M8-T06). */
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/kick')] });
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 ?? `Expulsé par ${interaction.user.tag}`);
await logModerationAction(interaction, { action: 'kick', targetId: target.id, reason });
await interaction.editReply({
embeds: [successEmbed(`**${target.user.tag}** a été expulsé du serveur.`)],
});
}
+38 -6
View File
@@ -1,9 +1,13 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.js';
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')
@@ -15,7 +19,35 @@ export const data = new SlashCommandBuilder()
.addUserOption((option) => option.setName('user').setDescription('Filtrer par membre')),
);
// TODO(M8-T06): read from moderation_actions.
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/mod logs')] });
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 raison'}`
);
}
/** 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 ? `Aucune action enregistrée contre ${user}.` : 'Aucune action enregistrée sur ce serveur.',
)
: 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} dernière(s) action(s)` });
await interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
}
+38 -4
View File
@@ -1,6 +1,13 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.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;
@@ -19,7 +26,34 @@ export const data = new SlashCommandBuilder()
)
.addStringOption((option) => option.setName('reason').setDescription('Raison').setMaxLength(500));
// TODO(M8-T02 / M8-T07): use member.timeout() after canActOn() check.
/** Applies a Discord timeout after the hierarchy checks (M8-T02 / M8-T07). */
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/mute')] });
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(`**${target.user.tag}** est réduit au silence pendant **${formatDuration(durationMs)}**.`),
],
});
}
+97
View File
@@ -0,0 +1,97 @@
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, 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(`Les notifications **${type}** seront envoyées 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(`Aucun salon personnalisé n’est configuré pour **${type}**.`);
await interaction.reply({
embeds: [successEmbed(`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}> _(personnalisé)_`
: `\`${type}\` → _configuration par défaut_`;
});
await interaction.reply({
embeds: [
baseEmbed()
.setTitle('Salons de notification')
.setDescription(lines.join('\n'))
.setFooter({ text: `Serveur ${interaction.guildId}` }),
],
flags: MessageFlags.Ephemeral,
});
}
+50 -4
View File
@@ -1,6 +1,8 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.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;
@@ -23,7 +25,51 @@ export const data = new SlashCommandBuilder()
),
);
// TODO(M7-T05 / M7-T06): enforce role hierarchy (M3-T05) and log the change.
/** Adds or removes a role after checking both hierarchies (M7-T05 / M3-T05). */
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/role set')] });
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 peut pas être attribué.');
}
if (role.managed) {
throw new UserFacingError('Ce rôle est géré par une intégration et ne peut pas être modifié.');
}
const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(role) <= 0) {
throw new UserFacingError('Mon rôle est trop bas pour gérer ce rôle.');
}
const target = await fetchTargetMember(interaction, user.id);
const hasRole = target.roles.cache.has(role.id);
if (adding && hasRole) throw new UserFacingError(`**${target.user.tag}** possède déjà le rôle ${role}.`);
if (!adding && !hasRole)
throw new UserFacingError(`**${target.user.tag}** ne possède 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('Tu ne peux pas gérer un rôle au-dessus ou égal au tien.');
}
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(`Le rôle ${role} a été ${adding ? 'ajouté à' : 'retiré de'} **${target.user.tag}**.`),
],
});
}
+34 -4
View File
@@ -1,6 +1,13 @@
import { PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { notImplementedEmbed } from '../../ui/embeds.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;
@@ -13,7 +20,30 @@ export const data = new SlashCommandBuilder()
option.setName('reason').setDescription('Raison').setRequired(true).setMaxLength(500),
);
// TODO(M8-T01): record in moderation_actions and log (M8-T06).
/** Records the warning, notifies the member and logs it (M8-T01 / M8-T06). */
export async function execute(interaction) {
await interaction.reply({ embeds: [notImplementedEmbed('/warn')] });
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(`**${target.user.tag}** a été averti (${total} avertissement(s) au total).`)],
});
}
@@ -0,0 +1,118 @@
import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { UserFacingError } from '../../core/errors.js';
import { canActOn } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { recordAction } from '../../database/repositories/moderation-repository.js';
import { baseEmbed } from '../../ui/embeds.js';
/**
* Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08).
* @param {import('discord.js').ChatInputCommandInteraction} interaction
* @param {import('discord.js').GuildMember} target
*/
export function assertModerationTarget(interaction, target) {
if (!target) throw new UserFacingError('Ce membre n’est pas présent sur le serveur.');
if (target.id === interaction.user.id) {
throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi-même.');
}
if (!canActOn(interaction.member, target)) {
throw new UserFacingError('Tu ne peux pas agir sur ce membre : son rôle est égal ou supérieur au tien.');
}
const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(target.roles.highest) <= 0) {
throw new UserFacingError(`Mon rôle est trop bas pour agir sur ${target.user.tag}.`);
}
}
/**
* Records the action in SQLite and mirrors it in the moderation log channel (M8-T06).
* Call it only once the Discord action has succeeded.
*/
export async function logModerationAction(
interaction,
{ action, targetId, reason = null, durationMs = null },
) {
recordAction({
guildId: interaction.guildId,
action,
moderatorId: interaction.user.id,
targetId,
reason,
durationMs,
});
logEvent({
guildId: interaction.guildId,
type: `moderation.${action}`,
actorId: interaction.user.id,
payload: { targetId, reason, durationMs },
});
const meta = MODERATION_ACTIONS[action];
await sendModerationLog(interaction.client, interaction.guild, {
action,
color: meta?.color ?? COLORS.moderation,
targetId,
moderatorId: interaction.user.id,
reason,
durationMs,
});
}
/** Posts an entry in `CHANNEL_MOD_LOGS_ID`, if configured (M8-T06). */
export async function sendModerationLog(
client,
guild,
{ action, targetId, moderatorId, reason, durationMs },
) {
if (!env.channels.modLogs) return;
const channel = await client.channels.fetch(env.channels.modLogs).catch(() => null);
if (!channel?.isSendable()) return;
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color)
.setTitle(`Modération — ${meta?.label ?? action}`)
.addFields(
{ name: 'Cible', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true },
{ name: 'Modérateur', value: `<@${moderatorId}>`, inline: true },
{ name: 'Raison', value: reason || 'Non précisée' },
);
if (durationMs) {
embed.addFields({ name: 'Durée', value: formatDuration(durationMs), inline: true });
}
if (guild) embed.setFooter({ text: `${guild.name} · ${guild.id}` });
await channel.send({ embeds: [embed] }).catch(() => {});
}
/** Direct message sent to the member who is being moderated (M8-T07). */
export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) {
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color)
.setTitle(`Sanction sur ${guildName}`)
.setDescription(`Action : **${meta?.label ?? action}**`)
.addFields({ name: 'Raison', value: reason || 'Non précisée' });
if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) });
return embed;
}
/** Human readable duration for embeds: `2 h 30 min`. */
export function formatDuration(durationMs) {
const minutes = Math.round(durationMs / 60_000);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
if (hours < 24) return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`;
const days = Math.floor(hours / 24);
const remainingHours = hours % 24;
return remainingHours === 0 ? `${days} j` : `${days} j ${remainingHours} h`;
}
/** Fetches the member targeted by a command, with a clear error if absent. */
export async function fetchTargetMember(interaction, userId) {
const member = await interaction.guild.members.fetch(userId).catch(() => null);
if (!member) throw new UserFacingError('Ce membre n’est pas présent sur le serveur.');
return member;
}