diff --git a/src/core/BotVoiceMixin.mjs b/src/core/BotVoiceMixin.mjs index 463e0dd..e201588 100644 --- a/src/core/BotVoiceMixin.mjs +++ b/src/core/BotVoiceMixin.mjs @@ -189,7 +189,7 @@ const BotVoiceMixin = { } const guild = this.client?.guilds?.get?.(cleanG); - if (!guild) { + if (!guild && this.client?.guilds?.size > 0 && typeof this.client?.guilds?.fetch !== "function") { logger.voice247(`[247] Bot is not currently in guild ${cleanG} — skipping rejoin for ${cleanCh} (setting kept intact)`); return; } diff --git a/src/utils/Helpers247.mjs b/src/utils/Helpers247.mjs index 3ff498c..0874171 100644 --- a/src/utils/Helpers247.mjs +++ b/src/utils/Helpers247.mjs @@ -54,10 +54,12 @@ export function get247ChannelMode(set, channelId) { if (!set?.get) return "off"; const raw = set.get("stay_247"); if (!raw || raw === "none") return "off"; + const target = cleanId(channelId); + if (!target) return "off"; const channels = Array.isArray(raw) - ? raw.map(id => String(id).trim()).filter(Boolean) - : [String(raw).trim()]; - return channels.includes(channelId) ? "on" : "off"; + ? raw.map(id => cleanId(id)).filter(Boolean) + : [cleanId(raw)].filter(Boolean); + return channels.includes(target) ? "on" : "off"; } /** diff --git a/src/voice/gateway/GatewayHandler.mjs b/src/voice/gateway/GatewayHandler.mjs index 8eb4d53..4f781d2 100644 --- a/src/voice/gateway/GatewayHandler.mjs +++ b/src/voice/gateway/GatewayHandler.mjs @@ -242,6 +242,7 @@ class GatewayHandler { this._lastReadyAt = Date.now(); remix._lastGatewayHeartbeat = Date.now(); remix._gatewayConnected = true; + this.rejoinBackoff?.clear?.(); const readyGuilds = payload.d?.guilds; if (Array.isArray(readyGuilds)) { for (const g of readyGuilds) { @@ -277,6 +278,7 @@ class GatewayHandler { this._lastReadyAt = Date.now(); remix._lastGatewayHeartbeat = Date.now(); remix._gatewayConnected = true; + this.rejoinBackoff?.clear?.(); if (remix._hasBooted) { logger.voice247("[Gateway] RESUMED session active — scheduling 24/7 self-healing sweep in 3s..."); @@ -314,9 +316,9 @@ class GatewayHandler { if (payload.t === "VOICE_STATE_UPDATE") { const d = payload.d; - const userId = d?.user_id; - const channelId = d?.channel_id ?? null; - const guildId = d?.guild_id; + const userId = cleanId(d?.user_id ?? d?.userId); + const channelId = cleanId(d?.channel_id ?? d?.channelId) || null; + const guildId = cleanId(d?.guild_id ?? d?.guildId); const isBot = resolveIsBotUser({ userId, member: d?.member, guild: client.guilds?.get?.(guildId), client, botId: client.user?.id }); if (!userId) return; if (channelId) { @@ -324,6 +326,11 @@ class GatewayHandler { } else { remix.voiceCache.updateUser({ guildId, userId, channelId: null, isBot }); } + try { + this._handleVoiceStateUpdate(d); + } catch (e) { + logger.warn("[Gateway] Error in _handleVoiceStateUpdate from raw event:", e?.message); + } } } catch(e) { logger.warn("[Gateway] Raw gateway handler error:", e?.message); } }; @@ -536,8 +543,10 @@ class GatewayHandler { this._processGuildDelete(guildId); }); - client.on(Events.VoiceStateUpdate, async (data) => { - this._handleVoiceStateUpdate(data); + client.on(Events.VoiceStateUpdate, async (oldOrNew, maybeNew) => { + const data = maybeNew ?? oldOrNew; + const extra = maybeNew ? oldOrNew : null; + this._handleVoiceStateUpdate(data, extra); }); client.on(Events.VoiceStatesSync, (data) => { @@ -674,6 +683,18 @@ class GatewayHandler { return; } + /* Ensure backoff cooldowns from previous session/downtime are reset */ + this.rejoinBackoff?.clear?.(); + + /* Wait for gateway to establish connection so voice joins do not immediately time out */ + if (remix._gatewayConnected === false) { + logger.voice247("[BootRecovery] Waiting up to 30s for gateway connection before rejoining 24/7 channels..."); + const startWait = Date.now(); + while (remix._gatewayConnected === false && Date.now() - startWait < 30_000) { + await new Promise(resolve => setTimeout(resolve, 500)); + } + } + try { const lava = remix.lavalink; if (lava?.hasConnectedNode && !lava.hasConnectedNode() && lava.waitForNode) { @@ -696,7 +717,16 @@ class GatewayHandler { const cleanG = cleanId(guildId); const cleanC = cleanId(channelId); - const guild = remix.client?.guilds?.get?.(cleanG); + let guild = remix.client?.guilds?.get?.(cleanG); + if (!guild && typeof remix.client?.guilds?.fetch === "function") { + try { guild = await remix.client.guilds.fetch(cleanG).catch(() => null); } catch (_) {} + } + if (!guild) { + const { channel: chCheck } = await this._resolve247Channel(cleanC); + if (chCheck) { + guild = chCheck.guild ?? { id: cleanG }; + } + } if (!guild) { logger.voice247( `[BootRecovery] Bot is not currently in guild ${cleanG} — skipping channel ${cleanC} (setting kept intact).` @@ -738,7 +768,8 @@ class GatewayHandler { ); continue; } - if (channelObj.type !== 2) { + const isVoice = channelObj.type === 2 || channelObj.type === 13 || channelObj.type === "voice"; + if (!isVoice) { logger.warn( `[BootRecovery] Channel ${channelId} in guild ${guildId} is not a voice channel (type: ${channelObj.type}) — skipping.` ); diff --git a/src/voice/gateway/RejoinBackoff.mjs b/src/voice/gateway/RejoinBackoff.mjs index c6364fb..e2ed0c9 100644 --- a/src/voice/gateway/RejoinBackoff.mjs +++ b/src/voice/gateway/RejoinBackoff.mjs @@ -13,12 +13,12 @@ export class RejoinBackoff { /** * @param {object} [o] - * @param {number} [o.baseMs=120000] - Cool-down after the first failed attempt cycle (doubles each time). + * @param {number} [o.baseMs=30000] - Cool-down after the first failed attempt cycle (doubles each time). * @param {number} [o.maxMs=3600000] - Upper bound for the cool-down. * @param {number} [o.maxEntries=5000] - Safety cap on remembered channels (oldest evicted first). * @param {() => number} [o.now] - Clock (injectable for tests). */ - constructor({ baseMs = 120_000, maxMs = 3_600_000, maxEntries = 5_000, now = Date.now } = {}) { + constructor({ baseMs = 30_000, maxMs = 3_600_000, maxEntries = 5_000, now = Date.now } = {}) { this.baseMs = baseMs; this.maxMs = maxMs; this.maxEntries = maxEntries; @@ -47,6 +47,11 @@ export class RejoinBackoff { this._entries.delete(String(channelId)); } + /** Clear all backoff entries (used on gateway reconnection). */ + clear() { + this._entries.clear(); + } + /** @returns {number} Milliseconds until the watchdog may try this channel again (0 = go ahead). */ remainingMs(channelId) { const e = this._entries.get(String(channelId)); diff --git a/src/voice/gateway/RejoinManager.mjs b/src/voice/gateway/RejoinManager.mjs index 27d405f..6116e48 100644 --- a/src/voice/gateway/RejoinManager.mjs +++ b/src/voice/gateway/RejoinManager.mjs @@ -56,6 +56,8 @@ const RejoinManager = { || errMsg.includes("internal error") || errMsg.includes("ETIMEDOUT") || errMsg.includes("ECONNRESET") + || errMsg.includes("Gateway") + || this.remix?._gatewayConnected === false ); if (isTransientError && attempt < maxRetries) { @@ -97,7 +99,10 @@ const RejoinManager = { const cleanGuildId = cleanId(guildId); const cleanChannelId = cleanId(channelId); - const guild = remix.client?.guilds?.get?.(cleanGuildId); + let guild = remix.client?.guilds?.get?.(cleanGuildId); + if (!guild && typeof remix.client?.guilds?.fetch === "function") { + try { guild = await remix.client.guilds.fetch(cleanGuildId).catch(() => null); } catch (_) {} + } if (!guild) { logger.voice247(`[Rejoin] Bot is not currently in guild ${cleanGuildId} — skipping ${cleanChannelId} (setting kept intact).`); return; @@ -168,7 +173,10 @@ const RejoinManager = { } } else { this._rejoinAttempts.delete(cleanChannelId); - this.rejoinBackoff?.recordFailure?.(cleanChannelId); + /* Only apply backoff cool-down if failure was not caused by a gateway outage */ + if (this.remix?._gatewayConnected !== false) { + this.rejoinBackoff?.recordFailure?.(cleanChannelId); + } } return player; } finally { diff --git a/src/voice/gateway/VoiceStateRouting.mjs b/src/voice/gateway/VoiceStateRouting.mjs index c59afb9..b601b2b 100644 --- a/src/voice/gateway/VoiceStateRouting.mjs +++ b/src/voice/gateway/VoiceStateRouting.mjs @@ -28,38 +28,47 @@ const VoiceStateRouting = { * @returns {Promise} * @private */ - async _handleVoiceStateUpdate(data) { + async _handleVoiceStateUpdate(data, extraState = null) { const { remix } = this; const client = remix.client; - const userId = data?.user_id; + /* Normalize field names across raw gateway payloads and library VoiceState objects */ + const rawState = data; + const userId = cleanId(rawState?.user_id ?? rawState?.userId ?? rawState?.id ?? rawState?.member?.user?.id ?? rawState?.member?.id); if (!userId) return; - const newChannelId = data?.channel_id ?? null; - const vsuGuildId = data?.guild_id; - const isBot = resolveIsBotUser({ + const newChannelId = cleanId(rawState?.channel_id ?? rawState?.channelId ?? rawState?.channel?.id) || null; + const vsuGuildId = cleanId(rawState?.guild_id ?? rawState?.guildId ?? rawState?.guild?.id); + + const botId = cleanId(client.user?.id ?? remix.botId ?? remix.config?.botId ?? client.id ?? ""); + const isBotUser = Boolean(botId && userId === botId); + const isBot = isBotUser || resolveIsBotUser({ userId, - member: data?.member, + member: rawState?.member, guild: client.guilds?.get?.(vsuGuildId), client, - botId: client.user?.id, + botId, }); - const prevEntry = this.findPrevVoiceStateEntry(userId, vsuGuildId); const prev = prevEntry.value; const prevSameGuild = prev && cleanId(prev.guildId ?? "") === cleanId(vsuGuildId ?? ""); - const oldChannelId = prevSameGuild ? (prev?.channelId ?? null) : null; - - - this._updatePreviousStates(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prevEntry, prev); - this._updateVoiceStateCache(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prev); + let oldChannelId = prevSameGuild ? (prev?.channelId ?? null) : null; + if (!oldChannelId && extraState) { + oldChannelId = cleanId(extraState?.channel_id ?? extraState?.channelId ?? extraState?.channel?.id) || null; + } const { player, playerGuildId, homeChannelId } = this._findAffectedPlayer(vsuGuildId, oldChannelId, newChannelId); - const isBotUser = isBot === true && userId === client.user?.id; + /* If this is the bot disconnecting, but oldChannelId was not tracked in _prevVoiceState, resolve it from the player */ + if (!oldChannelId && isBotUser && player) { + oldChannelId = cleanId(player._channelId ?? player._home247Channel ?? "") || null; + } + + this._updatePreviousStates(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prevEntry, prev); + this._updateVoiceStateCache(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prev); /* Handle server-mute (admin / community mute) on the bot */ if (isBotUser && player) { @@ -217,6 +226,14 @@ const VoiceStateRouting = { } } + if (guildId) { + const cleanG = cleanId(guildId); + const player = [...remix.players.playerMap.values()].find(p => !p._destroyed && cleanId(p._guildId) === cleanG); + if (player) { + return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel }; + } + } + return { player: null, playerGuildId: null, homeChannelId: null }; }, diff --git a/src/voice/gateway/Watchdog247.mjs b/src/voice/gateway/Watchdog247.mjs index c3df67c..4ce5b94 100644 --- a/src/voice/gateway/Watchdog247.mjs +++ b/src/voice/gateway/Watchdog247.mjs @@ -150,6 +150,10 @@ const Watchdog247 = { logger.voice247("[Watchdog247] Boot recovery in progress — skipping sweep."); return; } + if (remix._gatewayConnected === false) { + logger.voice247("[Watchdog247] Gateway is currently disconnected — deferring sweep until connection is restored."); + return; + } let healthy = 0, healed = 0, pruned = 0, skipped = 0; const savedChannels = []; @@ -170,9 +174,19 @@ const Watchdog247 = { const cleanG = cleanId(guildId); const cleanCh = cleanId(channelId); - const guild = remix.client?.guilds?.get?.(cleanG); + let guild = remix.client?.guilds?.get?.(cleanG); + if (!guild && typeof remix.client?.guilds?.fetch === "function") { + try { guild = await remix.client.guilds.fetch(cleanG).catch(() => null); } catch (_) {} + } if (!guild) { - // Bot is not in this guild — keep 24/7 setting intact for future invite, but skip sweep + /* If channel itself resolves via REST, the guild is accessible to the bot */ + const { channel: chCheck } = await this._resolve247Channel(cleanCh); + if (chCheck) { + guild = chCheck.guild ?? { id: cleanG }; + } + } + if (!guild) { + /* Bot is not in this guild — keep 24/7 setting intact for future invite, but skip sweep */ skipped++; continue; } @@ -219,11 +233,12 @@ const Watchdog247 = { skipped++; continue; } - if (channel && channel.type !== 2) { + const isVoice = channel.type === 2 || channel.type === 13 || channel.type === "voice"; + if (channel && !isVoice) { if (this._prune247Channel(guildId, channelId)) { pruned++; remix.cancel247Rejoin?.(channelId); - logger.voice247(`[Watchdog247] ${channelId} is not a voice channel anymore — pruned.`); + logger.voice247(`[Watchdog247] ${channelId} is not a voice channel anymore (type: ${channel.type}) — pruned.`); } continue; }