feat(voice): take back the generated channels the database forgot

A voice channel outlives the process that made it. A restored backup, a
wiped `data/` folder or a redeployment shipping a fresh database all leave
real channels behind that nothing manages any more: they are never cleaned
up, and their owner can no longer rename or lock them.

At startup the bot now reclaims the channels sitting in a trigger's own
category and named after its template — a channel created by hand is never
touched. Those still in use go back to whoever is inside; the empty ones are
leftovers and are removed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
nocodeandClaude Opus 5 committed 2026-09-23 22:31:42 +02:00
1 parent 52a5c50692
commit a61f446e44
2 files changed
+95 -1

No files matched your search

+10 -1
View File
@@ -2,7 +2,11 @@ import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
import { startPollScheduler } from '../services/polls/poll-service.js';
import { startBotStatusRotation } from '../services/status/bot-status-service.js';
import { startVoiceJanitor, sweepVoiceChannels } from '../services/voice/voice-service.js';
import {
adoptOrphanVoiceChannels,
startVoiceJanitor,
sweepVoiceChannels,
} from '../services/voice/voice-service.js';
const log = createLogger('discord');
@@ -11,6 +15,11 @@ export const once = true;
export async function execute(client) {
startPollScheduler(client);
// Channels outlive the process: take back the ones the database forgot before
// the sweep decides they are not ours.
await adoptOrphanVoiceChannels(client).catch((error) =>
log.warn('Could not recover the orphan voice channels', error),
);
await sweepVoiceChannels(client);
startVoiceJanitor(client);
startBotStatusRotation(client);
+85
View File
@@ -9,6 +9,7 @@ import {
} from 'discord.js';
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { readSetting } from '../../config/guild-settings.js';
import { PermissionDeniedError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { getAccessLevel } from '../../core/permissions.js';
@@ -525,6 +526,90 @@ export async function cleanupVoiceChannel(guild, channelId, { graceMs = EMPTY_GR
* (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.
*/
/** Builds a matcher from a trigger template, `{user}` standing for any name. */
function templateMatcher(template) {
const escaped = String(template ?? DEFAULT_TEMPLATE).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(`^${escaped.replace('\\{user\\}', '.+')}$`, 'u');
}
/**
* Takes back the generated channels the database no longer knows about (M14-T09).
*
* A channel outlives the process that made it: a restored backup, a wiped
* `data/` folder or a redeployment that ships a fresh database all leave real
* channels behind that nothing manages any more — they never get cleaned up and
* their owner can no longer rename or lock them.
*
* Only channels sitting in a trigger's own category and named after its
* template are taken, so a channel created by hand is never touched.
*/
export async function adoptOrphanVoiceChannels(client) {
let adopted = 0;
let removed = 0;
for (const guild of client.guilds.cache.values()) {
if (!readSetting('voice.adoptOrphans', guild.id)) continue;
let triggers = [];
try {
triggers = getVoiceTriggers(guild.id).filter((trigger) => trigger.enabled);
} catch (error) {
log.warn('Could not read the voice triggers', error);
continue;
}
if (triggers.length === 0) continue;
await guild.channels.fetch().catch(() => null);
for (const trigger of triggers) {
const triggerChannel = guild.channels.cache.get(trigger.triggerId);
const categoryId = trigger.categoryId || triggerChannel?.parentId;
if (!categoryId) continue;
const matches = templateMatcher(trigger.template);
for (const channel of guild.channels.cache.values()) {
if (channel.type !== ChannelType.GuildVoice) continue;
if (channel.parentId !== categoryId) continue;
if (channel.id === trigger.triggerId) continue;
if (getVoiceChannel(channel.id)) continue;
if (!matches.test(channel.name)) continue;
// Nobody left in it: it is a leftover, not something to hand back.
if (channel.members.size === 0) {
if (await deleteVoiceChannel(channel, 'Salon vocal temporaire orphelin et vide')) {
removed += 1;
logEvent({ guildId: guild.id, type: 'voice.orphan.removed', payload: { channelId: channel.id } });
}
continue;
}
// Still in use: give it back to whoever is in it, oldest member first.
const owner = channel.members.filter((member) => !member.user.bot).first() ?? channel.members.first();
addVoiceChannel({
channelId: channel.id,
guildId: guild.id,
ownerId: owner.id,
triggerId: trigger.triggerId,
name: channel.name,
userLimit: channel.userLimit ?? 0,
});
adopted += 1;
logEvent({
guildId: guild.id,
type: 'voice.orphan.adopted',
payload: { channelId: channel.id, ownerId: owner.id },
});
}
}
}
if (adopted > 0 || removed > 0) {
log.info('Recovered orphan voice channels', { adopted, removed });
}
return { adopted, removed };
}
export async function sweepVoiceChannels(client) {
for (const guild of client.guilds.cache.values()) {
let rows = [];