import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js'; import { env } from '../../config/env.js'; import { readSetting } from '../../config/guild-settings.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( 'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.', ); } if (target.id === interaction.user.id) { throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi‑même 😅 Vise un autre membre.'); } if (!canActOn(interaction.member, target)) { throw new UserFacingError( 'Cette personne a un rôle égal ou supérieur au tien : je ne peux pas la viser. Demande à quelqu’un de plus haut dans la hiérarchie si c’est nécessaire.', ); } const bot = interaction.guild.members.me; if (bot && bot.roles.highest.comparePositionTo(target.roles.highest) <= 0) { throw new UserFacingError( `Je ne peux pas agir sur ${target.user.tag} : mon rôle est placé plus bas que le sien. Remonte mon rôle dans les paramètres du serveur, et je m’en occupe.`, ); } } /** * 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: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true }, { name: 'Par', value: `<@${moderatorId}>`, inline: true }, { name: 'Motif', value: reason || 'Non précisé' }, ); 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(() => {}); } /** * Sends the private notice to the sanctioned member, when the server wants one * (M8-T07). Never throws: plenty of accounts refuse direct messages, and that * must not turn a successful sanction into an error. * @param guildId Server the sanction belongs to. A lifted ban targets someone * who has left the server, so a plain `User` is accepted with an explicit id. */ export async function notifyTarget(member, payload, guildId = member.guild?.id) { if (!readSetting('moderation.dmTarget', guildId)) return false; return member .send(payload) .then(() => true) .catch(() => false); } /** 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}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`, ) .addFields({ name: 'Motif', value: reason || 'Non précisé' }); 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( 'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.', ); } return member; }