Members read all replies as one voice, so the wording now lives in one place:
the shared titles, the list marker and the "what to do next" hint come from
src/ui/embeds.js, and every module follows them.
An error explains the cause, recalls the rule and offers the way out instead of
blaming; a success says what happens next. Nothing agrees on the gender of a
person ("utilisateur", "cher/chère", "ravie"), which also keeps the sentences
shorter. Two tests lock the shared titles and reject gendered descriptions.
1002 lines
34 KiB
JavaScript
1002 lines
34 KiB
JavaScript
import {
|
||
ActionRowBuilder,
|
||
ChannelType,
|
||
MessageFlags,
|
||
ModalBuilder,
|
||
PermissionFlagsBits,
|
||
TextInputBuilder,
|
||
TextInputStyle,
|
||
} from 'discord.js';
|
||
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
|
||
import { env } from '../../config/env.js';
|
||
import { PermissionDeniedError, UserFacingError } from '../../core/errors.js';
|
||
import { createLogger } from '../../core/logger.js';
|
||
import { getAccessLevel } from '../../core/permissions.js';
|
||
import { logEvent } from '../../database/repositories/event-log-repository.js';
|
||
import { resolveSetting } from '../../database/repositories/settings-repository.js';
|
||
import {
|
||
addVoiceChannel,
|
||
countVoiceChannels,
|
||
countVoiceChannelsByTrigger,
|
||
getVoiceChannel,
|
||
listOwnedVoiceChannels,
|
||
listVoiceChannels,
|
||
removeVoiceChannel,
|
||
setVoiceLimit,
|
||
setVoiceLocked,
|
||
setVoiceName,
|
||
setVoiceOwner,
|
||
} from '../../database/repositories/voice-repository.js';
|
||
import {
|
||
listVoiceTriggers,
|
||
removeVoiceTrigger as deleteVoiceTriggerRow,
|
||
upsertVoiceTrigger,
|
||
} from '../../database/repositories/voice-trigger-repository.js';
|
||
import { voicePanelComponents } from '../../ui/buttons.js';
|
||
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
|
||
|
||
const log = createLogger('voice');
|
||
|
||
export const DEFAULT_TEMPLATE = '🔊 Salon de {user}';
|
||
/** Discord caps the user limit of a voice channel at 99 (0 means unlimited). */
|
||
export const LIMIT_MAX = 99;
|
||
export const NAME_MAX = 100;
|
||
/**
|
||
* Delay before an empty temporary channel is deleted, so a quick move does not destroy a channel
|
||
* its owner customised. `VOICE_EMPTY_GRACE_MS=0` deletes it as soon as it is empty (M14-T04).
|
||
*/
|
||
const EMPTY_GRACE_MS = Math.max(0, env.voice.emptyGraceMs);
|
||
/** Interval of the safety net that catches the channels an event could not clean up. */
|
||
const SWEEP_INTERVAL_MS = 60_000;
|
||
|
||
/** Creation in flight per member, to never create two channels for the same person (M14-T02). */
|
||
const pendingCreations = new Set();
|
||
/** Channel id -> panel message id, so buttons can be refreshed after a change (M14-T05). */
|
||
const panelMessages = new Map();
|
||
|
||
const VIEW = PermissionFlagsBits.ViewChannel;
|
||
const CONNECT = PermissionFlagsBits.Connect;
|
||
const SPEAK = PermissionFlagsBits.Speak;
|
||
const MEMBER_ALLOW = [VIEW, CONNECT, SPEAK];
|
||
const OWNER_ALLOW = [...MEMBER_ALLOW, PermissionFlagsBits.ManageChannels, PermissionFlagsBits.MoveMembers];
|
||
/** Named form required by `permissionOverwrites.edit()` (permission bits are not keys). */
|
||
const OWNER_OVERWRITE = Object.freeze({
|
||
ViewChannel: true,
|
||
Connect: true,
|
||
Speak: true,
|
||
ManageChannels: true,
|
||
MoveMembers: true,
|
||
});
|
||
|
||
/** Strips control characters without a control-character regex, then collapses spaces. */
|
||
const clean = (value) =>
|
||
[...String(value ?? '')]
|
||
.map((char) => {
|
||
const code = char.codePointAt(0);
|
||
return code <= 31 || code === 127 ? ' ' : char;
|
||
})
|
||
.join('')
|
||
.replace(/\s+/g, ' ')
|
||
.trim();
|
||
|
||
/** Channel names are normalised and truncated before they reach Discord (M14-T08). */
|
||
export function sanitizeChannelName(value) {
|
||
const name = clean(value);
|
||
if (!name) throw new UserFacingError('Il me manque un nom : écris au moins un caractère pour ton salon.');
|
||
return name.slice(0, NAME_MAX);
|
||
}
|
||
|
||
/** `🔊 Salon de {user}` -> the name of the channel created for a member. */
|
||
export function buildChannelName(template, member) {
|
||
const replaced = String(template || DEFAULT_TEMPLATE).replaceAll(
|
||
'{user}',
|
||
member.displayName ?? member.user?.username ?? '',
|
||
);
|
||
return clean(replaced).slice(0, NAME_MAX) || '🔊 Salon vocal';
|
||
}
|
||
|
||
/** `0` means unlimited; anything outside 0..99 is rejected or ignored (M14-T06). */
|
||
export function clampLimit(value, { strict = false } = {}) {
|
||
const limit = Number(value);
|
||
if (!Number.isInteger(limit) || limit < 0 || limit > LIMIT_MAX) {
|
||
if (strict) {
|
||
throw new UserFacingError(
|
||
`Indique un nombre entre 0 (aucune limite) et ${LIMIT_MAX}. Par exemple 5 pour cinq places.`,
|
||
);
|
||
}
|
||
return 0;
|
||
}
|
||
return limit;
|
||
}
|
||
|
||
/** Index of the last slot of a category once the new channel is part of it (M14-T02). */
|
||
export function bottomPosition(childCount) {
|
||
return Math.max(0, Number(childCount) - 1);
|
||
}
|
||
|
||
/**
|
||
* Every trigger channel declared for a guild, so one server can host several of them
|
||
* ("dev", "sio", …), each with its own home category (M14-T01). Triggers written by the
|
||
* single-trigger version and the environment are still accepted as fallbacks.
|
||
*/
|
||
export function getVoiceTriggers(guildId) {
|
||
const triggers = new Map();
|
||
|
||
let rows = [];
|
||
try {
|
||
rows = listVoiceTriggers(guildId);
|
||
} catch (error) {
|
||
log.warn('Could not read the voice triggers', error);
|
||
}
|
||
|
||
for (const row of rows) {
|
||
triggers.set(row.trigger_id, {
|
||
triggerId: row.trigger_id,
|
||
label: row.label || null,
|
||
categoryId: row.category_id || null,
|
||
template: row.template || DEFAULT_TEMPLATE,
|
||
userLimit: clampLimit(row.user_limit),
|
||
enabled: Boolean(row.enabled),
|
||
source: 'database',
|
||
});
|
||
}
|
||
|
||
const legacyId = resolveSetting(guildId, 'voice.trigger', null);
|
||
if (legacyId && !triggers.has(legacyId)) {
|
||
triggers.set(legacyId, {
|
||
triggerId: legacyId,
|
||
label: null,
|
||
categoryId: resolveSetting(guildId, 'voice.category', env.channels.voiceCategory) || null,
|
||
template: resolveSetting(guildId, 'voice.template', DEFAULT_TEMPLATE) || DEFAULT_TEMPLATE,
|
||
userLimit: clampLimit(resolveSetting(guildId, 'voice.limit', 0)),
|
||
enabled: true,
|
||
source: 'settings',
|
||
});
|
||
}
|
||
|
||
const envId = env.channels.voiceTrigger;
|
||
if (envId && !triggers.has(envId)) {
|
||
triggers.set(envId, {
|
||
triggerId: envId,
|
||
label: null,
|
||
categoryId: env.channels.voiceCategory || null,
|
||
template: DEFAULT_TEMPLATE,
|
||
userLimit: 0,
|
||
enabled: true,
|
||
source: 'env',
|
||
});
|
||
}
|
||
|
||
return [...triggers.values()];
|
||
}
|
||
|
||
/** Any declared trigger, disabled ones included, so the commands can report and toggle them. */
|
||
export function findTrigger(guildId, triggerId) {
|
||
return getVoiceTriggers(guildId).find((trigger) => trigger.triggerId === triggerId) ?? null;
|
||
}
|
||
|
||
/** An enabled trigger: joining it creates a temporary channel (M14-T02). */
|
||
export function getVoiceTrigger(guildId, triggerId) {
|
||
const trigger = findTrigger(guildId, triggerId);
|
||
return trigger?.enabled ? trigger : null;
|
||
}
|
||
|
||
export function isTriggerChannel(guildId, channelId) {
|
||
return getVoiceTrigger(guildId, channelId) !== null;
|
||
}
|
||
|
||
/** Triggers with the number of channels they currently host, for the configuration embed. */
|
||
export function listTriggerSummaries(guildId) {
|
||
return getVoiceTriggers(guildId).map((trigger) => ({
|
||
...trigger,
|
||
activeChannels: countVoiceChannelsByTrigger(trigger.triggerId),
|
||
}));
|
||
}
|
||
|
||
/** Declares or updates a trigger; an omitted field keeps its stored value (M14-T01). */
|
||
export function saveVoiceTrigger(guildId, patch, updatedBy = null) {
|
||
const existing = patch.triggerId ? findTrigger(guildId, patch.triggerId) : null;
|
||
|
||
upsertVoiceTrigger({
|
||
triggerId: patch.triggerId,
|
||
guildId,
|
||
label: patch.label ?? existing?.label ?? null,
|
||
categoryId: patch.categoryId ?? existing?.categoryId ?? null,
|
||
template: patch.template ?? existing?.template ?? DEFAULT_TEMPLATE,
|
||
userLimit: clampLimit(patch.userLimit ?? existing?.userLimit ?? 0),
|
||
enabled: patch.enabled ?? existing?.enabled ?? true,
|
||
});
|
||
|
||
logEvent({
|
||
guildId,
|
||
type: 'voice.trigger.saved',
|
||
actorId: updatedBy,
|
||
payload: { triggerId: patch.triggerId },
|
||
});
|
||
return findTrigger(guildId, patch.triggerId);
|
||
}
|
||
|
||
/** Writes the trigger before toggling it, so an environment fallback can be switched off. */
|
||
export function setTriggerEnabled(guildId, triggerId, enabled) {
|
||
const trigger = findTrigger(guildId, triggerId);
|
||
if (!trigger)
|
||
throw new UserFacingError('Ce salon n’est pas un déclencheur : ajoute-le d’abord avec `/voice setup`.');
|
||
if (trigger.enabled === enabled) {
|
||
throw new UserFacingError(
|
||
enabled
|
||
? 'Ce déclencheur est déjà actif — il n’y a rien à changer.'
|
||
: 'Ce déclencheur est déjà désactivé — il n’y a rien à changer.',
|
||
);
|
||
}
|
||
|
||
upsertVoiceTrigger({
|
||
triggerId,
|
||
guildId,
|
||
label: trigger.label,
|
||
categoryId: trigger.categoryId,
|
||
template: trigger.template,
|
||
userLimit: trigger.userLimit,
|
||
enabled,
|
||
});
|
||
logEvent({ guildId, type: 'voice.trigger.toggled', payload: { triggerId, enabled } });
|
||
return findTrigger(guildId, triggerId);
|
||
}
|
||
|
||
/** Removes a trigger declared from Discord; the ones coming from the environment cannot be deleted. */
|
||
export function removeVoiceTriggerConfig(guildId, triggerId) {
|
||
const trigger = findTrigger(guildId, triggerId);
|
||
if (!trigger)
|
||
throw new UserFacingError('Ce salon n’est pas un déclencheur : il n’y a donc rien à supprimer.');
|
||
if (trigger.source !== 'database') {
|
||
throw new UserFacingError(
|
||
'Ce déclencheur vient des variables d’environnement (`CHANNEL_VOICE_TRIGGER_ID`) : je ne peux pas le supprimer d’ici. Retire‑le du `.env`, ou mets‑le en pause avec `/voice triggers disable`.',
|
||
);
|
||
}
|
||
|
||
deleteVoiceTriggerRow(triggerId);
|
||
logEvent({ guildId, type: 'voice.trigger.removed', payload: { triggerId } });
|
||
}
|
||
|
||
export function isStaff(member, roles = env.roles) {
|
||
return getAccessLevel(member, roles) >= ACCESS_LEVELS.STAFF;
|
||
}
|
||
|
||
export function isManagedChannel(channelId) {
|
||
return Boolean(getVoiceChannel(channelId));
|
||
}
|
||
|
||
/** Embed shown in the panel and by `/voice info` (M14-T05). */
|
||
export function voicePanelEmbed(channel, row) {
|
||
const ownerId = row?.owner_id ?? null;
|
||
return baseEmbed(COLORS.primary)
|
||
.setTitle(`Gestion de ${channel.name}`)
|
||
.setDescription(
|
||
'Les boutons ci-dessous agissent sur ce salon seulement. Tu retrouves exactement les mêmes options dans `/voice`.',
|
||
)
|
||
.addFields(
|
||
{ name: 'Propriétaire', value: ownerId ? `<@${ownerId}>` : 'Personne', inline: true },
|
||
{ name: 'Statut', value: row?.locked ? '🔒 Verrouillé' : '🔓 Ouvert', inline: true },
|
||
{ name: 'Limite', value: row?.user_limit ? `${row.user_limit} places` : 'Illimitée', inline: true },
|
||
{
|
||
name: 'Membres',
|
||
value: row?.user_limit ? `${channel.members.size} / ${row.user_limit}` : String(channel.members.size),
|
||
inline: true,
|
||
},
|
||
);
|
||
}
|
||
|
||
export function voiceInfoEmbed(channel, row) {
|
||
const embed = baseEmbed(COLORS.primary)
|
||
.setTitle(channel.name)
|
||
.addFields(
|
||
{ name: 'Propriétaire', value: row?.owner_id ? `<@${row.owner_id}>` : 'Personne', inline: true },
|
||
{ name: 'Statut', value: row?.locked ? '🔒 Verrouillé' : '🔓 Ouvert', inline: true },
|
||
{ name: 'Limite', value: row?.user_limit ? `${row.user_limit} places` : 'Illimitée', inline: true },
|
||
{
|
||
name: 'Membres',
|
||
value:
|
||
channel.members.size === 0
|
||
? 'Aucun'
|
||
: channel.members
|
||
.first(10)
|
||
.map((member) => `<@${member.id}>`)
|
||
.join(', '),
|
||
},
|
||
)
|
||
.addFields({ name: 'Créé', value: `<t:${Math.floor(channel.createdTimestamp / 1000)}:R>`, inline: true });
|
||
|
||
if (row?.trigger_id)
|
||
embed.setFooter({ text: `Salon temporaire · créé depuis le déclencheur ${row.trigger_id}` });
|
||
return embed;
|
||
}
|
||
|
||
/** Posts the control panel in the text chat of the voice channel (M14-T05). */
|
||
async function postPanel(channel, row) {
|
||
if (!channel.isSendable?.()) return;
|
||
|
||
const message = await channel
|
||
.send({
|
||
embeds: [voicePanelEmbed(channel, row)],
|
||
components: voicePanelComponents({ locked: Boolean(row.locked) }),
|
||
})
|
||
.catch((error) => {
|
||
log.warn('Could not post the voice panel', error);
|
||
return null;
|
||
});
|
||
if (message) panelMessages.set(channel.id, message.id);
|
||
}
|
||
|
||
/** Refreshes the panel buttons after a change, best effort (M14-T05). */
|
||
export async function refreshPanel(channel) {
|
||
const messageId = panelMessages.get(channel.id);
|
||
const row = getVoiceChannel(channel.id);
|
||
if (!messageId || !row || !channel.isSendable?.()) return;
|
||
|
||
const message = await channel.messages.fetch(messageId).catch(() => null);
|
||
await message
|
||
?.edit({
|
||
embeds: [voicePanelEmbed(channel, row)],
|
||
components: voicePanelComponents({ locked: Boolean(row.locked) }),
|
||
})
|
||
.catch(() => {});
|
||
}
|
||
|
||
/** Drops a channel from the database and from the panel cache. */
|
||
function forgetVoiceChannel(channelId) {
|
||
removeVoiceChannel(channelId);
|
||
panelMessages.delete(channelId);
|
||
}
|
||
|
||
/**
|
||
* The channel an owner can be moved back into: only one created from the same trigger, so that
|
||
* each trigger keeps its own channel in its own category (M14-T03). Rows of vanished channels
|
||
* are dropped along the way, whichever trigger they came from.
|
||
*/
|
||
async function findReusableChannel(guild, ownerId, triggerId) {
|
||
for (const row of listOwnedVoiceChannels(guild.id, ownerId)) {
|
||
const channel = guild.channels.cache.get(row.channel_id);
|
||
if (!channel) {
|
||
forgetVoiceChannel(row.channel_id);
|
||
continue;
|
||
}
|
||
if (row.trigger_id !== triggerId) continue;
|
||
|
||
const full = channel.userLimit > 0 && channel.members.size >= channel.userLimit;
|
||
if (!full) return { channel, row };
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** New channels are appended below the ones already sitting in the target category (M14-T02). */
|
||
async function placeAtBottomOfCategory(channel) {
|
||
if (!channel.parentId) return;
|
||
|
||
const siblings = channel.guild.channels.cache.filter(
|
||
(candidate) => candidate.parentId === channel.parentId,
|
||
);
|
||
const target = bottomPosition(siblings.size);
|
||
if (channel.position === target) return;
|
||
|
||
await channel
|
||
.setPosition(target, { reason: 'Nouveau salon en bas de sa catégorie' })
|
||
.catch((error) => log.warn('Could not move the new channel to the bottom of its category', error));
|
||
}
|
||
|
||
function buildOverwrites(guild, client, ownerId) {
|
||
return [
|
||
{ id: guild.roles.everyone.id, allow: MEMBER_ALLOW },
|
||
{ id: ownerId, allow: OWNER_ALLOW },
|
||
{ id: client.user.id, allow: OWNER_ALLOW },
|
||
];
|
||
}
|
||
|
||
/**
|
||
* Called when a member joins a trigger channel: creates their channel in the category of that
|
||
* trigger, below the channels already there, or moves them back into the one they already own
|
||
* (M14-T02 / M14-T03).
|
||
*/
|
||
export async function createFromTrigger(member, trigger) {
|
||
if (!trigger?.triggerId || pendingCreations.has(member.id)) return null;
|
||
|
||
const reusable = await findReusableChannel(member.guild, member.id, trigger.triggerId);
|
||
if (reusable) {
|
||
await member.voice
|
||
.setChannel(reusable.channel, 'Retour dans son salon vocal temporaire')
|
||
.catch((error) => log.warn('Could not move the member back into their channel', error));
|
||
return reusable.channel;
|
||
}
|
||
|
||
pendingCreations.add(member.id);
|
||
try {
|
||
const parent = trigger.categoryId
|
||
? await member.guild.channels.fetch(trigger.categoryId).catch(() => null)
|
||
: null;
|
||
|
||
const channel = await member.guild.channels.create({
|
||
name: buildChannelName(trigger.template, member),
|
||
type: ChannelType.GuildVoice,
|
||
userLimit: trigger.userLimit,
|
||
...(parent?.type === ChannelType.GuildCategory && { parent: parent.id }),
|
||
reason: `Salon vocal temporaire de ${member.user.tag}`,
|
||
permissionOverwrites: buildOverwrites(member.guild, member.client, member.id),
|
||
});
|
||
|
||
await placeAtBottomOfCategory(channel);
|
||
|
||
addVoiceChannel({
|
||
channelId: channel.id,
|
||
guildId: member.guild.id,
|
||
ownerId: member.id,
|
||
triggerId: trigger.triggerId,
|
||
name: channel.name,
|
||
userLimit: trigger.userLimit,
|
||
});
|
||
|
||
await member.voice
|
||
.setChannel(channel, 'Salon vocal temporaire créé')
|
||
.catch((error) => log.warn('Could not move the member into their new channel', error));
|
||
|
||
await postPanel(channel, getVoiceChannel(channel.id));
|
||
logEvent({
|
||
guildId: member.guild.id,
|
||
type: 'voice.created',
|
||
actorId: member.id,
|
||
payload: { channelId: channel.id, ownerId: member.id },
|
||
});
|
||
return channel;
|
||
} finally {
|
||
pendingCreations.delete(member.id);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Deletes a temporary channel. The row is only dropped once the channel is really gone, so that a
|
||
* failed API call leaves a channel the sweep can retry instead of an orphaned room (M14-T04).
|
||
*/
|
||
export async function deleteVoiceChannel(channel, reason = 'Salon vocal temporaire supprimé') {
|
||
try {
|
||
await channel.delete(reason);
|
||
} catch (error) {
|
||
if (!(await isChannelGone(channel, error))) {
|
||
log.warn('Could not delete the voice channel', error);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
forgetVoiceChannel(channel.id);
|
||
return true;
|
||
}
|
||
|
||
/** A 404 or an unknown-channel error means the channel is already deleted, whatever the cause. */
|
||
async function isChannelGone(channel, error) {
|
||
const codes = [error?.code, String(error?.code ?? '')];
|
||
if (error?.status === 404 || codes.includes(10003)) return true;
|
||
|
||
const fresh = await channel.guild.channels.fetch(channel.id).catch(() => null);
|
||
return fresh === null;
|
||
}
|
||
|
||
/** Resolves a channel from the cache or the API, or `null` when it does not exist anymore. */
|
||
async function resolveChannel(guild, channelId) {
|
||
return guild.channels.cache.get(channelId) ?? (await guild.channels.fetch(channelId).catch(() => null));
|
||
}
|
||
|
||
/**
|
||
* Deletes an empty temporary channel after a short grace period, so that a member moving between
|
||
* channels does not lose the one they customised (M14-T04).
|
||
*/
|
||
export async function cleanupVoiceChannel(guild, channelId, { graceMs = EMPTY_GRACE_MS } = {}) {
|
||
const row = getVoiceChannel(channelId);
|
||
if (!row) return;
|
||
|
||
const channel = await resolveChannel(guild, channelId);
|
||
if (!channel) {
|
||
forgetVoiceChannel(channelId);
|
||
return;
|
||
}
|
||
if (channel.members.size > 0) return;
|
||
|
||
const removeEmptyChannel = async () => {
|
||
const fresh = await resolveChannel(guild, channelId);
|
||
if (!fresh) {
|
||
forgetVoiceChannel(channelId);
|
||
return;
|
||
}
|
||
if (fresh.members.size > 0) return;
|
||
|
||
if (await deleteVoiceChannel(fresh, 'Salon vocal temporaire vide')) {
|
||
logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId } });
|
||
}
|
||
};
|
||
|
||
if (graceMs <= 0) {
|
||
await removeEmptyChannel().catch((error) => log.warn('Could not clean up an empty voice channel', error));
|
||
return;
|
||
}
|
||
|
||
setTimeout(
|
||
() => removeEmptyChannel().catch((error) => log.warn('Could not clean up an empty voice channel', error)),
|
||
graceMs,
|
||
).unref();
|
||
}
|
||
|
||
/**
|
||
* Forgets the channels that no longer exist and deletes the ones with nobody left in them
|
||
* (M14-T04 / M14-T07). Run at startup and then every minute: the voice state event is the fast
|
||
* path, this sweep is the guarantee when an event is missed or a deletion failed.
|
||
*/
|
||
export async function sweepVoiceChannels(client) {
|
||
for (const guild of client.guilds.cache.values()) {
|
||
let rows = [];
|
||
try {
|
||
rows = listVoiceChannels(guild.id);
|
||
} catch (error) {
|
||
log.warn('Could not read the stored voice channels', error);
|
||
continue;
|
||
}
|
||
|
||
for (const row of rows) {
|
||
const channel = await resolveChannel(guild, row.channel_id);
|
||
if (!channel) {
|
||
forgetVoiceChannel(row.channel_id);
|
||
continue;
|
||
}
|
||
if (channel.members.size > 0) continue;
|
||
|
||
if (await deleteVoiceChannel(channel, 'Salon vocal temporaire vide')) {
|
||
log.info(`Deleted the empty temporary channel ${row.channel_id}`);
|
||
logEvent({ guildId: guild.id, type: 'voice.deleted', payload: { channelId: row.channel_id } });
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/** Starts the periodic sweep; the returned interval can be cleared to stop it (M14-T04). */
|
||
export function startVoiceJanitor(client, intervalMs = SWEEP_INTERVAL_MS) {
|
||
const timer = setInterval(() => {
|
||
sweepVoiceChannels(client).catch((error) => log.error('Voice channel sweep failed', error));
|
||
}, intervalMs);
|
||
timer.unref?.();
|
||
return timer;
|
||
}
|
||
|
||
export function activeChannelCount(guildId) {
|
||
return countVoiceChannels(guildId);
|
||
}
|
||
|
||
/** Channel of the interaction itself, when it is a temporary voice channel (panel buttons and modals). */
|
||
function managedChannelOf(interaction) {
|
||
return interaction.channelId && isManagedChannel(interaction.channelId) ? interaction.channelId : null;
|
||
}
|
||
|
||
/**
|
||
* Resolves the temporary channel an action applies to: the explicit option first, then the
|
||
* channel the interaction happened in (panel, modal), then the voice channel of the caller (M14-T05).
|
||
*/
|
||
export async function resolveManagedChannel(interaction, { channelId = null } = {}) {
|
||
const id = channelId ?? managedChannelOf(interaction) ?? interaction.member?.voice?.channelId ?? null;
|
||
const row = id ? getVoiceChannel(id) : null;
|
||
if (!row) {
|
||
throw new UserFacingError(
|
||
'Je ne trouve pas ton salon temporaire : entre dans ton salon vocal, puis relance la commande — ou indique‑le avec l’option `channel`.',
|
||
);
|
||
}
|
||
if (channelId && channelId !== interaction.member?.voice?.channelId && !isStaff(interaction.member)) {
|
||
// An explicit channel is a staff convenience only: a member manages their own channel.
|
||
throw new PermissionDeniedError(
|
||
'C’est réservé à l’équipe : chaque personne gère son propre salon. Tu peux modifier le tien, sans option `channel`.',
|
||
);
|
||
}
|
||
|
||
const channel = await interaction.guild.channels.fetch(row.channel_id).catch(() => null);
|
||
if (!channel) {
|
||
forgetVoiceChannel(row.channel_id);
|
||
throw new UserFacingError('Ce salon n’existe plus — il a sûrement déjà été supprimé.');
|
||
}
|
||
return { channel, row };
|
||
}
|
||
|
||
/** Only the owner may manage a channel; staff can always step in (M14-T06). */
|
||
export function assertVoiceOwner(interaction, row, action = 'gérer ce salon') {
|
||
if (row.owner_id === interaction.user.id || isStaff(interaction.member)) return;
|
||
throw new PermissionDeniedError(
|
||
`Ce salon appartient à <@${row.owner_id}> : seule cette personne (ou l’équipe) peut ${action}.`,
|
||
);
|
||
}
|
||
|
||
const ephemeral = (payload) => ({ ...payload, flags: MessageFlags.Ephemeral });
|
||
|
||
export async function renameChannel(interaction, name) {
|
||
const { channel, row } = await resolveManagedChannel(interaction);
|
||
assertVoiceOwner(interaction, row, 'renommer le salon');
|
||
|
||
const sanitized = sanitizeChannelName(name);
|
||
await channel.setName(sanitized, `Renommé par ${interaction.user.tag}`);
|
||
setVoiceName(channel.id, sanitized);
|
||
await refreshPanel(channel);
|
||
|
||
await interaction.reply(
|
||
ephemeral({ embeds: [successEmbed(`Ton salon s’appelle maintenant **${sanitized}**.`)] }),
|
||
);
|
||
}
|
||
|
||
export async function setChannelLimit(interaction, limit) {
|
||
const { channel, row } = await resolveManagedChannel(interaction);
|
||
assertVoiceOwner(interaction, row, 'changer la limite');
|
||
|
||
const value = clampLimit(limit, { strict: true });
|
||
await channel.setUserLimit(value, `Limite modifiée par ${interaction.user.tag}`);
|
||
setVoiceLimit(channel.id, value);
|
||
await refreshPanel(channel);
|
||
|
||
await interaction.reply(
|
||
ephemeral({
|
||
embeds: [
|
||
successEmbed(
|
||
value === 0
|
||
? 'Ton salon n’a plus de limite de places : tout le monde peut entrer.'
|
||
: `Ton salon accueille maintenant **${value} personnes**.`,
|
||
),
|
||
],
|
||
}),
|
||
);
|
||
}
|
||
|
||
export async function toggleLock(interaction, { locked = null } = {}) {
|
||
const { channel, row } = await resolveManagedChannel(interaction);
|
||
assertVoiceOwner(interaction, row, 'verrouiller le salon');
|
||
|
||
const next = locked === null ? !row.locked : Boolean(locked);
|
||
if (next === Boolean(row.locked)) {
|
||
throw new UserFacingError(
|
||
next
|
||
? 'Ton salon est déjà verrouillé — il n’y a rien à changer.'
|
||
: 'Ton salon est déjà ouvert — il n’y a rien à changer.',
|
||
);
|
||
}
|
||
await channel.permissionOverwrites.edit(
|
||
interaction.guild.roles.everyone.id,
|
||
{ Connect: next ? false : null },
|
||
{ reason: `${next ? 'Verrouillé' : 'Déverrouillé'} par ${interaction.user.tag}` },
|
||
);
|
||
setVoiceLocked(channel.id, next);
|
||
await refreshPanel(channel);
|
||
|
||
await interaction.reply(
|
||
ephemeral({
|
||
embeds: [
|
||
successEmbed(
|
||
next
|
||
? '🔒 Salon verrouillé : seules les personnes que tu autorises peuvent entrer.'
|
||
: '🔓 Salon ouvert : tout le monde peut entrer.',
|
||
),
|
||
],
|
||
}),
|
||
);
|
||
}
|
||
|
||
export async function permitUser(interaction, userId) {
|
||
const { channel, row } = await resolveManagedChannel(interaction);
|
||
assertVoiceOwner(interaction, row, 'autoriser un membre');
|
||
|
||
await channel.permissionOverwrites.edit(
|
||
userId,
|
||
{ ViewChannel: true, Connect: true },
|
||
{
|
||
reason: `Autorisé par ${interaction.user.tag}`,
|
||
},
|
||
);
|
||
await interaction.reply(
|
||
ephemeral({ embeds: [successEmbed(`C’est noté : <@${userId}> peut entrer dans ton salon.`)] }),
|
||
);
|
||
}
|
||
|
||
export async function rejectUser(interaction, userId) {
|
||
const { channel, row } = await resolveManagedChannel(interaction);
|
||
assertVoiceOwner(interaction, row, 'refuser un membre');
|
||
|
||
await channel.permissionOverwrites.edit(
|
||
userId,
|
||
{ ViewChannel: false, Connect: false },
|
||
{
|
||
reason: `Refusé par ${interaction.user.tag}`,
|
||
},
|
||
);
|
||
const member = channel.members.get(userId);
|
||
await member?.voice.disconnect(`Refusé par ${interaction.user.tag}`).catch(() => {});
|
||
|
||
await interaction.reply(
|
||
ephemeral({ embeds: [successEmbed(`C’est noté : <@${userId}> ne peut plus entrer dans ton salon.`)] }),
|
||
);
|
||
}
|
||
|
||
export async function kickUser(interaction, userId) {
|
||
const { channel, row } = await resolveManagedChannel(interaction);
|
||
assertVoiceOwner(interaction, row, 'exclure un membre');
|
||
|
||
const member = channel.members.get(userId);
|
||
if (!member) throw new UserFacingError('Ce membre n’est pas dans ton salon — il n’y a rien à faire.');
|
||
if (member.id === row.owner_id)
|
||
throw new UserFacingError('Impossible : la personne propriétaire du salon ne peut pas en être exclue.');
|
||
|
||
await member.voice.disconnect(`Exclu par ${interaction.user.tag}`);
|
||
await interaction.reply(
|
||
ephemeral({ embeds: [successEmbed(`<@${userId}> ne fait plus partie de ton salon.`)] }),
|
||
);
|
||
}
|
||
|
||
export async function transferOwnership(interaction, userId) {
|
||
const { channel, row } = await resolveManagedChannel(interaction);
|
||
assertVoiceOwner(interaction, row, 'transférer le salon');
|
||
|
||
const member = channel.members.get(userId);
|
||
if (!member)
|
||
throw new UserFacingError(
|
||
'Cette personne doit déjà être dans le salon pour en devenir propriétaire : invite‑la, puis relance la commande.',
|
||
);
|
||
if (member.id === row.owner_id)
|
||
throw new UserFacingError('Cette personne est déjà propriétaire de ce salon.');
|
||
|
||
await channel.permissionOverwrites
|
||
.edit(row.owner_id, { ManageChannels: null, MoveMembers: null }, { reason: 'Nouveau propriétaire' })
|
||
.catch(() => {});
|
||
await channel.permissionOverwrites.edit(member.id, OWNER_OVERWRITE, {
|
||
reason: `Salon transféré par ${interaction.user.tag}`,
|
||
});
|
||
|
||
setVoiceOwner(channel.id, member.id);
|
||
await refreshPanel(channel);
|
||
logEvent({
|
||
guildId: interaction.guildId,
|
||
type: 'voice.transferred',
|
||
actorId: interaction.user.id,
|
||
payload: { channelId: channel.id, ownerId: member.id },
|
||
});
|
||
|
||
await interaction.reply(
|
||
ephemeral({
|
||
embeds: [
|
||
successEmbed(`<@${member.id}> est désormais propriétaire de **${channel.name}**. Bonne session !`),
|
||
],
|
||
}),
|
||
);
|
||
}
|
||
|
||
/** A member may take over a channel whose owner is gone (M14-T03). */
|
||
export async function claimOwnership(interaction) {
|
||
const { channel, row } = await resolveManagedChannel(interaction);
|
||
if (row.owner_id === interaction.user.id) {
|
||
throw new UserFacingError('Tu es déjà propriétaire de ce salon — tout est en ordre.');
|
||
}
|
||
if (channel.members.has(row.owner_id)) {
|
||
throw new UserFacingError(
|
||
'La personne propriétaire est encore dans le salon : ce salon n’est pas abandonné.',
|
||
);
|
||
}
|
||
if (!channel.members.has(interaction.user.id)) {
|
||
throw new UserFacingError(
|
||
'Entre d’abord dans le salon, puis relance la commande : la propriété se réclame depuis l’intérieur.',
|
||
);
|
||
}
|
||
|
||
await channel.permissionOverwrites.edit(interaction.user.id, OWNER_OVERWRITE, {
|
||
reason: `Salon réclamé par ${interaction.user.tag}`,
|
||
});
|
||
setVoiceOwner(channel.id, interaction.user.id);
|
||
await refreshPanel(channel);
|
||
logEvent({
|
||
guildId: interaction.guildId,
|
||
type: 'voice.claimed',
|
||
actorId: interaction.user.id,
|
||
payload: { channelId: channel.id },
|
||
});
|
||
|
||
await interaction.reply(
|
||
ephemeral({ embeds: [successEmbed('Tu es désormais propriétaire de ce salon. Amuse‑toi bien !')] }),
|
||
);
|
||
}
|
||
|
||
export async function removeChannel(interaction, { channelId = null } = {}) {
|
||
const { channel, row } = await resolveManagedChannel(interaction, { channelId });
|
||
assertVoiceOwner(interaction, row, 'supprimer le salon');
|
||
|
||
await interaction.reply(
|
||
ephemeral({
|
||
embeds: [
|
||
successEmbed(`Le salon **${channel.name}** disparaît dans 3 secondes. Merci pour la session !`),
|
||
],
|
||
}),
|
||
);
|
||
logEvent({
|
||
guildId: interaction.guildId,
|
||
type: 'voice.deleted',
|
||
actorId: interaction.user.id,
|
||
payload: { channelId: channel.id },
|
||
});
|
||
setTimeout(
|
||
() => deleteVoiceChannel(channel, `Supprimé par ${interaction.user.tag}`).catch(() => {}),
|
||
3_000,
|
||
).unref();
|
||
}
|
||
|
||
export async function showInfo(interaction, { channelId = null } = {}) {
|
||
const { channel, row } = await resolveManagedChannel(interaction, { channelId });
|
||
await interaction.reply(ephemeral({ embeds: [voiceInfoEmbed(channel, row)] }));
|
||
}
|
||
|
||
/** Embed published in a trigger channel to explain the "join to create" flow (M14-T01). */
|
||
function triggerPanelEmbed(trigger, channel) {
|
||
return baseEmbed(COLORS.primary)
|
||
.setTitle('🎧 Salons vocaux temporaires')
|
||
.setDescription(
|
||
`Rejoins ${channel} pour obtenir ton propre salon vocal.\n\n` +
|
||
'Tu en deviens le propriétaire : renomme-le, limite le nombre de places, verrouille-le, ' +
|
||
'autorise ou exclus des membres, ou transfère-le — depuis les boutons du salon ou les commandes `/voice`.',
|
||
)
|
||
.addFields(
|
||
{
|
||
name: 'Catégorie',
|
||
value: trigger.categoryId ? `<#${trigger.categoryId}>` : 'Celle du salon déclencheur',
|
||
inline: true,
|
||
},
|
||
{
|
||
name: 'Limite par défaut',
|
||
value: trigger.userLimit ? `${trigger.userLimit} places` : 'Illimitée',
|
||
inline: true,
|
||
},
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Publishes the explanation panel in one trigger, or in every enabled trigger of the guild
|
||
* when no trigger is given (M14-T01).
|
||
*/
|
||
export async function postSetupPanel(interaction, { triggerId = null } = {}) {
|
||
const triggers = getVoiceTriggers(interaction.guildId).filter(
|
||
(trigger) => trigger.enabled && (!triggerId || trigger.triggerId === triggerId),
|
||
);
|
||
if (triggers.length === 0) {
|
||
throw new UserFacingError(
|
||
triggerId
|
||
? 'Ce salon n’est pas un déclencheur actif : configure‑le avec `/voice setup`.'
|
||
: 'Aucun salon vocal déclencheur n’est configuré : lance `/voice setup`.',
|
||
);
|
||
}
|
||
|
||
const published = [];
|
||
for (const trigger of triggers) {
|
||
const channel = await interaction.guild.channels.fetch(trigger.triggerId).catch(() => null);
|
||
if (!channel?.isVoiceBased?.() || !channel.isSendable()) {
|
||
log.warn(`Skipped the panel of ${trigger.triggerId}: not a sendable voice channel`);
|
||
continue;
|
||
}
|
||
|
||
await channel.send({ embeds: [triggerPanelEmbed(trigger, channel)] }).catch((error) => {
|
||
log.warn('Could not publish the voice panel', error);
|
||
});
|
||
published.push(trigger.triggerId);
|
||
}
|
||
|
||
if (published.length === 0) {
|
||
throw new UserFacingError(
|
||
'Aucun panneau n’a pu être publié : vérifie que je peux écrire dans les salons déclencheurs.',
|
||
);
|
||
}
|
||
|
||
await interaction.reply(
|
||
ephemeral({
|
||
embeds: [successEmbed(`Panneau publié dans ${published.map((id) => `<#${id}>`).join(', ')}.`)],
|
||
}),
|
||
);
|
||
}
|
||
|
||
/** Button and select menu routing (M14-T05). */
|
||
export async function handleVoiceComponent(interaction) {
|
||
const action = interaction.customId.split(':')[1];
|
||
|
||
if (interaction.isUserSelectMenu()) {
|
||
const userId = interaction.values[0];
|
||
switch (action) {
|
||
case 'permit':
|
||
await permitUser(interaction, userId);
|
||
return;
|
||
case 'kick':
|
||
await kickUser(interaction, userId);
|
||
return;
|
||
case 'transfer':
|
||
await transferOwnership(interaction, userId);
|
||
return;
|
||
default:
|
||
log.debug(`Ignored voice select ${interaction.customId}`);
|
||
return;
|
||
}
|
||
}
|
||
|
||
switch (action) {
|
||
case 'rename':
|
||
await openRenameModal(interaction);
|
||
return;
|
||
case 'limit':
|
||
await openLimitModal(interaction);
|
||
return;
|
||
case 'lock':
|
||
await toggleLock(interaction);
|
||
return;
|
||
case 'claim':
|
||
await claimOwnership(interaction);
|
||
return;
|
||
case 'info':
|
||
await showInfo(interaction);
|
||
return;
|
||
case 'delete':
|
||
await removeChannel(interaction);
|
||
return;
|
||
default:
|
||
log.debug(`Ignored voice component ${interaction.customId}`);
|
||
}
|
||
}
|
||
|
||
async function openRenameModal(interaction) {
|
||
const { channel, row } = await resolveManagedChannel(interaction);
|
||
assertVoiceOwner(interaction, row, 'renommer le salon');
|
||
|
||
await interaction.showModal(
|
||
new ModalBuilder()
|
||
.setCustomId('voice:rename:modal')
|
||
.setTitle('Renommer le salon')
|
||
.addComponents(
|
||
new ActionRowBuilder().addComponents(
|
||
new TextInputBuilder()
|
||
.setCustomId('name')
|
||
.setLabel('Nouveau nom')
|
||
.setStyle(TextInputStyle.Short)
|
||
.setMaxLength(NAME_MAX)
|
||
.setValue(channel.name.slice(0, NAME_MAX))
|
||
.setRequired(true),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
async function openLimitModal(interaction) {
|
||
const { row } = await resolveManagedChannel(interaction);
|
||
assertVoiceOwner(interaction, row, 'changer la limite');
|
||
|
||
await interaction.showModal(
|
||
new ModalBuilder()
|
||
.setCustomId('voice:limit:modal')
|
||
.setTitle('Limite de places')
|
||
.addComponents(
|
||
new ActionRowBuilder().addComponents(
|
||
new TextInputBuilder()
|
||
.setCustomId('limit')
|
||
.setLabel(`Entre 0 (illimité) et ${LIMIT_MAX}`)
|
||
.setStyle(TextInputStyle.Short)
|
||
.setMaxLength(2)
|
||
.setValue(String(row.user_limit ?? 0))
|
||
.setRequired(true),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
/** Modal submissions opened from the panel (M14-T05). */
|
||
export async function handleVoiceModal(interaction) {
|
||
if (interaction.customId === 'voice:rename:modal') {
|
||
await renameChannel(interaction, interaction.fields.getTextInputValue('name'));
|
||
return;
|
||
}
|
||
|
||
if (interaction.customId === 'voice:limit:modal') {
|
||
const raw = interaction.fields.getTextInputValue('limit').trim();
|
||
const limit = Number.parseInt(raw, 10);
|
||
if (!/^\d{1,2}$/.test(raw)) {
|
||
throw new UserFacingError(`Indique un nombre entier entre 0 (illimité) et ${LIMIT_MAX}.`);
|
||
}
|
||
await setChannelLimit(interaction, limit);
|
||
return;
|
||
}
|
||
|
||
log.debug(`Ignored voice modal ${interaction.customId}`);
|
||
}
|