diff --git a/commands/stats.mjs b/commands/stats.mjs index 2358b6a..427d925 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -162,8 +162,10 @@ export async function run(message) { const lastfm = this.lastfm; const lastfmEnabled = lastfm?.enabled ?? false; + const cachedGuildCount = this.client.guilds.size; + const shared = { - guildCount: this.client.guilds.size, + guildCount: cachedGuildCount, playerCount: getLivePlayerCount(this.players.playerMap), scrobbleCount: 0, linkedUsers: 0, @@ -189,13 +191,28 @@ export async function run(message) { }); const ping = Date.now() - start; - const [users, scrobbleCount, linkedUsers] = await Promise.all([ + // Fetch the authoritative guild count from the API (same method the + // Dashboard uses for its "allServers" endpoint). This returns the + // actual number of servers the bot is in, regardless of cache state. + // Falls back to the cached count if the API call fails. + const guildCountPromise = (async () => { + try { + if (typeof this.client.user?.fetchGuilds === "function") { + const guilds = await this.client.user.fetchGuilds(); + return Array.isArray(guilds) ? guilds.length : cachedGuildCount; + } + } catch (_) { /* API unavailable — use cache */ } + return cachedGuildCount; + })(); + + const [users, scrobbleCount, linkedUsers, guildCount] = await Promise.all([ getUserCount(this.client), scrobblePromise, linkedPromise, + guildCountPromise, ]); await msg.edit({ - embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, userCount: users, scrobbleCount, linkedUsers, ping, loading: false })] + embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, guildCount, userCount: users, scrobbleCount, linkedUsers, ping, loading: false })] }).catch((err) => console.error("[stats] editEmbed failed:", err)); } \ No newline at end of file diff --git a/index.mjs b/index.mjs index 5655167..a844c49 100644 --- a/index.mjs +++ b/index.mjs @@ -745,9 +745,25 @@ export class Remix { // Handle autoleave — clean up the player map and destroy the player player.on("autoleave", () => { + // Safety guard: don't destroy 24/7 players or players with humans/queue + const mode = player._get247Mode(); + if (mode === "auto" || mode === "on") { + logger.inactivity(`[_spawnPlayer] autoleave suppressed for 24/7 ${mode} channel ${cleanChannelId} (guild ${cleanGuildId})`); + return; + } + if (player._hasHumansInChannel()) { + logger.inactivity(`[_spawnPlayer] autoleave suppressed — humans in channel ${cleanChannelId}`); + return; + } + if (player.queue?.getCurrent() || !player.queue?.isEmpty()) { + logger.inactivity(`[_spawnPlayer] autoleave suppressed — queue has songs in channel ${cleanChannelId}`); + return; + } + const activeChId = String(player._channelId ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId; const homeChId = String(player._home247Channel ?? activeChId).replace(/\D/g, "") || activeChId; this.players.playerMap.delete(activeChId); + this.players._unindexPlayer?.(cleanGuildId, activeChId); if (activeChId !== cleanChannelId) this.players.playerMap.delete(cleanChannelId); if (homeChId !== activeChId) this.players.playerMap.delete(homeChId); player.destroy(); diff --git a/src/Player.mjs b/src/Player.mjs index 7f9389e..0c1f146 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -443,8 +443,8 @@ export default class Player extends EventEmitter { * Get the 24/7 mode for this player's channel. * Returns "auto", "on", or "off". * - * %247 auto: bot stays in voice always (disconnect + reboot rejoin) - * %247 on: bot stays in voice only on reboot (not on disconnect) + * %247 auto: bot stays in voice always (never leaves, auto-rejoins on disconnect + reboot) + * %247 on: bot stays in voice always (never leaves due to inactivity, rejoins on reboot) * %247 off: bot leaves when inactive */ _get247Mode() { @@ -612,10 +612,18 @@ export default class Player extends EventEmitter { logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${mode}`); // %247 auto: bot always stays in voice, never start inactivity timer - // %247 on: bot leaves when alone, but rejoins on reboot — timer is allowed + // %247 on: bot stays in voice permanently — never start inactivity timer // %247 off: bot leaves when alone — timer is allowed - if (mode === "auto") { - logger.inactivity(`[Player] 24/7 auto mode active for guild ${this._guildId}, skipping inactivity timer`); + if (mode === "auto" || mode === "on") { + logger.inactivity(`[Player] 24/7 ${mode} mode active for guild ${this._guildId}, skipping inactivity timer`); + return; + } + + // Don't start the inactivity timer if there is a song currently playing + // or songs waiting in the queue — the bot should stay as long as there's + // music to play, even if no humans are currently in the channel. + if (this.queue?.getCurrent() || !this.queue?.isEmpty()) { + logger.inactivity(`[Player] Queue has songs for guild ${this._guildId}, skipping inactivity timer`); return; } @@ -626,8 +634,15 @@ export default class Player extends EventEmitter { logger.inactivity(`[Player] Starting inactivity timer for guild ${this._guildId} (${this._inactivityLimit / 1000}s)`); this._inactivityTimer = setTimeout(() => { - if (this._get247Mode() === "auto") { - logger.inactivity("[Player] 24/7 auto mode enabled during inactivity wait, aborting leave"); + // Re-check all conditions before leaving — they may have changed while + // the timer was running (user joined, 24/7 enabled, song queued, etc.) + const currentMode = this._get247Mode(); + if (currentMode === "auto" || currentMode === "on") { + logger.inactivity(`[Player] 24/7 ${currentMode} mode enabled during inactivity wait, aborting leave`); + return; + } + if (this.queue?.getCurrent() || !this.queue?.isEmpty()) { + logger.inactivity("[Player] Song in queue during inactivity wait, aborting leave"); return; } if (this._hasHumansInChannel()) { @@ -1231,10 +1246,19 @@ export default class Player extends EventEmitter { return; } logger.error("[Player] Voice error:", err?.message ?? err); + const mode = this._get247Mode(); this._stopMediaPlayer() .catch(() => {}) .finally(() => { - if (!this.leaving && !this._destroyed) this.emit("autoleave"); + if (this.leaving || this._destroyed) return; + // %247 on/auto: don't autoleave on voice errors — stop the media + // player but stay in the channel. The GatewayHandler will + // detect the state change and schedule a rejoin if needed. + if (mode === "auto" || mode === "on") { + logger.inactivity(`[Player] Voice error in 24/7 ${mode} mode — staying in channel, not autoleaving`); + return; + } + this.emit("autoleave"); }); }); @@ -1245,18 +1269,17 @@ export default class Player extends EventEmitter { } if (!this.leaving && !this._destroyed) { const mode = this._get247Mode(); - if (mode === "auto") { - // %247 auto: Do NOT emit autoleave on unexpected disconnect. + if (mode === "auto" || mode === "on") { + // %247 auto/on: Do NOT emit autoleave on unexpected disconnect. // The GatewayHandler will detect the bot's voice state change // and schedule a rejoin. Emitting autoleave here would cause // the player to be destroyed before the rejoin can be scheduled, // and creates a race condition where both Player.mjs AND // GatewayHandler try to handle the disconnect simultaneously. - logger.mediaplayer("[Player] Unexpected disconnect detected (24/7 auto) — stopping media player, GatewayHandler will schedule rejoin"); + logger.mediaplayer(`[Player] Unexpected disconnect detected (24/7 ${mode}) — stopping media player, GatewayHandler will schedule rejoin`); this._stopMediaPlayer().catch(() => {}); } else { - // %247 on or off: emit autoleave as normal. - // %247 on does NOT rejoin on disconnect (only on reboot). + // %247 off: emit autoleave as normal. logger.mediaplayer("[Player] Unexpected disconnect detected"); this._stopMediaPlayer() .catch(() => {}) @@ -1269,6 +1292,13 @@ export default class Player extends EventEmitter { connection.on("autoleave", () => { if (this.connection !== connection) return; + // Check 24/7 mode before forwarding the autoleave — for 24/7 channels + // the bot should never leave due to an empty room. + const mode = this._get247Mode(); + if (mode === "auto" || mode === "on") { + logger.mediaplayer(`[Player] Auto-leave suppressed for 24/7 ${mode} channel (room empty but staying)`); + return; + } logger.mediaplayer("[Player] Auto-leave triggered by FluxerVoiceConnection (room empty)"); if (!this.leaving && !this._destroyed) { this.emit("autoleave"); @@ -2103,6 +2133,17 @@ export default class Player extends EventEmitter { const room = this.connection.room; if (!room || !room.isConnected) { const cs = room?.connectionState; + const mode = this._get247Mode(); + // For 24/7 channels, don't autoleave on dead room — put the song back + // and wait for the GatewayHandler to schedule a rejoin. + if (mode === "auto" || mode === "on") { + logger.mediaplayer(`[Player] Room not connected (isConnected: ${room?.isConnected}, connectionState: ${cs}) in 24/7 ${mode} mode — deferring autoleave, waiting for rejoin.`); + if (songData) { + this.queue.data.unshift(songData); + this.queue.current = null; + } + return; + } logger.mediaplayer(`[Player] Room not connected (isConnected: ${room?.isConnected}, connectionState: ${cs}) — emitting autoleave.`); if (songData) { this.queue.data.unshift(songData); diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 592f63b..33d2cd8 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -907,6 +907,26 @@ export class PlayerManager { ? get247ChannelMode(this.settings.getServer(guildId), matchChannel) : "off"; + // ── Safety guard: re-validate before destroying ──────────────────── + // Even if autoleave was emitted, don't destroy the player if: + // 1. 24/7 mode is "on" or "auto" (bot should never leave) + // 2. Humans are still in the channel + // 3. There are songs in the queue or currently playing + // This catches cases where the autoleave event was emitted from a + // code path that didn't check these conditions (e.g. old timers). + if (mode247 === "auto" || mode247 === "on") { + logger.inactivity(`[PlayerManager] autoleave suppressed for 24/7 ${mode247} channel ${activeChannelId} (guild ${guildId})`); + return; + } + if (player._hasHumansInChannel()) { + logger.inactivity(`[PlayerManager] autoleave suppressed — humans still in channel ${activeChannelId} (guild ${guildId})`); + return; + } + if (player.queue?.getCurrent() || !player.queue?.isEmpty()) { + logger.inactivity(`[PlayerManager] autoleave suppressed — queue has songs in channel ${activeChannelId} (guild ${guildId})`); + return; + } + // Remove player from map and destroy this.playerMap.delete(activeChannelId); this._unindexPlayer(player._guildId, activeChannelId);