This commit is contained in:
NoLogicAlan committed 2026-05-14 21:24:29 +03:00
1 parent 2c9a124d47
commit 7cf97b0aed
4 files changed
+204 -209

No files matched your search

+82 -102
View File
@@ -23,7 +23,7 @@ export class GatewayHandler {
const timers = remix.config.timers ?? {};
this.T = {
aloneCheckDebounce: timers.aloneCheckDebounce ?? 500,
rejoin247Delay: timers.rejoin247Delay ?? 3_000,
rejoin247Delay: timers.rejoin247Delay ?? 2_000,
};
// ── Presence rotation config ─────────────────────────────────────────────
@@ -57,7 +57,7 @@ export class GatewayHandler {
/** @type {Map<string, {guild, timer}>} guildId → deferred cleanup data */
this._deferredGuildDeletes = new Map();
/** @type {number} How long to defer GuildDelete processing during startup (ms) */
this._startupDeleteGraceMs = 15_000;
this._startupDeleteGraceMs = 10_000;
/** @type {boolean} Whether we're still in the startup grace period */
this._inStartupGrace = true;
}
@@ -587,10 +587,7 @@ export class GatewayHandler {
if (deferred) {
clearTimeout(deferred.timer);
this._deferredGuildDeletes.delete(guildId);
logger.guild(
`[GuildDelete] Cancelled deferred cleanup for server ${guildId} — ` +
`guild came back (GuildCreate received during grace period).`
);
// Silently cancel — no need to log every guild that comes back during startup
}
// Part 1: Voice state population
@@ -719,18 +716,12 @@ export class GatewayHandler {
// come back via GUILD_CREATE moments later. Defer cleanup during
// the startup grace period; if GuildCreate arrives first, cancel.
if (this._inStartupGrace) {
logger.guild(
`[GuildDelete] Deferring cleanup for server ${guildId} ` +
`(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).`
);
// Cancel any existing deferred timer for this guild
// Silently buffer — log one summary after all deferrals are collected
const existing = this._deferredGuildDeletes.get(guildId);
if (existing) clearTimeout(existing.timer);
const timer = setTimeout(() => {
this._deferredGuildDeletes.delete(guildId);
// Grace period expired without GuildCreate — this guild is really gone
logger.guild(`[GuildDelete] Confirmed removal from server ${guildId} — cleaning up.`);
this._processGuildDelete(guildId);
}, this._startupDeleteGraceMs);
@@ -1130,25 +1121,26 @@ export class GatewayHandler {
// End the startup grace period after the configured delay.
// Any deferred GuildDelete events that weren't cancelled by a GuildCreate
// will be processed at this point.
// are processed in one batch here.
setTimeout(() => {
this._inStartupGrace = false;
const pending = this._deferredGuildDeletes.size;
if (pending > 0) {
logger.guild(
`[GuildDelete] Startup grace period ended. ` +
`${pending} deferred deletion(s) will be processed by their timers.`
);
} else {
logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`);
const pending = this._deferredGuildDeletes;
if (pending.size > 0) {
const ids = [...pending.keys()];
// Clear all individual deferred timers — we'll process them all at once
for (const [, data] of pending) {
clearTimeout(data.timer);
}
pending.clear();
this._processGuildDelete(ids);
}
}, this._startupDeleteGraceMs);
// ── Boot 24/7 auto-rejoin ────────────────────────────────────────────────
// After a reboot/crash, automatically rejoin all voice channels that have
// 24/7 mode enabled (stay_247 setting with mode "on" or "auto").
// Delayed slightly to let the gateway settle and Moonlink initialise.
setTimeout(() => this.rejoin247Channels(), 5_000);
// Minimal delay — Moonlink is already ready by onReady time.
setTimeout(() => this.rejoin247Channels(), 2_000);
}
/**
@@ -1208,7 +1200,8 @@ export class GatewayHandler {
// Verify the channel still exists
const ch = remix.client?.channels?.get?.(channelId);
if (!ch) {
logger.voice247(`[BootRecovery] Channel ${channelId} no longer exists — skipping`);
logger.voice247(`[BootRecovery] Channel ${channelId} no longer exists — removing 24/7 state`);
this._remove247ForChannel(guildId, channelId);
return;
}
@@ -1216,114 +1209,101 @@ export class GatewayHandler {
await remix._spawnPlayer(guildId, channelId);
logger.voice247(`[BootRecovery] Successfully rejoined 24/7 channel ${channelId}`);
} catch (e) {
const is401 = e?.message?.includes("401") || e?.message?.includes("Unauthorized");
if (is401) {
logger.warn(
`[BootRecovery] 401 error rejoining 24/7 channel ${channelId} (guild ${guildId}) — ` +
`auto-removing 24/7 state for this channel`
);
const msg = e?.message ?? "";
// 401 Unauthorized means the bot lost access to the channel (kicked,
// lost permissions, or channel deleted). Auto-remove the 24/7 state
// so we don't keep retrying on every reboot.
if (msg.includes("401") || msg.includes("Unauthorized") ||
msg.includes("NOT_LOGGED_IN") || msg.includes("Forbidden")) {
logger.warn(`[BootRecovery] 401 for channel ${channelId} — bot lacks access, removing 24/7 state`);
this._remove247ForChannel(guildId, channelId);
} else {
logger.warn(`[BootRecovery] Failed to rejoin 24/7 channel ${channelId}: ${e.message}`);
logger.warn(`[BootRecovery] Failed to rejoin 24/7 channel ${channelId}: ${msg}`);
}
}
}, delay);
}
}
// ── 401 auto-cleanup for boot rejoin ──────────────────────────────────────
/**
* Remove the 24/7 state for a channel when a 401 error occurs during
* boot rejoin. This prevents the bot from repeatedly trying to rejoin
* a channel that it no longer has access to (e.g. bot was removed from
* the server, channel was deleted, or permissions were revoked).
* Remove 24/7 state for a specific channel when the bot can't access it.
* This prevents repeated 401 failures on every reboot.
*
* @param {string} guildId
* @param {string} channelId
* @param {string} channelId Clean (digits-only) channel ID
*/
_remove247ForChannel(guildId, channelId) {
const { remix } = this;
const settings = remix.settingsMgr;
if (!settings?.guilds) return;
const set = remix.settingsMgr?.getServer?.(guildId);
if (!set) return;
const serverSettings = settings.guilds.get(guildId);
if (!serverSettings) return;
const cleanChannelId = String(channelId).replace(/\D/g, "");
// Get the current stay_247 channels
const raw = serverSettings.get("stay_247");
const raw = set.get("stay_247");
if (!raw || raw === "none") return;
const rawArr = Array.isArray(raw) ? raw : [raw];
const currentSet = new Set(
rawArr.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15)
);
const channels = Array.isArray(raw)
? new Set(raw.map(id => String(id).replace(/\D/g, "")))
: new Set([String(raw).replace(/\D/g, "")]);
const cleanCh = String(channelId).replace(/\D/g, "");
// Remove the channel from the set
if (!currentSet.has(cleanChannelId)) return; // already removed
currentSet.delete(cleanChannelId);
if (!channels.has(cleanCh)) return;
// Update stay_247 setting
if (currentSet.size === 0) {
serverSettings.set("stay_247", "none");
} else {
serverSettings.set("stay_247", [...currentSet]);
}
channels.delete(cleanCh);
// Use the shared helper to remove the per-channel mode entry and update the guild-wide mode
remove247ChannelMode(set, cleanCh, channels);
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
// Remove the per-channel mode
remove247ChannelMode(serverSettings, cleanChannelId, currentSet);
// Remove the playerMap entry if present
const existingPlayer = remix.players.playerMap.get(cleanChannelId);
if (existingPlayer) {
remix.players.playerMap.delete(cleanChannelId);
try { existingPlayer.leave().catch(() => {}); } catch (_) {}
try { existingPlayer.destroy(); } catch (_) {}
}
logger.voice247(
`[BootRecovery] Auto-removed 24/7 for channel ${cleanChannelId} ` +
`in guild ${guildId} due to 401 error`
);
logger.voice247(`[BootRecovery] Removed 24/7 for channel ${cleanCh} in guild ${guildId} (inaccessible)`);
}
// ── GuildDelete cleanup (extracted for deferred processing) ────────────────
/**
* Perform the actual cleanup for a guild that the bot was removed from.
* Extracted from the GuildDelete handler so it can be called after the
* startup grace period expires.
* @param {string} guildId
* Perform the actual cleanup for guild(s) that the bot was removed from.
* Accepts a single guildId (string) or an array of guildIds for batch
* processing (used when the startup grace period expires with multiple
* deferred deletes). Logs ONE summary line with all cleaned guild IDs.
* @param {string|string[]} guildIds
*/
_processGuildDelete(guildId) {
_processGuildDelete(guildIds) {
const ids = Array.isArray(guildIds) ? guildIds : [guildIds];
const { remix } = this;
const cleanGuildId = String(guildId).replace(/\D/g, "");
const cleanedIds = [];
let totalDestroyedPlayers = 0;
for (const [channelId, player] of remix.players.playerMap) {
if (String(player._guildId ?? "").replace(/\D/g, "") === cleanGuildId) {
remix.players.playerMap.delete(channelId);
try { player.leave().catch(() => {}); } catch (_) {}
try { player.destroy(); } catch (_) {}
logger.guild(`[GuildDelete] Destroyed player for channel ${channelId}.`);
for (const guildId of ids) {
const cleanGuildId = String(guildId).replace(/\D/g, "");
let destroyedPlayers = 0;
for (const [channelId, player] of remix.players.playerMap) {
if (String(player._guildId ?? "").replace(/\D/g, "") === cleanGuildId) {
remix.players.playerMap.delete(channelId);
try { player.leave().catch(() => {}); } catch (_) {}
try { player.destroy(); } catch (_) {}
destroyedPlayers++;
}
}
for (const [userId, info] of [...remix.observedVoiceUsers]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceUsers.delete(userId);
}
for (const [userId, info] of [...remix.observedVoiceBots]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceBots.delete(userId);
}
for (const [stateKey, info] of [...this._prevVoiceState]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId)
this._prevVoiceState.delete(stateKey);
}
remix.settingsMgr.removeServer(guildId);
remix._announcementChannelCache.delete(guildId);
cleanedIds.push(guildId);
totalDestroyedPlayers += destroyedPlayers;
}
for (const [userId, info] of [...remix.observedVoiceUsers]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceUsers.delete(userId);
if (cleanedIds.length > 0) {
const extra = totalDestroyedPlayers > 0 ? ` (${totalDestroyedPlayers} player(s) destroyed)` : "";
logger.guild(`[GuildDelete] Cleaned up ${cleanedIds.length} server(s): ${cleanedIds.join(", ")}${extra}`);
}
for (const [userId, info] of [...remix.observedVoiceBots]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceBots.delete(userId);
}
for (const [stateKey, info] of [...this._prevVoiceState]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId)
this._prevVoiceState.delete(stateKey);
}
remix.settingsMgr.removeServer(guildId);
remix._announcementChannelCache.delete(guildId);
logger.guild(`[GuildDelete] Cleanup complete for server ${guildId}.`);
}
}
+8 -6
View File
@@ -1003,7 +1003,7 @@ export default class Player extends EventEmitter {
if (this._destroyed) return;
if (this._isJoining) {
logger.player(`[Player] Busy joining. Ignoring: ${channelId}`);
logger.mediaplayer(`[Player] Busy joining. Ignoring: ${channelId}`);
return;
}
if (this.connection && this._channelId === channelId) {
@@ -1078,8 +1078,10 @@ export default class Player extends EventEmitter {
try { this._revoice.deleteConnection(this._channelId); } catch (_) {}
}
// FluxerRevoice.join() already adds a _globalJoinDelay (500ms) before
// the actual join, so no additional sleep is needed here.
// Wait to give the Fluxer gateway time to process the voice state
// leave before we join a new channel. FluxerRevoice adds its own
// _globalJoinDelay before the actual join, so 500ms here is enough.
await Utils.sleep(500);
this.connection = null;
this._mediaPlayer = null;
}
@@ -1254,7 +1256,7 @@ export default class Player extends EventEmitter {
const playerReady = await this._ensureMediaPlayer();
if (!playerReady) {
logger.mediaplayer("[Player] First MediaPlayer attempt failed, retrying after delay...");
await Utils.sleep(500);
await Utils.sleep(1500);
if (this._destroyed || this.leaving) throw new Error("Player destroyed during MediaPlayer retry");
const roomAlive = this.connection?.room?.isConnected ?? false;
if (!roomAlive) {
@@ -1278,7 +1280,7 @@ export default class Player extends EventEmitter {
if (this.queue.isEmpty() && !this.queue.getCurrent()) {
this._startInactivityTimer();
}
}, 1500);
}, 3000);
}
} catch (e) {
@@ -1287,7 +1289,7 @@ export default class Player extends EventEmitter {
if (e.message?.includes("401") || e.message?.includes("Unauthorized")) {
// Track 401 errors for logging purposes
logger.warn(`[Player] Join failed with 401 Unauthorized for guild ${this._guildId}`);
logger.warn(`[Player] Join failed with 401 Unauthorized for guild ${this._guildId ?? this._resolveGuildId() ?? 'unknown'}`);
}
if (this.connection) {
+93 -40
View File
@@ -31,24 +31,41 @@ import { Room, RoomEvent, ConnectionState } from "@livekit/rtc-node";
import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice";
import { logger } from "./Logger.mjs";
// ── Suppress verbose LiveKit SDK logging ──────────────────────────────────
// @livekit/rtc-node removed the `setLogLevel` export in newer versions,
// causing a SyntaxError crash when importing it. The SDK uses console.debug
// for verbose trace-level logs. Monkey-patch console.debug to filter out
// noisy LiveKit messages — no env vars needed.
const _origConsoleDebug = console.debug;
console.debug = function(...args) {
const msg = typeof args[0] === 'string' ? args[0] : (args[0]?.toString?.() ?? '');
if (typeof msg === 'string' && (
msg.includes('[LiveKit') ||
msg.includes('livekit') ||
msg.includes('RTCKit') ||
msg.includes('SignalClient') ||
msg.includes('Room connect') ||
msg.includes('ICE') ||
msg.includes('DTLS')
)) return;
return _origConsoleDebug.apply(console, args);
// Suppress LiveKit SDK's verbose pino/JSON logs (lk-rtc, [voice LiveKitRtc]).
// setLogLevel was removed in newer @livekit/rtc-node versions.
// The LiveKit SDK uses pino which writes JSON directly to process.stdout.write,
// bypassing console.log entirely. We must patch BOTH to fully suppress noise.
// This works without env vars and across all versions.
// ── Patch 1: console.log ──────────────────────────────────────────────────
// Catches [voice LiveKitRtc] lines and any SDK logs that go through console.
const _origConsoleLog = console.log;
console.log = function (...args) {
const msg = args.length > 0 ? String(args[0]) : '';
if (msg.includes('lk-rtc') || msg.includes('[voice LiveKitRtc]') ||
msg.includes('Connect callback received') || msg.includes('connected to room') ||
msg.includes('Room disconnected') || msg.includes('emitting disconnect') ||
msg.includes('room reconnecting') || msg.includes('SignalResumed')) {
return;
}
return _origConsoleLog.apply(console, args);
};
// ── Patch 2: process.stdout.write ─────────────────────────────────────────
// Catches pino JSON logs ({"level":20,"name":"lk-rtc",...}) that bypass
// console.log entirely. pino writes NDJSON directly to stdout.
const _origStdoutWrite = process.stdout.write.bind(process.stdout);
process.stdout.write = function (chunk, encoding, callback) {
if (typeof chunk === 'string') {
if (chunk.includes('"lk-rtc"') || chunk.includes('[voice LiveKitRtc]')) {
// Swallow the noisy LiveKit SDK output.
// If callback was provided, call it immediately so the caller
// doesn't hang waiting for the write to "complete".
if (typeof callback === 'function') callback();
return true;
}
}
return _origStdoutWrite(chunk, encoding, callback);
};
// ConnectionState enum values for reference:
@@ -490,7 +507,7 @@ export class FluxerRevoice extends EventEmitter {
const elapsed = Date.now() - lastJoin;
if (elapsed < this._guildMinJoinInterval) {
const extraWait = this._guildMinJoinInterval - elapsed;
logger.player(
logger.mediaplayer(
`[FluxerRevoice] Guild ${guildId} was joined ${elapsed}ms ago — ` +
`waiting additional ${extraWait}ms to avoid 401 race`
);
@@ -507,7 +524,7 @@ export class FluxerRevoice extends EventEmitter {
`aborting join for channel ${channelId} to avoid guaranteed failure. `
);
}
logger.player(
logger.mediaplayer(
`[FluxerRevoice] Guild ${guildId} has 401 cooldown — ` +
`waiting ${Math.round(cooldownRemaining / 1000)}s before attempting join`
);
@@ -532,18 +549,16 @@ export class FluxerRevoice extends EventEmitter {
// up fully and rejoin instead of returning a dead connection that will
// fail with "LiveKit disconnected (connectionState: 0)".
if (existing && !existing._destroyed && existing.room && existing.room.isConnected) {
logger.player(`[FluxerRevoice] Already connected to ${channelId}, returning existing connection`);
logger.mediaplayer(`[FluxerRevoice] Already connected to ${channelId}, returning existing connection`);
return existing;
}
logger.player(
`[FluxerRevoice] Stale connection for ${channelId} ` +
`(isConnected: ${existing?.room?.isConnected ?? false}, ` +
`destroyed: ${existing?._destroyed ?? true}) — cleaning up and rejoining`
logger.mediaplayer(
`[FluxerRevoice] Stale connection for ${channelId} — cleaning up and rejoining`
);
await this._destroyStaleConnection(channelId, existing);
}
logger.player(`[FluxerRevoice] Joining channel ${channelId} via Fluxer gateway...`);
logger.mediaplayer(`[FluxerRevoice] Joining channel ${channelId} via Fluxer gateway...`);
// Fetch the channel object from the client cache (or REST)
let channel = this.client.channels?.get?.(channelId);
@@ -561,34 +576,48 @@ export class FluxerRevoice extends EventEmitter {
// Resolve the guild ID for this channel (used for guild-scoped leave signals)
const channelGuildId = guildId ?? channel?.guildId ?? channel?.guild?.id ?? null;
// Use @fluxerjs/voice to join the channel via the Fluxer gateway.
// Use the official @fluxerjs/voice API: voiceManager.join(channel)
// This handles the VOICE_STATE_UPDATE → VOICE_SERVER_UPDATE flow
// and creates a LiveKit connection with the returned credentials.
// Per Fluxer docs: voiceManager.join(channel) is the recommended API.
let nativeConnection;
try {
nativeConnection = await joinVoiceChannel(this.client, channel);
const vm = getVoiceManager(this.client);
if (vm && typeof vm.join === "function") {
// Official API — voiceManager.join(channel)
nativeConnection = await vm.join(channel);
} else {
// Fallback for older @fluxerjs/voice versions that don't have vm.join()
nativeConnection = await joinVoiceChannel(this.client, channel);
}
} catch (e) {
// If the error is 401 Unauthorized, set a cooldown for this guild
// so subsequent join attempts wait longer before retrying.
if (e.message?.includes("401") || e.message?.includes("Unauthorized")) {
// If the error is 401 Unauthorized (or FluxerAPIError equivalent),
// set a cooldown for this guild so subsequent join attempts wait longer.
// Fluxer uses FluxerAPIError / FluxerError for API errors, but the
// underlying LiveKit/gateway error may still surface as "401" or
// "Unauthorized" in the message. Check both patterns.
const errMsg = e?.message ?? String(e ?? "");
const is401 = errMsg.includes("401") || errMsg.includes("Unauthorized") ||
errMsg.includes("NOT_LOGGED_IN") || errMsg.includes("Forbidden");
if (is401) {
const gId = channelGuildId ?? this._resolveGuildForChannel(channelId);
if (gId) {
// Set 15-second cooldown for this guild to prevent rapid 401 retries
this._guild401Cooldown.set(gId, Date.now() + 15_000);
logger.warn(
`[FluxerRevoice] 401 error for channel ${channelId} — ` +
`setting 15s cooldown for guild ${gId}`
`[FluxerRevoice] 401/auth error for channel ${channelId} — ` +
`setting 15s cooldown for guild ${gId}: ${errMsg}`
);
}
}
throw new Error(`Fluxer voice join failed for ${channelId}: ${e.message}`);
throw new Error(`Fluxer voice join failed for ${channelId}: ${errMsg}`);
}
if (!nativeConnection) {
throw new Error(`Fluxer voice join returned null for ${channelId}`);
}
logger.player(`[FluxerRevoice] Gateway join successful, extracting LiveKit room...`);
logger.mediaplayer(`[FluxerRevoice] Gateway join successful, extracting LiveKit room...`);
// The @fluxerjs/voice connection wraps a LiveKit Room.
// Extract it so we can use it with revoice.js's MediaPlayer.
@@ -597,7 +626,7 @@ export class FluxerRevoice extends EventEmitter {
// Try to get the LiveKit Room from the native connection
if (nativeConnection.room) {
room = nativeConnection.room;
logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`);
logger.mediaplayer(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`);
}
// (non-LiveKit) which we don't support for music playback.
@@ -662,7 +691,7 @@ export class FluxerRevoice extends EventEmitter {
throw new Error(`LiveKit room in disconnected state: ${stateLabel(finalCS)}`);
}
logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`);
logger.mediaplayer(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`);
// Record the successful join time for this guild so future joins
// can enforce the minimum interval and avoid 401 races.
@@ -689,7 +718,7 @@ export class FluxerRevoice extends EventEmitter {
room.on(RoomEvent.Disconnected, (reason) => {
const isIntentional = this._intentionalDisconnects.has(String(channelId));
const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected");
logger.player(`[FluxerRevoice] Room disconnected: ${reasonLabel}${isIntentional ? " (bot-initiated, recovery suppressed)" : ""}`);
logger.mediaplayer(`[FluxerRevoice] Room disconnected: ${reasonLabel}${isIntentional ? " (bot-initiated, recovery suppressed)" : ""}`);
this._intentionalDisconnects.delete(String(channelId));
connection._connected = false;
connection._destroyed = true;
@@ -714,11 +743,11 @@ export class FluxerRevoice extends EventEmitter {
});
room.on(RoomEvent.Reconnecting, () => {
logger.player("[FluxerRevoice] Room reconnecting...");
logger.mediaplayer("[FluxerRevoice] Room reconnecting...");
});
room.on(RoomEvent.Reconnected, () => {
logger.player("[FluxerRevoice] Room reconnected");
logger.mediaplayer("[FluxerRevoice] Room reconnected");
connection._connected = true;
});
@@ -743,6 +772,30 @@ export class FluxerRevoice extends EventEmitter {
// Track the connection
this.connections.set(channelId, connection);
// ── serverLeave event (official Fluxer reconnection API) ────────────
// Per Fluxer docs: connection.on?.('serverLeave') fires when LiveKit
// disconnects the bot. This is the recommended way to handle reconnects.
if (typeof nativeConnection?.on === "function") {
try {
nativeConnection.on("serverLeave", async () => {
const isIntentional = this._intentionalDisconnects.has(String(channelId));
if (isIntentional) {
logger.mediaplayer(`[FluxerRevoice] serverLeave for ${channelId} — intentional, skipping reconnect`);
return;
}
logger.mediaplayer(`[FluxerRevoice] serverLeave for ${channelId} — server disconnected, will reconnect via 24/7 recovery`);
// Don't reconnect here directly — the VoiceStateUpdate handler
// in GatewayHandler.mjs handles bot disconnect recovery.
// Just mark the connection as disconnected so recovery picks it up.
connection._connected = false;
this.connections.delete(channelId);
connection.emit("disconnect");
});
} catch (_) {
// nativeConnection.on may not be available in all versions
}
}
// Auto-leave when room empties (if requested)
if (_leaveIfEmpty) {
connection.on("userleave", () => {