Files
FWS-DiscordBot/src/commands/voice/voice.js
T

374 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { 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;
}
}