(hotfix)cleaning up

This commit is contained in:
NoLogicAlan committed 2026-05-14 20:08:10 +03:00
1 parent 3c14f04756
commit 7096602d9c
9 files changed
+43 -1096

No files matched your search

+4 -4
View File
@@ -273,7 +273,7 @@ export async function run(msg) {
for (const emoji of allEmojisForPage(p)) { for (const emoji of allEmojisForPage(p)) {
try { try {
await menuMsg.message.react(emoji); await menuMsg.message.react(emoji);
await Utils.sleep(150); await Utils.sleep(50);
} catch (_) {} } catch (_) {}
} }
}; };
@@ -389,7 +389,7 @@ export async function run(msg) {
.setDescription(this.t(msg, "responses.filter.nothingPlaying")) .setDescription(this.t(msg, "responses.filter.nothingPlaying"))
; ;
await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {}); await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {});
await Utils.sleep(2000); await Utils.sleep(1000);
await menuMsg.edit({ await menuMsg.edit({
embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, null)] embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, null)]
}).catch(() => {}); }).catch(() => {});
@@ -430,7 +430,7 @@ export async function run(msg) {
) )
; ;
await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {}); await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {});
await Utils.sleep(3000); await Utils.sleep(1500);
await menuMsg.edit({ await menuMsg.edit({
embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, track)] embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, track)]
}).catch(() => {}); }).catch(() => {});
@@ -462,7 +462,7 @@ export async function run(msg) {
; ;
await menuMsg.edit({ embeds: [confirmEmbed] }).catch(() => {}); await menuMsg.edit({ embeds: [confirmEmbed] }).catch(() => {});
await Utils.sleep(2500); await Utils.sleep(1200);
// Restore picker (session stays open) // Restore picker (session stays open)
if (!settled) { if (!settled) {
+1 -1
View File
@@ -151,7 +151,7 @@ export async function run(msg) {
for (const control of row) { for (const control of row) {
try { try {
await message.message.react(control.emoji); await message.message.react(control.emoji);
await Utils.sleep(200); await Utils.sleep(50);
} catch (_) {} } catch (_) {}
} }
} }
+2 -6
View File
@@ -117,7 +117,7 @@
"mediaplayer": true, "mediaplayer": true,
"commands": true, "commands": true,
"guild": true, "guild": true,
"recovery": true, "recovery": false,
"settings": true, "settings": true,
"worker": true, "worker": true,
"moonlink": true, "moonlink": true,
@@ -134,10 +134,6 @@
"playerUpdateInterval": 5000, "playerUpdateInterval": 5000,
"searchSessionTimeout": 30000, "searchSessionTimeout": 30000,
"playerSessionTimeout": 300000, "playerSessionTimeout": 300000,
"intentionalLeaveTTL": 10000, "intentionalLeaveTTL": 10000
"recoveryStaggerMs": 2000,
"recoveryConcurrency": 2,
"maxTransientRetries": 5,
"retryBaseDelay": 15000
} }
} }
+2 -57
View File
@@ -13,7 +13,6 @@ import { FluxerRevoice } from "./src/constants/FluxerRevoice.mjs";
import { MoonlinkManager } from "./src/MoonlinkManager.mjs"; import { MoonlinkManager } from "./src/MoonlinkManager.mjs";
import { Dashboard } from "./src/dashboard/Dashboard.mjs"; import { Dashboard } from "./src/dashboard/Dashboard.mjs";
import { Locale } from "./src/constants/Locale.mjs"; import { Locale } from "./src/constants/Locale.mjs";
import { RecoveryManager } from "./src/RecoveryManager.mjs";
import { GatewayHandler } from "./src/GatewayHandler.mjs"; import { GatewayHandler } from "./src/GatewayHandler.mjs";
import { LastFmManager } from "./src/LastFmManager.mjs"; import { LastFmManager } from "./src/LastFmManager.mjs";
@@ -168,24 +167,11 @@ export class Remix {
this._announcementChannelCache = new Map(); this._announcementChannelCache = new Map();
this.intentionalLeaves = new Map(); this.intentionalLeaves = new Map();
// ── Recovery Manager (24/7 auto-join + spawn) ──────────────────────────
// Handles 24/7 auto-join on boot and player spawning.
// The boot-time session recovery system has been removed.
this.recoveryManager = new RecoveryManager(this);
// Expose recoveryManager on the Fluxer client so that Player.mjs and
// other modules that only have a client reference can access it.
client._recoveryManager = this.recoveryManager;
// ── Gateway Handler ───────────────────────────────────────────────────── // ── Gateway Handler ─────────────────────────────────────────────────────
// Handles raw WS gateway events, voice-state tracking, presence rotation, // Handles raw WS gateway events, voice-state tracking, presence rotation,
// and high-level Fluxer event handlers (GuildCreate, GuildDelete, // and high-level Fluxer event handlers (GuildCreate, GuildDelete,
// VoiceStateUpdate). // VoiceStateUpdate).
this.gatewayHandler = new GatewayHandler(this, this.recoveryManager); this.gatewayHandler = new GatewayHandler(this);
// Give RecoveryManager a back-reference to GatewayHandler so it can call
// reseedVoiceStatesForChannel() after spawning a player.
this.recoveryManager.gatewayHandler = this.gatewayHandler;
// Register GuildCreate, GuildDelete, VoiceStateUpdate handlers now so they // Register GuildCreate, GuildDelete, VoiceStateUpdate handlers now so they
// are active before the first Ready event fires. // are active before the first Ready event fires.
@@ -240,8 +226,7 @@ export class Remix {
} }
} }
} }
this.recoveryManager.settingsReady = true;
this.recoveryManager.tryAutoJoin();
}); });
// ── Bot ready ───────────────────────────────────────────────────────────── // ── Bot ready ─────────────────────────────────────────────────────────────
@@ -317,7 +302,6 @@ export class Remix {
player: this.playerContext, player: this.playerContext,
dashboard: this.dashboard, dashboard: this.dashboard,
locale: this.locale, locale: this.locale,
spawnPlayer: this._spawnPlayer,
timers: this.T, timers: this.T,
}); });
this.players.observedVoiceUsers = this.observedVoiceUsers; this.players.observedVoiceUsers = this.observedVoiceUsers;
@@ -705,13 +689,6 @@ export class Remix {
} }
} }
// ── Snapshot other 247 auto channels before leaving ────────────────
const other247AutoChannels = [...channels].filter(id => {
if (id === cleanId) return false;
const mode = get247ChannelMode(set, id);
return mode === "auto";
});
if (channels.has(cleanId)) { if (channels.has(cleanId)) {
channels.delete(cleanId); channels.delete(cleanId);
set.set("stay_247", channels.size > 0 ? [...channels] : "none"); set.set("stay_247", channels.size > 0 ? [...channels] : "none");
@@ -733,38 +710,6 @@ export class Remix {
message.replyEmbed(this.locale.translate(guildIdForLocale, "responses._common.successfullyLeft")); message.replyEmbed(this.locale.translate(guildIdForLocale, "responses._common.successfullyLeft"));
} }
// ── Rejoin other 24/7 auto channels that may have been collateral-disconnected ──
// When the gateway sends a guild-level leave (because leaveChannel() API
// was unavailable), ALL voice connections in the guild are dropped. We
// must schedule rejoins for every other 24/7 auto channel that lost its
// player as a side effect.
if (other247AutoChannels.length > 0) {
const rejoinBaseDelay = this.T?.leave247RejoinDelay ?? 5000;
const rejoinStagger = this.T?.rejoin247Delay ?? 3000;
for (let i = 0; i < other247AutoChannels.length; i++) {
const otherChannelId = other247AutoChannels[i];
const otherPlayer = this.players.playerMap.get(otherChannelId);
// Only rejoin if the player is gone (was collateral-disconnected)
if (!otherPlayer || otherPlayer._destroyed) {
if (otherPlayer) {
this.players.playerMap.delete(otherChannelId);
try { otherPlayer.destroy(); } catch (_) {}
}
const delay = rejoinBaseDelay + (i + 1) * rejoinStagger;
logger.recovery(
`[leaveChannel] Scheduling 247 auto-rejoin for collateral-disconnected channel ${otherChannelId} in ${delay}ms`
);
setTimeout(() => {
if (this._spawnPlayer) {
this._spawnPlayer(guildId, otherChannelId).catch(e =>
logger.warn("[leaveChannel] 247 collateral rejoin failed for", otherChannelId, e.message)
);
}
}, delay);
}
}
}
return true; return true;
} }
+8 -209
View File
@@ -15,11 +15,9 @@ import mysql from "mysql2";
export class GatewayHandler { export class GatewayHandler {
/** /**
* @param {import('../../index.mjs').Remix} remix The running bot instance. * @param {import('../../index.mjs').Remix} remix The running bot instance.
* @param {import('./RecoveryManager.mjs').RecoveryManager} recoveryManager For scheduleSpawn / 24/7 auto-join.
*/ */
constructor(remix, recoveryManager) { constructor(remix) {
this.remix = remix; this.remix = remix;
this.recoveryManager = recoveryManager;
// ── Timers config (kept local — derived from remix.config) ─────────────── // ── Timers config (kept local — derived from remix.config) ───────────────
const timers = remix.config.timers ?? {}; const timers = remix.config.timers ?? {};
@@ -41,25 +39,6 @@ export class GatewayHandler {
/** @type {Map<string, {channelId, guildId}>} guildId:userId → state */ /** @type {Map<string, {channelId, guildId}>} guildId:userId → state */
this._prevVoiceState = new Map(); this._prevVoiceState = new Map();
// ── Recent join tracker (for detecting channel moves during recovery) ────
// When the bot joins a new channel via recovery/spawn, the gateway sends
// a VOICE_STATE_UPDATE with channel_id=null for the old channel. Without
// tracking recent joins, this looks like a real disconnect and triggers
// a recovery loop. By tracking recent joins, we can distinguish between
// a real disconnect and a channel-move side effect.
/** @type {Map<string, number>} guildId → timestamp of last bot voice join */
this._recentBotJoins = new Map();
/** @type {number} Window in ms during which a bot disconnect is considered
* a move side-effect rather than a real disconnect. */
this._moveDetectionWindow = 10_000;
// ── Gateway disconnect cooldown ──────────────────────────────────────────
// After the gateway force-disconnects the bot, don't attempt recovery
// for this guild until the cooldown expires. This prevents the cascade
// where recovery rejoins → gateway disconnects again → recovery again.
/** @type {Map<string, number>} guildId → timestamp when cooldown expires */
this._gatewayDisconnectCooldown = new Map();
// ── Startup GuildDelete deferral ─────────────────────────────────────── // ── Startup GuildDelete deferral ───────────────────────────────────────
// Fluxer's GUILD_DELETE does NOT expose the `unavailable` flag, so we // Fluxer's GUILD_DELETE does NOT expose the `unavailable` flag, so we
// cannot distinguish "bot was kicked" from "guild is temporarily // cannot distinguish "bot was kicked" from "guild is temporarily
@@ -726,37 +705,6 @@ export class GatewayHandler {
} }
} }
// Part 3: 24/7 auto-join for late-arriving guilds
// If tryAutoJoin() has already completed (meaning this GUILD_CREATE
// arrived after the initial recovery sweep), check whether this guild
// has 24/7 channels that need a player. This handles the race where
// the guild cache wasn't populated when tryAutoJoin() built its join
// list, causing those channels to be skipped.
if (this.recoveryManager._autoJoinDone) {
try {
const set = remix.settingsMgr.getServer(guildId);
if (set) {
const raw = set.get("stay_247");
if (raw && raw !== "none") {
const channels = Array.isArray(raw)
? raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15)
: [String(raw).replace(/\D/g, "")].filter(id => id.length >= 15);
for (const chId of channels) {
// Per-channel mode: only spawn if this channel is on/auto
const mode = get247ChannelMode(set, chId);
if (mode !== "on" && mode !== "auto") continue;
// Only spawn if there isn't already a player for this channel
if (!remix.players.playerMap.has(chId) && !this.recoveryManager.pendingSpawns.has(chId)) {
logger.voice247(
`[GuildCreate] Late-arriving guild ${guildId} — scheduling 24/7 spawn for channel ${chId} (mode ${mode})`
);
this.recoveryManager.scheduleSpawn(guildId, chId, this.T.rejoin247Delay, "guild-create-247");
}
}
}
}
} catch (_) {}
}
}); });
// ── GUILD_DELETE ──────────────────────────────────────────────────────── // ── GUILD_DELETE ────────────────────────────────────────────────────────
@@ -956,11 +904,6 @@ export class GatewayHandler {
// ── Bot-only logic below ─────────────────────────────────────────────── // ── Bot-only logic below ───────────────────────────────────────────────
// Track recent bot joins to distinguish real disconnects from move side-effects
if (channelId && guildId) {
this._recentBotJoins.set(String(guildId).replace(/\D/g, ""), Date.now());
}
const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) => const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) =>
String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "") String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "")
); );
@@ -1006,7 +949,6 @@ export class GatewayHandler {
} }
})(); })();
const newChannelPendingSpawn = const newChannelPendingSpawn =
this.recoveryManager?.pendingSpawns?.has?.(cleanId) ||
remix.players?._pendingJoins?.has?.(cleanId) || remix.players?._pendingJoins?.has?.(cleanId) ||
false; false;
const targetChannel = client.channels.get(cleanId) const targetChannel = client.channels.get(cleanId)
@@ -1155,160 +1097,21 @@ export class GatewayHandler {
} }
} }
// Bot disconnected unexpectedly — rejoin if 247 active // Bot disconnected unexpectedly — emit autoleave on the player
if (!channelId && oldChannelId && guildId) { if (!channelId && oldChannelId && guildId) {
try { try {
const cleanOld = String(oldChannelId).replace(/\D/g, ""); const cleanOld = String(oldChannelId).replace(/\D/g, "");
const cleanGuild = String(guildId).replace(/\D/g, "");
if (remix.intentionalLeaves.has(cleanOld)) { if (remix.intentionalLeaves.has(cleanOld)) {
logger.voice247(`[247] Skipping rejoin for ${cleanOld} — intentional leave.`); logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`);
} else { } else {
// Check if the bot is still in another voice channel in this guild.
// During multi-voice recovery, the bot may be moved from one channel
// to another, which triggers a disconnect event for the old channel.
// This is NOT a real disconnect — it's a side effect of joining a
// new channel in the same guild. Skip recovery in this case to
// prevent the recovery loop (Bug #5).
const botInOtherChannel = [...remix.players.playerMap.entries()].some(([mapKey, p]) => {
if (String(p?._guildId ?? "").replace(/\D/g, "") !== String(guildId ?? "").replace(/\D/g, "")) return false;
const pChannel = String(p?._channelId ?? mapKey).replace(/\D/g, "");
return pChannel !== cleanOld && !p.leaving && !p._destroyed;
});
// Also check if there was a recent bot join in this guild — if so,
// the disconnect is likely a side-effect of the channel move, not a
// real disconnect that needs recovery.
// IMPORTANT: We also verify that the bot is in another channel in
// THIS SAME guild. Cross-guild joins should NOT suppress recovery
// for this guild's disconnect — that was causing guilds to lose
// their 24/7 player silently when a different guild joined nearby.
const recentJoin = this._recentBotJoins.get(cleanGuild) ?? 0;
const timeSinceJoin = Date.now() - recentJoin;
const isLikelyMoveSideEffect = timeSinceJoin < this._moveDetectionWindow && botInOtherChannel;
// Also check if there are pending spawns for this guild — if a
// spawnPlayer is in progress, the disconnect is expected.
// pendingSpawns is a Set<string> (channel IDs), not a Map — we
// cross-reference with scheduledSpawns to check the guild.
const hasPendingSpawn = (() => {
for (const chId of this.recoveryManager.pendingSpawns) {
const entry = this.recoveryManager.scheduledSpawns.get(chId);
if (entry && String(entry.guildId).replace(/\D/g, "") === cleanGuild) return true;
}
for (const [, entry] of this.recoveryManager.scheduledSpawns) {
if (String(entry.guildId).replace(/\D/g, "") === cleanGuild) return true;
}
return false;
})();
// Check gateway disconnect cooldown — if the gateway recently
// force-disconnected us, don't attempt recovery again immediately.
const cooldownExpiry = this._gatewayDisconnectCooldown.get(cleanGuild) ?? 0;
const inCooldown = Date.now() < cooldownExpiry;
if (inCooldown) {
logger.voice247(
`[247] Skipping recovery for ${cleanOld} in guild ${guildId} — ` +
`gateway disconnect cooldown active (${Math.ceil((cooldownExpiry - Date.now()) / 1000)}s remaining).`
);
} else if (botInOtherChannel || (isLikelyMoveSideEffect && !hasPendingSpawn)) {
const reason = botInOtherChannel ? "bot in other channel" : `recent join ${timeSinceJoin}ms ago (move side-effect)`;
logger.voice247(
`[247] Bot disconnected from ${cleanOld} but ${reason} ` +
`in guild ${guildId} — skipping recovery (likely a channel move).`
);
// Clean up the old player entry if it wasn't already removed
const oldPlayer = remix.players.playerMap.get(cleanOld);
if (oldPlayer && !oldPlayer._destroyed) {
remix.players.playerMap.delete(cleanOld);
try { oldPlayer.destroy(); } catch (_) {}
}
} else if (hasPendingSpawn) {
logger.voice247(
`[247] Bot disconnected from ${cleanOld} in guild ${guildId} — ` +
`pending spawn in progress, skipping recovery to avoid race.`
);
} else {
const set = remix.settingsMgr.getServer(guildId);
if (!set) {
logger.voice247(
`[247] Skipping recovery for ${cleanOld} in guild ${guildId} — ` +
`settings not loaded yet (race with GuildCreate).`
);
return;
}
const raw = set.get("stay_247");
if (raw && raw !== "none") {
const channels = Array.isArray(raw)
? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15))
: new Set();
if (channels.has(cleanOld)) {
// Per-channel mode: check the mode for this specific channel
const mode = get247ChannelMode(set, cleanOld);
if (mode === "on" || mode === "auto") {
// Check persistent 401 ban — if this guild was recently
// 401-banned, don't attempt recovery (it will fail).
const banExpiry = this.recoveryManager._guild401Ban?.get(cleanGuild) ?? 0;
if (banExpiry > Date.now()) {
logger.voice247(
`[247] Skipping recovery for ${cleanOld} in guild ${guildId} — ` +
`guild is 401-banned (${Math.round((banExpiry - Date.now()) / 1000)}s remaining).`
);
// Remove the old player entry and destroy it
remix.players.playerMap.delete(cleanOld);
try { remix.players.playerMap.get(cleanOld)?.destroy(); } catch (_) {}
return;
}
// Match the specific player by channel ID
const player = remix.players.playerMap.get(cleanOld); const player = remix.players.playerMap.get(cleanOld);
if (player && !player.leaving) { if (player && !player.leaving && !player._destroyed) {
logger.voice247("[247] Fluxer gateway disconnected us. Forcing player recovery..."); logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — emitting autoleave.`);
player.emit("autoleave");
// Set a gateway disconnect cooldown for this guild to
// prevent recovery cascades. If recovery rejoins and the
// gateway force-disconnects again, we don't want to
// immediately retry.
this._gatewayDisconnectCooldown.set(cleanGuild, Date.now() + 15_000);
// Auto-clear the cooldown after 30 seconds
setTimeout(() => this._gatewayDisconnectCooldown.delete(cleanGuild), 30_000);
// Mark the disconnect reason on the player for smarter recovery
player._lastDisconnectReason = "gateway";
player._lastDisconnectTime = Date.now();
if (typeof player._recoverConnection === "function") {
player._recoverConnection();
} else {
remix.players.playerMap.delete(cleanOld);
try { player.destroy(); } catch (_) {}
this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect");
}
} else {
this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect");
}
} else {
logger.voice247(`[247] Channel ${cleanOld} mode='${mode}' — not rejoining.`);
channels.delete(cleanOld);
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
// Also clean up the per-channel mode entry
const modes = set.get("stay_247_modes");
if (modes && typeof modes === "object" && !Array.isArray(modes)) {
delete modes[cleanOld];
set.set("stay_247_modes", modes);
}
if (channels.size === 0) set.set("stay_247_mode", "off");
else {
const first = [...channels][0];
set.set("stay_247_mode", modes?.[first] ?? "auto");
}
}
}
}
} }
} }
} catch (e) { } catch (e) {
logger.warn("[247] Rejoin on disconnect failed:", e.message); logger.warn("[VoiceState] Bot disconnect handler failed:", e.message);
} }
} }
} }
@@ -1317,16 +1120,12 @@ export class GatewayHandler {
/** /**
* Invoke after the bot has connected and Moonlink has been initialised. * Invoke after the bot has connected and Moonlink has been initialised.
* Seeds voice states, attaches raw WS listener, signals botReady, and * Seeds voice states, attaches raw WS listener, and kicks off presence rotation.
* kicks off presence rotation.
*/ */
onReady() { onReady() {
this.seedVoiceStatesFromGuilds(); this.seedVoiceStatesFromGuilds();
this.attachRawListener(); this.attachRawListener();
this.recoveryManager.botReady = true;
this.recoveryManager.tryAutoJoin();
this.setupPresenceRotation(); this.setupPresenceRotation();
// End the startup grace period after the configured delay. // End the startup grace period after the configured delay.
+12 -242
View File
@@ -302,7 +302,6 @@ export default class Player extends EventEmitter {
// that even if the bot is temporarily in a transit channel (e.g. "move"), // that even if the bot is temporarily in a transit channel (e.g. "move"),
// the player knows its intended home channel and can check 247 correctly. // the player knows its intended home channel and can check 247 correctly.
_home247Channel = null; _home247Channel = null;
_recoveryTimer = null;
// Components // Components
queue = null; queue = null;
@@ -324,12 +323,7 @@ export default class Player extends EventEmitter {
_paused = false; _paused = false;
_pausedAt = null; // track exact moment of pause for clock sync _pausedAt = null; // track exact moment of pause for clock sync
_playingNext = false; _playingNext = false;
_isRecovering = false;
startedPlaying = null; startedPlaying = null;
// Track last disconnect reason for smarter recovery
_lastDisconnectReason = null; // "401" | "gateway" | "unexpected" | null
_lastDisconnectTime = 0; // timestamp of last disconnect
// searches Map with max-size eviction to prevent memory leak on busy servers. // searches Map with max-size eviction to prevent memory leak on busy servers.
searches = new Map(); searches = new Map();
_searchMaxSize = 50; _searchMaxSize = 50;
@@ -457,16 +451,6 @@ export default class Player extends EventEmitter {
return false; return false;
} }
_getRecoveryChannelId() {
const cleanCurrent = String(this._channelId ?? "").replace(/\D/g, "");
if (cleanCurrent) return cleanCurrent;
const cleanHome = String(this._home247Channel ?? "").replace(/\D/g, "");
if (cleanHome && this._is247Enabled()) return cleanHome;
return cleanHome || null;
}
/** /**
* Resolve the guild ID for this player, using the channel cache * Resolve the guild ID for this player, using the channel cache
* as a fallback if _guildId is not set. This is needed for * as a fallback if _guildId is not set. This is needed for
@@ -516,198 +500,6 @@ export default class Player extends EventEmitter {
} }
} }
// ═══════════════════════════════════════════════════════════════════════════
// Connection Recovery
// ═══════════════════════════════════════════════════════════════════════════
async _recoverConnection() {
// bail immediately if the player has been destroyed or a recovery is
// already in-flight or scheduled (covers the gap between attempts).
if (this._isRecovering || this._recoveryPending || this._destroyed) return;
const targetChannelId = this._getRecoveryChannelId();
if (!targetChannelId) {
logger.warn(`[Player] Recovery aborted for guild ${this._guildId} - no channel target available.`);
this.emit("autoleave");
return;
}
// ── 401 Permission-based recovery guard ──────────────────────────────
// If the last disconnect was due to a 401 Unauthorized error, don't
// keep retrying — 401 is a permission problem, not a transient failure.
// Retrying just creates more 401 errors and recovery loops.
// Instead, give up on recovery and let the 24/7 system schedule a
// delayed respawn.
if (this._lastDisconnectReason === "401") {
const timeSinceDisconnect = Date.now() - this._lastDisconnectTime;
if (timeSinceDisconnect < 60_000) {
logger.warn(
`[Player] Skipping recovery for guild ${this._guildId} — ` +
`last disconnect was 401 Unauthorized (${timeSinceDisconnect / 1000}s ago). ` +
`Delegating to 24/7 respawn system.`
);
this._isRecovering = false;
this._recoveryPending = false;
this.emit("autoleave");
return;
}
// If more than 60s have passed since the 401, try again — permissions
// may have been restored.
logger.player(
`[Player] 401 was ${timeSinceDisconnect / 1000}s ago — retrying recovery ` +
`(permissions may have been restored).`
);
}
this._isRecovering = true;
this._recoveryPending = true;
this._recoveryAttempts = (this._recoveryAttempts ?? 0) + 1;
const MAX_RECOVERY = 5;
if (this._recoveryAttempts > MAX_RECOVERY) {
logger.error(`[Player] Recovery failed after ${MAX_RECOVERY} attempts for guild ${this._guildId} — giving up.`);
this._isRecovering = false;
this._recoveryPending = false;
this._recoveryAttempts = 0;
this.emit("autoleave");
return;
}
// Exponential backoff: 2s, 4s, 8s, 16s, 32s (was linear: 2s, 4s, 6s, 8s, 10s)
// If last disconnect was a gateway force-disconnect, use longer backoff
// to avoid the recovery cascade where rejoining causes another disconnect.
let backoffMs;
if (this._lastDisconnectReason === "gateway") {
// Gateway force-disconnects need longer recovery time to avoid cascading
backoffMs = Math.min(5000 * Math.pow(2, this._recoveryAttempts - 1), 60_000);
} else {
backoffMs = Math.min(2000 * Math.pow(2, this._recoveryAttempts - 1), 30_000);
}
logger.mediaplayer(`[Player] Recovery attempt ${this._recoveryAttempts}/${MAX_RECOVERY} for ${this._guildId} (backoff ${backoffMs}ms, reason: ${this._lastDisconnectReason ?? "unknown"})`);
await Utils.sleep(backoffMs);
// re-check after await — player may have been destroyed during backoff
if (this._destroyed) {
this._isRecovering = false;
return;
}
// Wait for _isJoining to clear — if another operation (e.g. spawnPlayer or
// a concurrent _recoverConnection from a different event path) is currently
// calling join(), we must not race against it. Poll every 500ms for up to
// 15s, then give up on this attempt and schedule a retry.
let waited = 0;
while (this._isJoining && waited < 15_000) {
logger.mediaplayer(`[Player] Waiting for _isJoining to clear before recovery attempt...`);
await Utils.sleep(500);
waited += 500;
}
if (this._isJoining) {
logger.warn("[Player] _isJoining still busy after 15s — deferring recovery attempt.");
this._isRecovering = false;
this._recoveryPending = false;
// Schedule a retry via setTimeout so we don't stack synchronous calls
this._recoveryTimer = setTimeout(() => {
this._recoveryTimer = null;
this._recoverConnection().catch(() => {});
}, 2000);
return;
}
logger.mediaplayer(`[Player] Attempting to recover voice connection for ${this._guildId}`);
try {
if (this.connection) {
// Clean up the old connection. FluxerVoiceConnection.disconnect()
// handles native @fluxerjs/voice disconnect + LiveKit room close.
// We also need to send a gateway leave signal so the gateway
// processes the leave before we attempt to rejoin.
try { await this.connection.disconnect(); } catch (_) {}
// Explicitly send a gateway leave signal via @fluxerjs/voice so
// the gateway knows the bot left the channel. Without this, the
// gateway may still think the bot is in the channel and won't
// send a fresh VOICE_SERVER_UPDATE on the next joinVoiceChannel().
try {
const vm = getVoiceManager(this.client);
if (vm && typeof vm.updateVoiceState === "function") {
// IMPORTANT: Always use guild-scoped leave. An unscoped
// updateVoiceState(null, opts) disconnects ALL guilds' voice
// connections, causing cascading failures.
const guildIdForLeave = this._guildId ?? this._resolveGuildId();
if (guildIdForLeave) {
try {
vm.updateVoiceState(guildIdForLeave, null, { self_deaf: false, self_mute: false });
} catch (e1) {
// Older @fluxerjs/voice may not accept 3-arg form
try { vm.updateVoiceState(guildIdForLeave, null); } catch (e2) {}
}
logger.mediaplayer(`[Player] Sent guild-scoped gateway leave signal for guild ${guildIdForLeave} before recovery rejoin`);
} else {
logger.warn(`[Player] Cannot send guild-scoped leave — no guildId available. Skipping to avoid disconnecting all guilds.`);
}
}
} catch (e) {
logger.warn(`[Player] Gateway leave signal failed: ${e?.message}`);
}
// Also remove the stale connection from FluxerRevoice's map
// so the next _revoice.join() doesn't return the dead connection.
if (this._revoice && this._channelId) {
try { this._revoice.deleteConnection(this._channelId); } catch (_) {}
}
}
await Utils.sleep(3000);
if (this.leaving || this._destroyed) return;
logger.mediaplayer(`[Player] Rejoining channel ${targetChannelId}`);
await this.join(targetChannelId);
// Do NOT re-read room.isConnected/room.connectionState here —
// join() already awaited ConnectionStateChanged and only resolved when
// the room was truly connected, so reaching this line means success.
// The old check using room.state (which doesn't exist in @livekit/rtc-node)
// always threw "unexpected state: undefined" and emitted autoleave,
// causing the infinite reconnect storm in the logs.
this._isRecovering = false;
this._recoveryPending = false;
this._recoveryAttempts = 0;
if (this._recoveryTimer) {
clearTimeout(this._recoveryTimer);
this._recoveryTimer = null;
}
// Keep _home247Channel in sync with the channel we successfully recovered to.
if (this._channelId) this._home247Channel = this._channelId;
const current = this.queue.getCurrent();
if (current) {
logger.player(`[Player] Resuming track after recovery: ${current.title}`);
this.queue.data.unshift(current);
this.queue.current = null;
this._playingNext = false;
await this.playNext();
} else if (!this.queue.isEmpty()) {
this._playingNext = false;
await this.playNext();
}
} catch (e) {
logger.error("[Player] Recovery failed:", e.message);
this._isRecovering = false;
// _recoveryPending stays true during the retry delay to block duplicate
// calls from stacking up (e.g. two rapid disconnect events).
if (!this._destroyed && !this.leaving) {
const delay = Math.min(2000 * (this._recoveryAttempts ?? 1), 30_000);
if (this._recoveryTimer) clearTimeout(this._recoveryTimer);
this._recoveryTimer = setTimeout(() => {
this._recoveryTimer = null;
this._recoveryPending = false;
if (!this._destroyed && !this.leaving) this._recoverConnection();
}, delay);
} else {
this._recoveryPending = false;
}
}
}
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
// Inactivity Timer // Inactivity Timer
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
@@ -920,7 +712,6 @@ export default class Player extends EventEmitter {
logger.error("[Player] Error stopping media player:", e.message); logger.error("[Player] Error stopping media player:", e.message);
} }
await new Promise(r => setTimeout(r, 150));
// Null the reference so the native revoice.js/LiveKit object can be GC'd. // Null the reference so the native revoice.js/LiveKit object can be GC'd.
this._mediaPlayer = null; this._mediaPlayer = null;
} }
@@ -1287,10 +1078,10 @@ export default class Player extends EventEmitter {
try { this._revoice.deleteConnection(this._channelId); } catch (_) {} try { this._revoice.deleteConnection(this._channelId); } catch (_) {}
} }
// Wait longer (1500ms instead of 500ms) to give the Fluxer gateway // Wait to give the Fluxer gateway time to process the voice state
// time to process the voice state leave before we join a new channel. // leave before we join a new channel. FluxerRevoice adds its own
// 500ms was too short and caused 401 errors on the subsequent join. // _globalJoinDelay before the actual join, so 500ms here is enough.
await Utils.sleep(1500); await Utils.sleep(500);
this.connection = null; this.connection = null;
this._mediaPlayer = null; this._mediaPlayer = null;
} }
@@ -1423,12 +1214,11 @@ export default class Player extends EventEmitter {
try { connection.removeAllListeners(); } catch (_) {} try { connection.removeAllListeners(); } catch (_) {}
return; return;
} }
const causeStr = err?.cause ? ` (Cause: ${err.cause})` : ""; logger.error("[Player] Voice error:", err?.message ?? err);
logger.error("[Player] Voice error:", err?.message ?? err, causeStr);
this._stopMediaPlayer() this._stopMediaPlayer()
.catch(() => {}) .catch(() => {})
.finally(() => { .finally(() => {
if (!this.leaving && !this._destroyed) this._recoverConnection(); if (!this.leaving && !this._destroyed) this.emit("autoleave");
}); });
}); });
@@ -1438,19 +1228,10 @@ export default class Player extends EventEmitter {
return; return;
} }
if (!this.leaving && !this._destroyed) { if (!this.leaving && !this._destroyed) {
// Detect the reason for the disconnect to make smarter recovery decisions logger.mediaplayer("[Player] Unexpected disconnect detected");
const room = connection.room;
const lastSignalErr = room?._lastSignalError;
if (lastSignalErr?.includes?.("401") || lastSignalErr?.includes?.("Unauthorized")) {
this._lastDisconnectReason = "401";
} else {
this._lastDisconnectReason = "unexpected";
}
this._lastDisconnectTime = Date.now();
logger.mediaplayer(`[Player] Unexpected disconnect detected (reason: ${this._lastDisconnectReason})`);
this._stopMediaPlayer() this._stopMediaPlayer()
.catch(() => {}) .catch(() => {})
.finally(() => this._recoverConnection()); .finally(() => this.emit("autoleave"));
} else { } else {
try { connection.removeAllListeners(); } catch (_) {} try { connection.removeAllListeners(); } catch (_) {}
} }
@@ -1475,7 +1256,7 @@ export default class Player extends EventEmitter {
const playerReady = await this._ensureMediaPlayer(); const playerReady = await this._ensureMediaPlayer();
if (!playerReady) { if (!playerReady) {
logger.mediaplayer("[Player] First MediaPlayer attempt failed, retrying after delay..."); logger.mediaplayer("[Player] First MediaPlayer attempt failed, retrying after delay...");
await Utils.sleep(3000); await Utils.sleep(1500);
if (this._destroyed || this.leaving) throw new Error("Player destroyed during MediaPlayer retry"); if (this._destroyed || this.leaving) throw new Error("Player destroyed during MediaPlayer retry");
const roomAlive = this.connection?.room?.isConnected ?? false; const roomAlive = this.connection?.room?.isConnected ?? false;
if (!roomAlive) { if (!roomAlive) {
@@ -1506,10 +1287,9 @@ export default class Player extends EventEmitter {
const causeStr = e.cause ? ` (Cause: ${e.cause})` : ""; const causeStr = e.cause ? ` (Cause: ${e.cause})` : "";
logger.error("[Player] Join failed:", e.message, causeStr); logger.error("[Player] Join failed:", e.message, causeStr);
// Track the disconnect reason for smarter recovery decisions
if (e.message?.includes("401") || e.message?.includes("Unauthorized")) { if (e.message?.includes("401") || e.message?.includes("Unauthorized")) {
this._lastDisconnectReason = "401"; // Track 401 errors for logging purposes
this._lastDisconnectTime = Date.now(); logger.warn(`[Player] Join failed with 401 Unauthorized for guild ${this._guildId}`);
} }
if (this.connection) { if (this.connection) {
@@ -1527,12 +1307,6 @@ export default class Player extends EventEmitter {
try { try {
this.leaving = true; this.leaving = true;
this._stopInactivityTimer(); this._stopInactivityTimer();
if (this._recoveryTimer) {
clearTimeout(this._recoveryTimer);
this._recoveryTimer = null;
}
this._recoveryPending = false;
this._isRecovering = false;
this._streamingStopped = true; this._streamingStopped = true;
if (this._mediaPlayer) { if (this._mediaPlayer) {
@@ -1798,9 +1572,6 @@ export default class Player extends EventEmitter {
await this._stopMediaPlayer().catch(() => {}); await this._stopMediaPlayer().catch(() => {});
this._streamingStopped = false; this._streamingStopped = false;
// Small delay to let the old pipe fully drain
await Utils.sleep(100);
// _stopMediaPlayer sets _mediaPlayer to null — must recreate before streaming // _stopMediaPlayer sets _mediaPlayer to null — must recreate before streaming
const hasPlayer = await this._ensureMediaPlayer(); const hasPlayer = await this._ensureMediaPlayer();
if (!hasPlayer) { if (!hasPlayer) {
@@ -2343,7 +2114,6 @@ export default class Player extends EventEmitter {
this._mediaPlayer.setVolume(this.preferredVolume); this._mediaPlayer.setVolume(this.preferredVolume);
} }
await Utils.sleep(200);
if (!this.connection || this.leaving) return; if (!this.connection || this.leaving) return;
let streamUrl = null; let streamUrl = null;
@@ -2416,7 +2186,7 @@ export default class Player extends EventEmitter {
this.queue.data.unshift(songData); this.queue.data.unshift(songData);
this.queue.current = null; this.queue.current = null;
this._streamingStopped = false; this._streamingStopped = false;
await Utils.sleep(1500); await Utils.sleep(500);
if (!this.leaving && !this._skipping) return this._doPlayNext(); if (!this.leaving && !this._skipping) return this._doPlayNext();
} else { } else {
if (!this._paused) { if (!this._paused) {
+3 -11
View File
@@ -117,7 +117,6 @@ export class PlayerManager {
this.playerConfig = config.player; this.playerConfig = config.player;
this.dashboard = config.dashboard ?? null; this.dashboard = config.dashboard ?? null;
this.locale = config.locale ?? null; this.locale = config.locale ?? null;
this.spawnPlayer = config.spawnPlayer ?? null; // RecoveryManager.spawnPlayer — for 24/7 rejoin
this.timers = config.timers ?? {}; this.timers = config.timers ?? {};
this._lastfm = null; // Set later by Remix class after init this._lastfm = null; // Set later by Remix class after init
} }
@@ -817,16 +816,9 @@ export class PlayerManager {
player.destroy(); player.destroy();
if (isIn247List && (mode247 === "on" || mode247 === "auto")) { if (isIn247List && (mode247 === "on" || mode247 === "auto")) {
// 24/7 is active — rejoin after a short delay (same as RecoveryManager.spawnPlayer autoleave) // 24/7 mode active — just leave the player, no auto-rejoin.
const delay = this.timers?.rejoin247Delay ?? 3000; // Users can re-invoke the play command to restart the bot in the channel.
if (this.spawnPlayer) { logger.voice247(`[AutoLeave] 24/7 channel ${homeChannelId} (mode ${mode247}) auto-left — no auto-rejoin (recovery system removed).`);
logger.recovery(`[AutoLeave] 24/7 rejoin scheduled for ${homeChannelId} (mode ${mode247}) in ${delay}ms`);
setTimeout(() => {
this.spawnPlayer(guildId, homeChannelId).catch(e =>
logger.warn("[AutoLeave] 24/7 rejoin failed for", homeChannelId, e.message)
);
}, delay);
}
} else { } else {
// Not 24/7 — send inactivity message // Not 24/7 — send inactivity message
const prefix = (() => { const prefix = (() => {
-550
View File
@@ -1,550 +0,0 @@
import { logger } from "./constants/Logger.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "./MessageHandler.mjs";
import Player from "./Player.mjs";
import { get247ChannelMode } from "./constants/Helpers247.mjs";
/**
* RecoveryManager — handles 24/7 auto-join on boot and player spawning.
*
* The boot-time recovery system (session persistence via recovery.json) has
* been removed. On restart the bot starts clean; only 24/7 channels configured
* in each guild's settings are automatically rejoined.
*
* This module still provides:
* - spawnPlayer() — create a Player, join a voice channel (used by 24/7)
* - scheduleSpawn() — delayed player spawn (used by 24/7 autoleave rejoin)
* - cleanStaleGuild() — purge all state for a guild the bot left
* - tryAutoJoin() — auto-join 24/7 channels when bot + settings are ready
*/
export class RecoveryManager {
/**
* @param {import('../../index.mjs').Remix} remix Reference to the running bot instance.
*/
constructor(remix) {
this.remix = remix;
// ── Timers derived from config ────────────────────────────────────────────
const timers = remix.config.timers ?? {};
this.T = {
aloneCheckInterval: timers.aloneCheckInterval ?? 30_000,
aloneCheckDebounce: timers.aloneCheckDebounce ?? 500,
rejoin247Delay: timers.rejoin247Delay ?? 3_000,
};
// ── Internal state ────────────────────────────────────────────────────────
/** @type {Set<string>} Per-channel spawn mutex */
this.pendingSpawns = new Set();
/** @type {Map<string, {timer, guildId, reason}>} Scheduled delayed spawns */
this.scheduledSpawns = new Map();
// ── Ready flags ───────────────────────────────────────────────────────────
this.botReady = false;
this.settingsReady = false;
// ── Auto-join guard ───────────────────────────────────────────────────────
this._autoJoinRunning = false;
this._autoJoinDone = false;
// ── 401 error tracking ──────────────────────────────────────────────────────
/** @type {Map<string, number>} Guild ID → timestamp when 401 ban expires.
* After 3 consecutive 401s, the guild is banned from further retries for
* 5 minutes to avoid infinite retry loops. */
this._guild401Ban = new Map();
/** @type {Map<string, number>} Guild ID → consecutive 401 retry count.
* Used for exponential backoff: 1st retry after 15s, 2nd after 45s, 3rd = ban. */
this._guild401Retries = new Map();
// ── Expose convenience methods on the Remix instance ──────────────────────
remix._spawnPlayer = this.spawnPlayer.bind(this);
// ── GatewayHandler reference (set after construction) ────────────────────
this.gatewayHandler = null;
}
// ── Utility helpers ──────────────────────────────────────────────────────────
normalizeChannelId(value) {
return String(value ?? "").replace(/\D/g, "");
}
/**
* Clean up all state for a guild the bot is no longer a member of.
*
* @param {string} guildId
* @param {string} [reason="bot no longer in guild"]
*/
cleanStaleGuild(guildId, reason = "bot no longer in guild") {
const { remix } = this;
const cleanId = String(guildId).replace(/\D/g, "");
logger.recovery(`[SpawnManager] Cleaning stale guild ${cleanId} (${reason}).`);
// Destroy any active players for this guild
for (const [channelId, player] of remix.players.playerMap) {
if (String(player._guildId ?? "").replace(/\D/g, "") === cleanId) {
remix.players.playerMap.delete(channelId);
try { player.leave().catch(() => {}); } catch (_) {}
try { player.destroy(); } catch (_) {}
}
}
// Cancel any scheduled spawns for this guild
for (const [channelId, entry] of this.scheduledSpawns) {
if (String(entry.guildId).replace(/\D/g, "") === cleanId) {
clearTimeout(entry.timer);
this.scheduledSpawns.delete(channelId);
}
}
// Clean voice-user observations
for (const [userId, info] of [...remix.observedVoiceUsers]) {
if (String(info.guildId).replace(/\D/g, "") === cleanId) remix.observedVoiceUsers.delete(userId);
}
for (const [userId, info] of [...remix.observedVoiceBots]) {
if (String(info.guildId).replace(/\D/g, "") === cleanId) remix.observedVoiceBots.delete(userId);
}
// Remove from settings cache
remix.settingsMgr.removeServer(cleanId);
remix._announcementChannelCache?.delete?.(cleanId);
}
// ── Spawn scheduling ─────────────────────────────────────────────────────────
/**
* Schedule a delayed player spawn. Cancels any previous scheduled spawn for
* the same channel.
*
* @param {string} guildId
* @param {string} channelId
* @param {number} [delayMs=0]
* @param {string} [reason="spawn"]
*/
scheduleSpawn(guildId, channelId, delayMs = 0, reason = "spawn") {
const cleanChannelId = this.normalizeChannelId(channelId);
if (!cleanChannelId) return;
const existing = this.scheduledSpawns.get(cleanChannelId);
if (existing) clearTimeout(existing.timer);
const timer = setTimeout(() => {
this.scheduledSpawns.delete(cleanChannelId);
this.spawnPlayer(guildId, cleanChannelId).catch(e => {
logger.warn(`[PlayerSpawn] Scheduled ${reason} failed for ${cleanChannelId}:`, e?.message ?? e);
});
}, Math.max(0, delayMs));
this.scheduledSpawns.set(cleanChannelId, { timer, guildId, reason });
}
// ── Player spawning ──────────────────────────────────────────────────────────
/**
* Create a new Player and join the target voice channel.
* Used primarily for 24/7 auto-join (boot + autoleave rejoin).
*/
async spawnPlayer(guildId, channelId) {
const { remix } = this;
const cleanChannelId = this.normalizeChannelId(channelId);
if (!cleanChannelId) return;
// Clean up any previously scheduled spawn for this channel.
const scheduled = this.scheduledSpawns.get(cleanChannelId);
if (scheduled) {
clearTimeout(scheduled.timer);
this.scheduledSpawns.delete(cleanChannelId);
}
const cleanGuildId = String(guildId).replace(/\D/g, "");
// ── Pre-flight: verify bot is still in the guild ─────────────────────
// During startup, the guild cache may not be populated yet because
// GuildCreate events haven't arrived. In that case, DON'T call
// cleanStaleGuild — it would nuke the in-memory settings cache for a
// guild the bot IS still in, causing unnecessary churn and scary log
// messages. The GuildCreate handler will schedule the 24/7 spawn for
// late-arriving guilds. cleanStaleGuild is only appropriate when we
// know for sure the bot was kicked (i.e. a GuildDelete was received).
if (!remix.client.guilds.has(guildId) && !remix.client.guilds.has(cleanGuildId)) {
if (this._autoJoinRunning || !this._autoJoinDone) {
// Startup phase — guild cache not populated yet, just skip
logger.recovery(
`[PlayerSpawn] Skipping channel ${cleanChannelId} in guild ${cleanGuildId} — ` +
`guild cache not populated yet (startup race). GuildCreate will schedule spawn.`
);
} else {
// Runtime — bot was actually removed from the guild
logger.recovery(
`[PlayerSpawn] Skipping channel ${cleanChannelId} in guild ${cleanGuildId} — ` +
`bot is no longer in this guild.`
);
this.cleanStaleGuild(guildId, "bot removed before spawn attempt");
}
return;
}
// ── 24/7 check ──────────────────────────────────────────────────────
// Only spawn if this channel is in the stay_247 list.
let set = remix.settingsMgr.getServer(guildId);
let raw = set?.get("stay_247");
if ((!raw || raw === "none") && String(guildId).replace(/\D/g, "") !== String(guildId)) {
const cleanGId = String(guildId).replace(/\D/g, "");
set = remix.settingsMgr.getServer(cleanGId);
raw = set?.get("stay_247");
}
if (!raw || raw === "none") {
logger.recovery(
`[PlayerSpawn] Skipping channel ${cleanChannelId} in guild ${guildId}: ` +
`stay_247=${JSON.stringify(raw)}.`
);
return;
}
const channels = Array.isArray(raw)
? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean))
: new Set([String(raw).replace(/\D/g, "")]);
if (!channels.has(cleanChannelId)) {
logger.recovery(
`[PlayerSpawn] Skipping channel ${cleanChannelId}: not in stay_247 list [${[...channels].join(", ")}]`
);
return;
}
// Atomic mutex check — blocks concurrent spawns for the same channel.
if (remix.players.playerMap.has(cleanChannelId) || this.pendingSpawns.has(cleanChannelId)) return;
// ── Duplicate player cleanup for same guild ──────────────────────────
for (const [mapKey, existingPlayer] of remix.players.playerMap) {
if (existingPlayer._destroyed || existingPlayer.leaving) {
remix.players.playerMap.delete(mapKey);
try { existingPlayer.destroy(); } catch (_) {}
continue;
}
const existingChannelId = String(existingPlayer._channelId ?? mapKey).replace(/\D/g, "");
const existingGuildId = String(existingPlayer._guildId ?? "").replace(/\D/g, "");
if (existingGuildId === cleanGuildId && existingChannelId === cleanChannelId) {
logger.warn(
`[PlayerSpawn] Found existing player for channel ${cleanChannelId} ` +
`in guild ${cleanGuildId} (mapKey=${mapKey}) — destroying duplicate before spawning new player`
);
remix.players.playerMap.delete(mapKey);
try { existingPlayer.leave().catch(() => {}); } catch (_) {}
try { existingPlayer.destroy(); } catch (_) {}
}
}
this.pendingSpawns.add(cleanChannelId);
try {
let channel = remix.client.channels.get(cleanChannelId);
if (!channel) {
try {
channel = await remix.client.channels.fetch(cleanChannelId);
} catch (e) {
throw new Error(`Could not fetch channel ${cleanChannelId}: ${e.message}`);
}
}
if (!channel) { throw new Error(`Channel not found: ${cleanChannelId}`); }
remix.client.channels.set(cleanChannelId, channel);
const p = new Player(remix.config.token, {
client: remix.client,
config: remix.config,
nodelink: remix.config.nodelink,
moonlink: remix.moonlink,
revoice: remix.revoice,
settingsMgr: remix.settingsMgr,
observedVoiceUsers: remix.observedVoiceUsers,
locale: remix.locale ?? null,
});
remix.players.setupEvents(p, { channelId: cleanChannelId, guildId });
// ── Set a default textChannel so song announcements have somewhere to go ──
// After a reboot, spawned players don't have a user message to set
// textChannel from. Find the guild's announcement channel or the first
// available text channel as a fallback.
try {
const guild = remix.client.guilds.get(cleanGuildId) ?? remix.client.guilds.get(guildId);
const serverSet = remix.settingsMgr.getServer(guildId);
const cachedChId = remix._announcementChannelCache?.get?.(guildId)
?? serverSet?.get("announcementChannelId")
?? null;
let textCh = cachedChId ? guild?.channels?.get(String(cachedChId)) : null;
if (!textCh && guild) {
textCh = [...(guild.channels?.values?.() ?? [])].find(c =>
(c.isTextBased?.() ?? c.channel_type === "TextChannel" ?? true) &&
(c.permissionsFor?.(remix.client.user)?.has?.("SendMessages") ?? true)
);
}
if (textCh) {
p.textChannel = textCh;
if (!cachedChId && serverSet) {
remix._announcementChannelCache?.set?.(guildId, textCh.id);
if (serverSet.get("announcementChannelId") !== textCh.id) {
serverSet.set("announcementChannelId", textCh.id);
}
}
}
} catch (_) {}
// ── Autoleave handler ───────────────────────────────────────────────────
p.on("autoleave", async () => {
const activeChannelId = String(p._channelId ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId;
const homeChannelId = String(p._home247Channel ?? activeChannelId).replace(/\D/g, "") || activeChannelId;
const raw2 = remix.settingsMgr.getServer(guildId).get("stay_247");
const channels2 = (!raw2 || raw2 === "none")
? []
: Array.isArray(raw2)
? raw2.map(id => String(id).replace(/\D/g, "")).filter(Boolean)
: [String(raw2).replace(/\D/g, "")].filter(Boolean);
// Per-channel mode: check the mode for this specific channel
const matchChannel = channels2.includes(homeChannelId) ? homeChannelId
: channels2.includes(activeChannelId) ? activeChannelId
: null;
const mode2 = matchChannel
? get247ChannelMode(remix.settingsMgr.getServer(guildId), matchChannel)
: "off";
// Remove player from map and destroy it now that we've read the state.
remix.players.playerMap.delete(activeChannelId);
if (activeChannelId !== cleanChannelId) remix.players.playerMap.delete(cleanChannelId);
p.destroy();
if (matchChannel && (mode2 === "on" || mode2 === "auto")) {
this.scheduleSpawn(guildId, homeChannelId, this.T.rejoin247Delay, "247-autoleave");
} else {
// 24/7 is off — send inactivity message with hint to enable 247
try {
const prefix = remix.handler?.getPrefix?.(guildId) ?? "%";
const guild = remix.client.guilds.get(guildId);
const ch = guild?.channels?.find(c =>
(c.isTextBased?.() ?? c.channel_type === "TextChannel" ?? true) &&
(c.permissionsFor?.(remix.client.user)?.has?.("SendMessages") ?? true)
);
if (ch) {
const desc = remix.locale?.translate(guildId, "responses.join.autoLeaveInactive247", {
channel: `<#${activeChannelId}>`,
prefix
}) ?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on\` or \`${prefix}247 auto\`\nUse \`${prefix}247\` to view and manage all saved channels.`;
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(desc)
.toJSON();
if (typeof ch?.send === "function") ch.send({ embeds: [embed] }).catch(() => {});
}
} catch (_) {}
}
});
// ── Song announcement handler ──────────────────────────────────────────
p.on("message", (m) => {
const raw = remix.settingsMgr.getServer(guildId).get("songAnnouncements");
const disabled = raw === false || raw === 0 ||
["false", "0", "no", "off", "disable"].includes(String(raw).toLowerCase().trim());
if (disabled) return;
const guild = remix.client.guilds.get(guildId);
const serverSet = remix.settingsMgr.getServer(guildId);
const cachedChId = remix._announcementChannelCache.get(guildId)
?? serverSet.get("announcementChannelId")
?? null;
let ch = p.textChannel?.channel ?? p.textChannel ?? null;
if (typeof ch?.send !== "function") {
ch = cachedChId ? guild?.channels?.get(String(cachedChId)) : null;
}
if (cachedChId && !ch) {
remix._announcementChannelCache.delete(guildId);
}
if (!ch) {
ch = guild?.channels?.find(c =>
(c.isTextBased?.() ?? c.channel_type === "TextChannel" ?? true) &&
(c.permissionsFor?.(remix.client.user)?.has?.("SendMessages") ?? true)
);
if (ch) {
remix._announcementChannelCache.set(guildId, ch.id);
if (serverSet.get("announcementChannelId") !== ch.id) {
serverSet.set("announcementChannelId", ch.id);
}
}
}
if (typeof ch?.send === "function") {
const payload = (typeof m === "object" && Array.isArray(m?.embeds))
? m
: { embeds: [{ description: String(m), color: getGlobalColor() }] };
ch.send(payload).catch(() => {});
}
});
// ── Join channel ───────────────────────────────────────────────────────
try {
await p.join(cleanChannelId);
// Only add to playerMap once the join is confirmed successful.
remix.players.playerMap.set(cleanChannelId, p);
// Record the intended 247 home channel for this player.
p._home247Channel = cleanChannelId;
// ── Re-seed voice states for this channel ────────────────────────────
try {
const humansFound = this.gatewayHandler.reseedVoiceStatesForChannel(guildId, cleanChannelId);
if (humansFound > 0) {
logger.recovery(
`[Spawn] Re-seeded voice states for ${cleanChannelId}: ` +
`${humansFound} human(s) already present — cancelling inactivity timer.`
);
if (typeof p._stopInactivityTimer === "function") {
p._stopInactivityTimer();
}
}
} catch (reseedErr) {
logger.warn("[PlayerSpawn] Voice state reseed failed:", reseedErr?.message);
}
// ── Restore saved volume from guild settings ─────────────────────────
try {
const savedVol = remix.settingsMgr.getServer(guildId)?.get("volume");
if (savedVol !== undefined && savedVol !== null) {
const vol = Number(savedVol);
if (!isNaN(vol)) p.preferredVolume = vol / 100;
}
} catch (_) {}
logger.recovery(`[Spawn] Joined 24/7 channel ${cleanChannelId} in guild ${cleanGuildId}.`);
// Join succeeded — clear any 401 retry counters for this guild
this._guild401Retries.delete(cleanGuildId);
this._guild401Ban.delete(cleanGuildId);
} catch (e) {
remix.players.playerMap.delete(cleanChannelId);
try { p.destroy(); } catch (_) {}
logger.warn("[PlayerSpawn] Failed to join channel", cleanChannelId, "guild", guildId, e.message);
// ── 401 Unauthorized handling ─────────────────────────────────────
const is401Error = /\b401\b/.test(e.message) ||
e.message?.includes("Unauthorized") ||
e.message?.includes("no permissions to access the room") ||
e.message?.includes("signal failure: client error");
if (is401Error) {
// Bot not in guild cache — but during startup, the cache might not
// be populated yet. Same race as the pre-flight check.
if (!remix.client.guilds.has(guildId) && !remix.client.guilds.has(cleanGuildId)) {
if (this._autoJoinRunning || !this._autoJoinDone) {
logger.warn(
`[PlayerSpawn] 401 on guild ${guildId} — guild cache not populated yet (startup race). Will retry.`
);
// Schedule a retry — don't clean up
const retryCount = (this._guild401Retries.get(cleanGuildId) ?? 0) + 1;
this._guild401Retries.set(cleanGuildId, retryCount);
if (retryCount < 3) {
this.scheduleSpawn(guildId, cleanChannelId, 15_000, `401-startup-retry-${retryCount}`);
}
return;
}
// Runtime — bot was actually removed
logger.warn(
`[PlayerSpawn] 401 on guild ${guildId} — bot no longer in server. Cleaning up.`
);
this.cleanStaleGuild(guildId, "401 and bot not in guild");
return;
}
// Bot IS still in the guild — the 401 may be transient (gateway slow
// to provision voice room). Retry with exponential backoff instead of
// permanently giving up on the first failure.
const retryCount = (this._guild401Retries.get(cleanGuildId) ?? 0) + 1;
this._guild401Retries.set(cleanGuildId, retryCount);
if (retryCount >= 3) {
// After 3 consecutive 401s, ban this guild for 5 minutes to avoid
// infinite retry loops. The FluxerRevoice 45s cooldown + this ban
// prevent wasting resources on guilds where voice is truly broken.
const banDuration = 5 * 60 * 1000; // 5 minutes
this._guild401Ban.set(cleanGuildId, Date.now() + banDuration);
this._guild401Retries.delete(cleanGuildId);
logger.warn(
`[PlayerSpawn] 401 for guild ${cleanGuildId} — ` +
`${retryCount} consecutive failures. Banning for 5 minutes.`
);
return;
}
// Exponential backoff: 1st retry after 15s, 2nd after 45s
const backoffMs = retryCount === 1 ? 15_000 : 45_000;
logger.warn(
`[PlayerSpawn] 401 for guild ${cleanGuildId} — ` +
`transient? Retry ${retryCount}/3 in ${backoffMs / 1000}s.`
);
this.scheduleSpawn(guildId, cleanChannelId, backoffMs, `401-retry-${retryCount}`);
return;
}
// Non-401 error — clear the 401 retry counter for this guild since
// this was a different kind of failure.
this._guild401Retries.delete(cleanGuildId);
}
return p;
} finally {
// Always release the mutex so future spawns aren't permanently blocked.
this.pendingSpawns.delete(cleanChannelId);
}
}
// ── Auto-join on boot (24/7 only) ────────────────────────────────────────────
/**
* Called when both `botReady` and `settingsReady` are true.
* Auto-joins all 24/7 channels based on current guild settings.
* No session persistence or recovery from previous boot.
*/
async tryAutoJoin() {
if (!this.botReady || !this.settingsReady) return;
if (this._autoJoinRunning || this._autoJoinDone) return;
this._autoJoinRunning = true;
const { remix } = this;
const joinList = [];
// Collect all 24/7 channels from loaded guild settings
for (const [guildId, serverSettings] of remix.settingsMgr.guilds) {
try {
const raw = serverSettings.get("stay_247");
if (!raw || raw === "none") continue;
const channels = Array.isArray(raw)
? raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15)
: [String(raw).replace(/\D/g, "")].filter(id => id.length >= 15);
for (const chId of channels) {
const mode = get247ChannelMode(serverSettings, chId);
if (mode !== "on" && mode !== "auto") continue;
if (!remix.players.playerMap.has(chId) && !this.pendingSpawns.has(chId)) {
joinList.push({ guildId, channelId: chId });
}
}
} catch (_) {}
}
logger.recovery(
`[AutoJoin] Found ${joinList.length} 24/7 channel(s) to join.`
);
// Schedule all 24/7 spawns immediately (no stagger). The FluxerRevoice
// global join queue handles serialization — only one join is in-flight
// at a time across all guilds, with a 3s gap between each. Staggering
// here is no longer needed and just adds unnecessary delay before the
// joins start queuing.
for (let i = 0; i < joinList.length; i++) {
const { guildId, channelId } = joinList[i];
this.scheduleSpawn(guildId, channelId, 0, "247-autojoin");
}
this._autoJoinDone = true;
this._autoJoinRunning = false;
}
}
+11 -16
View File
@@ -194,10 +194,9 @@ export class FluxerRevoice extends EventEmitter {
/** @type {number} Minimum delay between ANY two joins (ms), even across guilds. /** @type {number} Minimum delay between ANY two joins (ms), even across guilds.
* This delay runs AFTER the previous join completes and BEFORE the next * This delay runs AFTER the previous join completes and BEFORE the next
* one starts, giving the Fluxer gateway time to clean up the previous * one starts, giving the Fluxer gateway time to clean up the previous
* voice session. 3 seconds is needed because the gateway's Erlang backend * voice session. 500ms is sufficient; the per-guild _guildMinJoinInterval
* needs time to process the voice state transition before a new join * provides additional safety for rapid same-guild rejoins. */
* can succeed without 401 errors. */ _globalJoinDelay = 500;
_globalJoinDelay = 3_000;
/** @type {Set<string>} Channel IDs where disconnect is expected (bot-initiated) */ /** @type {Set<string>} Channel IDs where disconnect is expected (bot-initiated) */
_intentionalDisconnects = new Set(); _intentionalDisconnects = new Set();
@@ -211,12 +210,9 @@ export class FluxerRevoice extends EventEmitter {
/** @type {number} Minimum time between guild joins (ms) — enforced on top of /** @type {number} Minimum time between guild joins (ms) — enforced on top of
* the per-join delay. If a new join is requested within this window, we * the per-join delay. If a new join is requested within this window, we
* wait the remaining time before proceeding. Increased from 7000 to 8000 * wait the remaining time before proceeding. 2s is enough with the global
* because 7000ms was insufficient to prevent 401 errors when the bot * join queue providing additional serialization. */
* re-joins a channel in the same guild quickly after a disconnect, _guildMinJoinInterval = 2000;
* especially during boot recovery when multiple guilds compete for
* gateway attention. */
_guildMinJoinInterval = 8000;
/** @type {Map<string, number>} Guild IDs that recently had a 401 error. /** @type {Map<string, number>} Guild IDs that recently had a 401 error.
* Used to add an even longer backoff before retrying joins in that guild. */ * Used to add an even longer backoff before retrying joins in that guild. */
@@ -391,9 +387,8 @@ export class FluxerRevoice extends EventEmitter {
try { existing.removeAllListeners(); } catch (_) {} try { existing.removeAllListeners(); } catch (_) {}
// 4. Brief delay to let the gateway process the leave before we rejoin. // 4. Brief delay to let the gateway process the leave before we rejoin.
// Increased from 1500ms to 2000ms to give the Erlang gateway backend // 250ms is enough since the join() operation itself adds _globalJoinDelay.
// more time to clean up the previous voice session. await new Promise(r => setTimeout(r, 250));
await new Promise(r => setTimeout(r, 2000));
} }
/** /**
@@ -558,11 +553,11 @@ export class FluxerRevoice extends EventEmitter {
if (e.message?.includes("401") || e.message?.includes("Unauthorized")) { if (e.message?.includes("401") || e.message?.includes("Unauthorized")) {
const gId = channelGuildId ?? this._resolveGuildForChannel(channelId); const gId = channelGuildId ?? this._resolveGuildForChannel(channelId);
if (gId) { if (gId) {
// Set 45-second cooldown for this guild to prevent rapid 401 retries // Set 15-second cooldown for this guild to prevent rapid 401 retries
this._guild401Cooldown.set(gId, Date.now() + 45_000); this._guild401Cooldown.set(gId, Date.now() + 15_000);
logger.warn( logger.warn(
`[FluxerRevoice] 401 error for channel ${channelId} — ` + `[FluxerRevoice] 401 error for channel ${channelId} — ` +
`setting 45s cooldown for guild ${gId}` `setting 15s cooldown for guild ${gId}`
); );
} }
} }