From 584ca05e2da556fc21ab98b2d0212c6d008934b9 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Sat, 9 May 2026 15:04:00 +0300 Subject: [PATCH] lots of stuff noo need to say it lol --- commands/leave.mjs | 6 +- commands/settings.mjs | 118 +++++++++++++----- index.mjs | 95 +++++++------- src/GatewayHandler.mjs | 14 ++- src/Player.mjs | 85 +++++++------ src/PlayerManager.mjs | 229 +++++++--------------------------- src/RecoveryManager.mjs | 232 +++++++++++++++++++---------------- src/constants/Helpers247.mjs | 69 +++++++++++ storage/defaults.json | 6 +- 9 files changed, 449 insertions(+), 405 deletions(-) create mode 100644 src/constants/Helpers247.mjs diff --git a/commands/leave.mjs b/commands/leave.mjs index e53a115..2aba05f 100644 --- a/commands/leave.mjs +++ b/commands/leave.mjs @@ -2,6 +2,7 @@ import { CommandBuilder } from "../src/CommandHandler.mjs"; import { logger } from "../src/constants/Logger.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { get247ChannelMode } from "../src/constants/Helpers247.mjs"; export const command = new CommandBuilder() .setName("leave") @@ -64,7 +65,10 @@ export async function run(msg) { : new Set([String(raw).replace(/\D/g, "")]); if (ch247.has(activeChannelId) || ch247.has(homeChannelId)) { - const mode = set?.get("stay_247_mode") ?? "auto"; + const matchChannel = ch247.has(homeChannelId) ? homeChannelId + : ch247.has(activeChannelId) ? activeChannelId + : null; + const mode = matchChannel ? get247ChannelMode(set, matchChannel) : "off"; this.markIntentionalLeave(activeChannelId); this.players.playerMap.delete(activeChannelId); if (activeChannelId !== cid) this.players.playerMap.delete(cid); diff --git a/commands/settings.mjs b/commands/settings.mjs index 5c91d16..33c6cf9 100644 --- a/commands/settings.mjs +++ b/commands/settings.mjs @@ -83,6 +83,64 @@ function getGuildName(message) { // ── 24/7 helpers ────────────────────────────────────────────────────────────── +/** + * Get the 24/7 mode for a specific channel. + * Reads from the per-channel map (stay_247_modes) first, + * falls back to the guild-wide stay_247_mode for backward compat. + * + * @param {ServerSettings} set + * @param {string} channelId Clean channel ID + * @returns {string} "on" | "auto" | "off" + */ +function get247ChannelMode(set, channelId) { + const modes = set.get("stay_247_modes"); + if (modes && typeof modes === "object" && !Array.isArray(modes)) { + const perChannel = modes[channelId]; + if (perChannel === "on" || perChannel === "auto" || perChannel === "off") return perChannel; + } + // Fallback: guild-wide mode (legacy) + const guildMode = set.get("stay_247_mode") ?? "off"; + return guildMode; +} + +/** + * Set the 24/7 mode for a specific channel. + * + * @param {ServerSettings} set + * @param {string} channelId Clean channel ID + * @param {string} mode "on" | "auto" | "off" + */ +function set247ChannelMode(set, channelId, mode) { + let modes = set.get("stay_247_modes"); + if (!modes || typeof modes !== "object" || Array.isArray(modes)) modes = {}; + modes[channelId] = mode; + set.set("stay_247_modes", modes); + // Also update guild-wide mode for backward compat with older code + set.set("stay_247_mode", mode); +} + +/** + * Remove a channel from the per-channel modes map. + * If no channels remain, clears stay_247_modes entirely. + * + * @param {ServerSettings} set + * @param {string} channelId Clean channel ID + * @param {Set} currentChannels Current set of all 247 channels for this guild + */ +function remove247ChannelMode(set, channelId, currentChannels) { + let modes = set.get("stay_247_modes"); + if (!modes || typeof modes !== "object" || Array.isArray(modes)) return; + delete modes[channelId]; + set.set("stay_247_modes", modes); + // Update guild-wide mode to match the first remaining channel, or "off" + if (currentChannels.size === 0) { + set.set("stay_247_mode", "off"); + } else { + const firstChannel = [...currentChannels][0]; + set.set("stay_247_mode", modes[firstChannel] ?? "auto"); + } +} + function get247Channels(set) { const raw = set.get("stay_247"); if (!raw || raw === "none") return new Set(); @@ -103,19 +161,28 @@ function save247Channels(set, channels) { set.set("stay_247", arr.length > 0 ? arr : "none"); } +function modeLabel(mode) { + return mode === "auto" ? "🔄 auto" : mode === "on" ? "✅ on" : "❌ off"; +} + function format247Status(set) { const channels = get247Channels(set); - const mode = set.get("stay_247_mode") ?? "off"; if (channels.size === 0) return "❌ disabled"; - const channelList = [...channels].map(id => `<#${id}>`).join(", "); - const modeLabel = mode === "auto" ? "🔄 auto" : mode === "on" ? "✅ on" : "❌ off"; - const countLabel = channels.size === 1 ? "1 channel" : `${channels.size} channels`; - return `${modeLabel} — ${countLabel}: ${channelList}`; + // Show per-channel mode for multi-voice, single mode for single channel + if (channels.size === 1) { + const chId = [...channels][0]; + const mode = get247ChannelMode(set, chId); + return `${modeLabel(mode)} — <#${chId}>`; + } + const parts = [...channels].map(id => { + const mode = get247ChannelMode(set, id); + return `<#${id}> (${modeLabel(mode)})`; + }); + return `${channels.size} channels: ${parts.join(", ")}`; } function format247Summary(set) { const channels = [...get247Channels(set)]; - const mode = set.get("stay_247_mode") ?? "off"; if (channels.length === 0) { return [ "**24/7 Mode**", @@ -124,17 +191,12 @@ function format247Summary(set) { ].join("\n"); } - const modeLabel = mode === "auto" - ? "🔄 auto" - : mode === "on" - ? "✅ on" - : "❌ off"; - - return [ - "**24/7 Mode**", - `Status: ${modeLabel}`, - `Saved channels (${channels.length}): ${channels.map(id => `<#${id}>`).join(", ")}` - ].join("\n"); + const lines = ["**24/7 Mode**"]; + for (const id of channels) { + const mode = get247ChannelMode(set, id); + lines.push(`• <#${id}> — ${modeLabel(mode)}`); + } + return lines.join("\n"); } function prettifySettingLabel(key) { @@ -177,6 +239,7 @@ async function handle247(ctx, message, value) { const id = cleanId(channelId); channels.delete(id); save247Channels(set, channels); + remove247ChannelMode(set, id, channels); ctx.markIntentionalLeave?.(id); const player = ctx.players.playerMap.get(id) ?? [...ctx.players.playerMap.values()].find(p => @@ -190,10 +253,9 @@ async function handle247(ctx, message, value) { await player.leave().catch(() => {}); player.destroy(); } - if (channels.size === 0) set.set("stay_247_mode", "off"); const remaining = [...channels]; const extra = remaining.length > 0 - ? `\nSaved channels left: ${remaining.map(ch => `<#${ch}>`).join(", ")}` + ? `\nSaved channels left: ${remaining.map(ch => `<#${ch}> (${modeLabel(get247ChannelMode(set, ch))})`).join(", ")}` : ""; return message.reply(embed(ctx.t(message, "responses.settings.247Disabled", { channel: id }) + extra)); } @@ -201,6 +263,7 @@ async function handle247(ctx, message, value) { // Not in a channel — disable all for this guild save247Channels(set, new Set()); set.set("stay_247_mode", "off"); + set.set("stay_247_modes", {}); for (const [chId, player] of [...ctx.players.playerMap.entries()]) { if (cleanId(player?._guildId ?? "") === cleanId(guildId)) { const activeChannelId = cleanId(player._channelId ?? chId); @@ -228,14 +291,13 @@ async function handle247(ctx, message, value) { const channels = get247Channels(set); channels.add(id); save247Channels(set, channels); - set.set("stay_247_mode", resolved); + // Per-channel mode: each channel gets its own on/auto setting + set247ChannelMode(set, id, resolved); - const modeLabel = resolved === "auto" - ? "**auto**" - : "**on**"; + const resolvedLabel = resolved === "auto" ? "**auto**" : "**on**"; const savedSummary = channels.size === 1 - ? `Saved channel: <#${id}>` - : `Saved channels (${channels.size}): ${[...channels].map(ch => `<#${ch}>`).join(", ")}`; + ? `Saved channel: <#${id}> (${resolvedLabel})` + : `Saved channels (${channels.size}): ${[...channels].map(ch => `<#${ch}> (${modeLabel(get247ChannelMode(set, ch))})`).join(", ")}`; if ( ctx.players.playerMap.has(id) || @@ -243,12 +305,12 @@ async function handle247(ctx, message, value) { cleanId(p?._channelId ?? "") === id && cleanId(p?._guildId ?? "") === cleanId(guildId) ) ) { - return message.reply(embed(ctx.t(message, "responses.settings.247Set", { mode: modeLabel, channel: id, summary: savedSummary }))); + return message.reply(embed(ctx.t(message, "responses.settings.247Set", { mode: resolvedLabel, channel: id, summary: savedSummary }))); } try { await ctx._spawnPlayer(guildId, id); - return message.reply(embed(ctx.t(message, "responses.settings.247Joined", { mode: modeLabel, channel: id, summary: savedSummary }))); + return message.reply(embed(ctx.t(message, "responses.settings.247Joined", { mode: resolvedLabel, channel: id, summary: savedSummary }))); } catch (e) { return message.reply(embed(ctx.t(message, "responses.settings.247JoinFailed", { channel: id, error: e.message, summary: savedSummary }))); } @@ -519,7 +581,7 @@ export async function run(message, data) { // guild.iconURL() is a method that does not exist on @fluxerjs/core Guild objects. const rawGuild = message.message?.guild; const iconUrl = rawGuild?.icon - ? `https://fluxerusercontent.com/icons/${rawGuild.id}/${rawGuild.icon}.webp` + ? `https://cdn.fluxer.app/icons/${rawGuild.id}/${rawGuild.icon}.webp` : null; const lines = Object.entries(d) diff --git a/index.mjs b/index.mjs index 810604f..006103f 100644 --- a/index.mjs +++ b/index.mjs @@ -77,19 +77,6 @@ export class Remix { client.setMaxListeners(50); this.client = client; - // ── VoiceManager — MUST be created BEFORE login ────────────────────────── - // Per Fluxer.js docs: "Create a VoiceManager before login so it receives - // VoiceStatesSync from READY/GUILD_CREATE. This lets the manager see users - // already in voice when the bot starts." - // If created after login, the VoiceStatesSync events are already fired and - // missed — the bot won't know who's in voice channels after a restart. - try { - getVoiceManager(client); - // VoiceManager will auto-register for VoiceStatesSync / VoiceStateUpdate - } catch (e) { - logger.warn("[VoiceManager] Pre-login init failed:", e.message); - } - // ── Message & Settings handlers ────────────────────────────────────────── const messages = new MessageHandler(this.client); this.messages = messages; @@ -119,7 +106,7 @@ export class Remix { false, { icon_url: msg.channel.channel.guild?.icon - ? `https://fluxerusercontent.com/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.icon}.webp` + ? `https://cdn.fluxer.app/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.icon}.webp` : null, title: msg.channel.channel.guild?.name ?? null, } @@ -150,6 +137,10 @@ export class Remix { // VoiceStateUpdate). this.gatewayHandler = new GatewayHandler(this, this.recoveryManager); + // 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 // are active before the first Ready event fires. this.gatewayHandler.setupEventHandlers(); @@ -179,6 +170,25 @@ export class Remix { `[settings] Cleaned stay_247 for guild ${guildId}: ${JSON.stringify(val)} → ${JSON.stringify(newVal)}` ); } + + // ── Migrate guild-wide stay_247_mode → per-channel stay_247_modes ── + // If stay_247_modes doesn't exist yet but stay_247_mode does, create + // the per-channel map from the guild-wide mode so all channels inherit + // the same mode (backward compatible). + const modesMap = serverSettings.get("stay_247_modes"); + if (!modesMap || typeof modesMap !== "object") { + const guildMode = serverSettings.get("stay_247_mode") ?? "off"; + if (guildMode && guildMode !== "off" && cleaned.length > 0) { + const newModes = {}; + for (const chId of cleaned) { + newModes[chId] = guildMode; + } + serverSettings.set("stay_247_modes", newModes); + logger.settings( + `[settings] Migrated stay_247_mode → stay_247_modes for guild ${guildId}: ${guildMode} → ${JSON.stringify(newModes)}` + ); + } + } } this.recoveryManager.settingsReady = true; this.recoveryManager.tryAutoJoin(); @@ -189,13 +199,10 @@ export class Remix { logger.player("Logged in as " + (client.user?.username ?? "bot")); try { - // VoiceManager was created before login to catch VoiceStatesSync. - // Ensure it's accessible and log its state. - const vm = getVoiceManager(client); - const guildCount = vm.voiceStates?.size ?? 0; - logger.player(`VoiceManager ready (${guildCount} guild voice-state maps).`); + getVoiceManager(client); + logger.player("VoiceManager initialized."); } catch (e) { - logger.warn("[VoiceManager] Ready check failed:", e.message); + logger.warn("[VoiceManager] Init failed:", e.message); } const botId = client.user?.id ?? "0"; @@ -250,7 +257,6 @@ export class Remix { timers: this.T, }); this.players.observedVoiceUsers = this.observedVoiceUsers; - this.players.observedVoiceBots = this.observedVoiceBots; // ── Periodic alone-check ─────────────────────────────────────────────────── const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval; @@ -280,8 +286,6 @@ export class Remix { if (player._is247Enabled()) continue; let hasHuman = false; - - // Source 1: observedVoiceUsers map (seeded from READY/GUILD_CREATE + VOICE_STATE_UPDATE) for (const [, info] of this.observedVoiceUsers) { const infoChannel = String(info.channelId ?? "").replace(/\D/g, ""); const infoGuild = String(info.guildId ?? "").replace(/\D/g, ""); @@ -291,22 +295,32 @@ export class Remix { } } - // Source 2: VoiceManager.voiceStates (populated from VoiceStatesSync events) - // This is the authoritative source per Fluxer.js docs. It catches users - // who were already in voice when the bot started, even if - // observedVoiceUsers hasn't been fully seeded yet. + // Fallback: check guild voice_states cache if observedVoiceUsers + // didn't find anyone (can happen after bot restart before reseed). if (!hasHuman) { try { - const vm = getVoiceManager(this.client); - const participants = vm.listParticipantsInChannel?.(guildId, channelId); - if (participants && participants.length > 0) { - // Filter out bots — listParticipantsInChannel returns ALL users - const guild = this.client.guilds.get(guildId); - for (const uid of participants) { - const member = guild?.members?.get?.(uid); - if (!member?.user?.bot) { - hasHuman = true; - break; + const guild = this.client?.guilds?.get?.(cleanGuildId); + const voiceStates = guild?.voice_states ?? guild?.voiceStates; + if (voiceStates) { + const entries = Array.isArray(voiceStates) + ? voiceStates + : typeof voiceStates.values === "function" + ? [...voiceStates.values()] + : Object.values(voiceStates); + for (const state of entries) { + const stateChannel = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, ""); + if (stateChannel === cleanChanId) { + const stateUserId = state?.userId ?? state?.user_id ?? state?.id; + const member = guild?.members?.get?.(stateUserId); + const isBot = member?.user?.bot ?? state?.member?.user?.bot ?? false; + if (!isBot) { + hasHuman = true; + // Also update observedVoiceUsers so future checks are fast + if (stateUserId) { + this.observedVoiceUsers.set(stateUserId, { channelId: cleanChanId, guildId: cleanGuildId }); + } + break; + } } } } @@ -616,15 +630,12 @@ export class Remix { name: guild.name, id: guild.id, icon: guild.icon - ? `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp` + ? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp` : null, description: guild.description ?? null, ownerId: guild.ownerId ?? null, - channelIds: guild.channels && typeof guild.channels.keys === "function" - ? [...guild.channels.keys()] - : [], voiceChannels: guild.channels - .filter(c => c.isVoice?.() ?? (c.type === 2) ?? false) + .filter(c => c.isVoiceBased?.() ?? false) .map(c => { // Build voice participants list for this channel const voiceParticipants = []; diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index 59fbe10..53cb7c6 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -1,6 +1,7 @@ import { Events, GatewayOpcodes } from "@fluxerjs/core"; import { logger } from "./constants/Logger.mjs"; import { ServerSettings } from "./Settings.mjs"; +import { get247ChannelMode } from "./constants/Helpers247.mjs"; import mysql from "mysql2"; /** @@ -481,16 +482,18 @@ export class GatewayHandler { const set = remix.settingsMgr.getServer(guildId); if (set) { const raw = set.get("stay_247"); - const mode = set.get("stay_247_mode") ?? "auto"; - if (raw && raw !== "none" && (mode === "on" || mode === "auto")) { + 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}` + `[GuildCreate] Late-arriving guild ${guildId} — scheduling 24/7 spawn for channel ${chId} (mode ${mode})` ); this.recoveryManager.scheduleSpawn(guildId, chId, this.T.rejoin247Delay, null, "guild-create-247"); } @@ -818,7 +821,8 @@ export class GatewayHandler { ? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15)) : new Set(); if (channels.has(cleanOld)) { - const mode = set.get("stay_247_mode") ?? "auto"; + // Per-channel mode: check the mode for this specific channel + const mode = get247ChannelMode(set, cleanOld); if (mode === "on" || mode === "auto") { // For multi-voice guilds, match the specific player by channel ID // instead of skipping recovery entirely (was: if multiVoiceGuild return) @@ -836,7 +840,7 @@ export class GatewayHandler { this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, null, "gateway-disconnect"); } } else { - logger.voice247(`[247] stay_247_mode='${mode}' — not rejoining.`); + logger.voice247(`[247] Channel ${cleanOld} mode='${mode}' — not rejoining.`); channels.delete(cleanOld); set.set("stay_247", channels.size > 0 ? [...channels] : "none"); } diff --git a/src/Player.mjs b/src/Player.mjs index f804db1..fa48fd1 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -19,6 +19,7 @@ import https from "node:https"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "./MessageHandler.mjs"; import { logger } from "./constants/Logger.mjs"; +import { get247ChannelMode } from "./constants/Helpers247.mjs"; import { PROVIDER_NAMES } from "./constants/providers.mjs"; /** Emit a plain embed payload so listeners can send it directly */ @@ -341,6 +342,7 @@ export default class Player extends EventEmitter { // Inactivity timeout _inactivityTimer = null; _inactivityLimit = 3 * 60 * 1000; // 3 min default + _pendingInactivityCheck = false; // Guard to prevent race between join() timer and reseed // Join mutex — prevents concurrent join() calls from racing each other _isJoining = false; @@ -414,8 +416,6 @@ export default class Player extends EventEmitter { if (!set?.get) return false; const raw = set.get("stay_247"); if (!raw || raw === "none") return false; - const mode = set.get("stay_247_mode") ?? "auto"; - if (mode !== "on" && mode !== "auto") return false; const channels = Array.isArray(raw) ? raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean) @@ -430,9 +430,15 @@ export default class Player extends EventEmitter { : null; const currentChannel = String(this._channelId ?? "").replace(/\D/g, ""); - // Check home channel first (most reliable), then current channel - // (covers players created via join command that have no home set). - return channels.includes(homeChannel) || channels.includes(currentChannel); + // Determine which channel to check the mode for + const matchChannel = channels.includes(homeChannel) ? homeChannel + : channels.includes(currentChannel) ? currentChannel + : null; + if (!matchChannel) return false; + + // Per-channel mode lookup: each channel can have its own on/auto/off + const mode = get247ChannelMode(set, matchChannel); + return mode === "on" || mode === "auto"; }; if (this.settingsMgr?.getServer) return checkSettings(this.settingsMgr.getServer(this._guildId)); @@ -604,43 +610,36 @@ export default class Player extends EventEmitter { if (!this._channelId || !this._guildId) return false; const cleanChan = String(this._channelId).replace(/\D/g, ""); const cleanGuild = String(this._guildId).replace(/\D/g, ""); - - // ── Source 1: observedVoiceUsers map (fast path) ──────────────────────── try { const voiceUsers = this._observedVoiceUsers; if (voiceUsers) { - for (const [, info] of voiceUsers) { + for ( const [, info] of voiceUsers) { if ( String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild && String(info.channelId ?? "").replace(/\D/g, "") === cleanChan ) return true; } - // Don't return false here — fall through to VoiceManager check. - // After a bot restart, observedVoiceUsers may be empty if the - // GUILD_CREATE purge bug hasn't been fully resolved, but VoiceManager - // receives VoiceStatesSync events and has the correct data. + // Don't return false here — fall through to guild voice_states + // fallback in case observedVoiceUsers hasn't been populated yet + // (e.g., right after bot restart before reseed completes). } } catch (_) {} - - // ── Source 2: VoiceManager.voiceStates (authoritative per Fluxer.js docs) ── try { - const vm = getVoiceManager(this.client); - const participants = vm?.listParticipantsInChannel?.(cleanGuild, cleanChan); - if (participants && participants.length > 0) { - const guild = this.client?.guilds?.get?.(this._guildId); - for (const uid of participants) { - const member = guild?.members?.get?.(uid); - if (!member?.user?.bot) return true; + // @fluxerjs channels do NOT have a .members property. + // Use the guild's member manager and filter by voice state instead. + const guild = this.client?.guilds?.get?.(this._guildId); + if (guild?.members) { + for (const member of guild.members.values()) { + // GuildMember doesn't expose voice channelId directly in @fluxerjs, + // so fall through to the voice_states raw data check below. + if (!member?.user?.bot) { + // We can't determine channel from member alone — skip here + // and rely on _observedVoiceUsers or voice_states instead. + } } } - } catch (_) {} - - // ── Source 3: guild.voice_states (legacy fallback) ────────────────────── - // Fluxer.js Guild does NOT normally have a voice_states property, but - // check anyway for forward compatibility. - try { - const guild = this.client?.guilds?.get?.(this._guildId); - const voiceStates = guild?.voice_states ?? guild?.voiceStates; + // Fallback: iterate raw voice_states on the guild object. + const voiceStates = guild?.voice_states; if (voiceStates) { const entries = Array.isArray(voiceStates) ? voiceStates @@ -651,6 +650,7 @@ export default class Player extends EventEmitter { const stateChannelId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, ""); if (stateChannelId === cleanChan) { const userId = String(state?.userId ?? state?.user_id ?? ""); + // Check if user is a bot — look up via members or observedVoiceUsers const member = guild?.members?.get?.(userId); const isBot = member?.user?.bot ?? false; if (!isBot) return true; @@ -658,7 +658,6 @@ export default class Player extends EventEmitter { } } } catch (_) {} - return false; } @@ -695,6 +694,12 @@ export default class Player extends EventEmitter { } _stopInactivityTimer() { + // Also cancel any pending inactivity check that Player.join() scheduled. + // This is important after recovery: reseedVoiceStatesForChannel() calls + // _stopInactivityTimer() when it finds humans in the channel, but + // Player.join() may have already scheduled a 3-second delayed check. + // Clearing the flag prevents that delayed check from restarting the timer. + this._pendingInactivityCheck = false; if (this._inactivityTimer) { logger.inactivity(`[Player] Stopping inactivity timer for guild ${this._guildId}`); clearTimeout(this._inactivityTimer); @@ -1315,16 +1320,20 @@ export default class Player extends EventEmitter { if (!this.queue.isEmpty() && !this.queue.getCurrent()) { this.playNext(); } else if (this.queue.isEmpty()) { - // Only start inactivity timer if no humans are in the channel. - // After a bot restart, humans may already be in the channel — don't - // start a timer that would cause the bot to leave immediately. + // Delay the inactivity timer start to give the caller (e.g. RecoveryManager.spawnPlayer) + // time to re-seed voice states and check for humans already in the channel. + // The reseed will call _stopInactivityTimer() if humans are found, which + // sets this._inactivityTimer = null. When this callback fires, it checks + // whether the timer was cancelled (by checking if _inactivityTimer is null) + // before starting a new one. + this._pendingInactivityCheck = true; setTimeout(() => { + // If the inactivity timer was stopped between scheduling and now (e.g. + // by reseedVoiceStatesForChannel finding humans), don't restart it. + if (!this._pendingInactivityCheck) return; + this._pendingInactivityCheck = false; if (this.queue.isEmpty() && !this.queue.getCurrent()) { - if (this._hasHumansInChannel()) { - logger.inactivity(`[Player] Humans present after join — skipping inactivity timer.`); - } else { - this._startInactivityTimer(); - } + this._startInactivityTimer(); } }, 3000); } diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index d6eb598..194ea03 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -11,6 +11,7 @@ import { Message } from "./MessageHandler.mjs"; import { SettingsManager } from "./Settings.mjs"; import { Utils } from "./Utils.mjs"; import { logger } from "./constants/Logger.mjs"; +import { get247ChannelMode } from "./constants/Helpers247.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getVoiceManager } from "@fluxerjs/voice"; import { getGlobalColor } from "./MessageHandler.mjs"; @@ -167,88 +168,34 @@ export class PlayerManager { // Broadcast user list changes to the global :users channel when // someone joins or leaves the player's voice channel. - // - // CRITICAL: After a bot reload, guild.voice_states may not yet contain all - // users who are in the channel (only the bot's own state may be present). - // The observedVoiceUsers map is seeded from READY/GUILD_CREATE and IS - // reliable — so we use it as a fallback to ensure all users are announced. const sendUserUpdates = (eventType) => { if (!this.dashboard?.enabled) return; const channelId = getPlayerChannelId(player, context.channelId); - const guildId = cleanId(player._guildId ?? context.guildId); const channel = player.client?.channels?.get(channelId); - const guild = player.client?.guilds?.get(guildId); - const sentUserIds = new Set(); // Deduplicate across both sources - - // ── Source 1: guild.voice_states (real-time Discord data) ────────── - if (guild) { - const voiceStates = guild.voice_states ?? guild.voiceStates ?? null; - if (voiceStates) { - const entries = Array.isArray(voiceStates) - ? voiceStates - : typeof voiceStates.values === "function" - ? [...voiceStates.values()] - : Object.values(voiceStates); - for (const state of entries) { - if (!state?.channelId && !state?.channel_id) continue; - const stateChannelId = cleanId(state.channelId ?? state.channel_id); - if (stateChannelId !== channelId) continue; - const userId = String(state.userId ?? state.user_id ?? ""); - if (!userId) continue; - const member = guild.members?.get?.(userId); - if (!member?.user || member.user?.bot) continue; - sentUserIds.add(userId); - emit(eventType, member.user.id); - this.dashboard.userUpdate({ - type: eventType, - guildId, - channelId, - }, member.user); - } - } - } - - // ── Source 2: observedVoiceUsers (seeded from READY/GUILD_CREATE) ── - // This catches users who were already in the channel when the bot - // reloaded but whose voice states aren't in guild.voice_states yet. - // After a bot restart, guild.voice_states may only contain the bot's - // own voice state, while observedVoiceUsers was populated from the - // READY payload and contains ALL humans who were already in voice. - if (eventType === "join" && this.observedVoiceUsers) { - const botUserId = player.client?.user?.id; - for (const [mapUserId, info] of this.observedVoiceUsers) { - if (sentUserIds.has(mapUserId)) continue; // Already sent from voice_states - const infoChannelId = cleanId(info.channelId ?? ""); - const infoGuildId = cleanId(info.guildId ?? ""); - if (infoChannelId !== channelId || infoGuildId !== guildId) continue; - // Skip the bot itself — it's not a "user" to announce - if (botUserId && String(mapUserId) === String(botUserId)) continue; - // Skip bots (check observedVoiceBots if available) - const botKey = `${infoGuildId}:${mapUserId}`; - if (this.observedVoiceBots?.has?.(botKey)) continue; - sentUserIds.add(mapUserId); - // Try to get user object from cache first, then fetch asynchronously - const cachedUser = player.client?.users?.get?.(mapUserId); - emit(eventType, String(mapUserId)); - if (cachedUser) { - this.dashboard.userUpdate({ - type: eventType, - guildId, - channelId, - }, cachedUser); - } else { - // User not in cache — fetch async and send update when available - player.client?.users?.fetch?.(mapUserId)?.then?.((userObj) => { - if (userObj) { - this.dashboard.userUpdate({ - type: eventType, - guildId, - channelId, - }, userObj); - } - })?.catch?.(() => {}); - } - } + const guild = player.client?.guilds?.get(cleanId(player._guildId ?? context.guildId)); + if (!guild) return; + const voiceStates = guild.voice_states ?? guild.voiceStates ?? null; + if (!voiceStates) return; + const entries = Array.isArray(voiceStates) + ? voiceStates + : typeof voiceStates.values === "function" + ? [...voiceStates.values()] + : Object.values(voiceStates); + for (const state of entries) { + if (!state?.channelId && !state?.channel_id) continue; + const stateChannelId = cleanId(state.channelId ?? state.channel_id); + if (stateChannelId !== channelId) continue; + const member = guild.members?.get?.(state.userId ?? state.user_id); + if (!member?.user || member.user?.bot) continue; + // Send per-player channel "join"/"leave" event with just the user ID + // (matching Stoat format where data = userId string) + emit(eventType, member.user.id); + // Also send global user update + this.dashboard.userUpdate({ + type: eventType, + guildId: cleanId(player._guildId ?? context.guildId), + channelId, + }, member.user); } }; @@ -377,84 +324,6 @@ export class PlayerManager { return player; } - /** - * Safely send a message to a text channel. - * - * In Fluxer.js, VoiceChannel does NOT have a .send() method — only - * TextChannel and DMChannel do. If player.textChannel is a voice - * channel (or any object without .send()), we fall back to - * client.channels.send(channelId, payload) which works on any - * channel type. - * - * @param {Object} ch - Channel object (player.textChannel) - * @param {Object} payload - Message payload (embed, content, etc.) - * @returns {Promise} - */ - async _sendToTextChannel(ch, payload) { - // ── Check if the channel is actually a text channel ──────────────── - // Fluxer.js voice channels have a .send() method that throws - // CANNOT_SEND_MESSAGES_IN_NON_TEXT_CHANNEL when called. We need to - // detect this BEFORE calling .send() and fall back to a real text - // channel from the same guild. - const isTextChannel = (c) => { - if (!c) return false; - // type 0 = text channel in Fluxer/Discord; type 2 = voice; type 13 = stage - if (c.type != null) return c.type === 0 || c.type === 5 || c.type === 13; - // isText() method if available - if (typeof c.isText === "function") return c.isText(); - // If the channel has isVoice() and it returns true, it's NOT a text channel - if (typeof c.isVoice === "function" && c.isVoice()) return false; - return false; - }; - - // Method 1: channel.send() — only if it's a real text channel - if (ch && isTextChannel(ch) && typeof ch.send === "function") { - try { - return await ch.send(payload); - } catch (e) { - // Send failed even though we thought it was a text channel — - // fall through to the guild text channel search below - logger.warn("[PlayerManager] _sendToTextChannel: send() failed on type-0 channel:", e.message); - } - } - - // Method 2: Find a suitable text channel from the same guild - const channelId = ch?.id ?? ch?._id; - const guildId = ch?.guildId ?? ch?.guild?.id ?? ch?.server_id ?? ch?.serverId; - - if (guildId && this.commands?.client) { - const guild = this.commands.client.guilds.get(guildId); - if (guild?.channels) { - const channelValues = typeof guild.channels.values === "function" - ? [...guild.channels.values()] - : Array.isArray(guild.channels) ? guild.channels : Object.values(guild.channels); - - // Prefer: system channel > first text channel the bot can send to - const sysCh = guild.systemChannelId - ? channelValues.find(c => (c.id ?? c._id) === guild.systemChannelId) - : null; - if (sysCh && isTextChannel(sysCh) && typeof sysCh.send === "function") { - try { return await sysCh.send(payload); } catch (_) {} - } - - // Fall back to the first text channel - const textCh = channelValues.find(c => isTextChannel(c)); - if (textCh && typeof textCh.send === "function") { - try { return await textCh.send(payload); } catch (_) {} - } - } - } - - // Method 3: client.channels.send(id, payload) — last resort - if (channelId && this.commands?.client?.channels?.send) { - try { - return await this.commands.client.channels.send(channelId, payload); - } catch (_) {} - } - - logger.warn("[PlayerManager] _sendToTextChannel: no valid text channel found for guild", guildId ?? channelId ?? "(unknown)"); - } - /** * Translate a locale key using the message's guild locale. * @param {Object} message @@ -833,19 +702,16 @@ export class PlayerManager { guildId: cleanId(channel.guildId ?? getMessageGuildId(message)), }); - player.on("autoleave", async () => { + player.on("autoleave", () => { const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId; const homeChannelId = cleanId(player._home247Channel) || activeChannelId; const ch = player.textChannel; const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch })); - // Check 24/7 settings for this channel + // Check 24/7 settings for this channel (per-channel mode) const raw247 = (() => { try { return this.settings.getServer(guildId)?.get("stay_247"); } catch (_) { return null; } })(); - const mode247 = (() => { - try { return this.settings.getServer(guildId)?.get("stay_247_mode") ?? "off"; } catch (_) { return "off"; } - })(); const isIn247List = (() => { if (!raw247 || raw247 === "none") return false; const channels = Array.isArray(raw247) @@ -854,6 +720,16 @@ export class PlayerManager { return channels.includes(homeChannelId) || channels.includes(activeChannelId); })(); + // Per-channel mode: check the mode for this specific channel + const matchChannel = isIn247List + ? (channels247list => channels247list.includes(homeChannelId) ? homeChannelId : activeChannelId)( + Array.isArray(raw247) ? raw247.map(id => String(id).replace(/\D/g, "")) : [String(raw247).replace(/\D/g, "")] + ) + : null; + const mode247 = matchChannel + ? get247ChannelMode(this.settings.getServer(guildId), matchChannel) + : "off"; + // Remove player from map and destroy this.playerMap.delete(activeChannelId); if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId); @@ -864,7 +740,7 @@ export class PlayerManager { // 24/7 is active — rejoin after a short delay (same as RecoveryManager.spawnPlayer autoleave) const delay = this.timers?.rejoin247Delay ?? 3000; if (this.spawnPlayer) { - logger.recovery(`[AutoLeave] 24/7 rejoin scheduled for ${homeChannelId} in ${delay}ms`); + logger.recovery(`[AutoLeave] 24/7 rejoin scheduled for ${homeChannelId} (mode ${mode247}) in ${delay}ms`); setTimeout(() => { this.spawnPlayer(guildId, homeChannelId, 0, null, "initplayer-autoleave").catch(e => logger.warn("[AutoLeave] 24/7 rejoin failed for", homeChannelId, e.message) @@ -878,44 +754,29 @@ export class PlayerManager { })(); const desc = this.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/auto\``; - try { - await this._sendToTextChannel(ch, mkEmbed(desc)); - } catch (e) { - logger.warn("[PlayerManager] autoleave send failed:", e.message); - } + if (typeof ch?.send === "function") ch.send(mkEmbed(desc)); } }); player.on("leave", () => {}); - player.on("message", async (m) => { + player.on("message", (m) => { const ch = player.textChannel; const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch })); const raw = this.settings.getServer(guildId)?.get("songAnnouncements"); const disabled = raw === false || raw === 0 || ["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim()); if (disabled) return; - try { - await this._sendToTextChannel(ch, typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)); - } catch (e) { - logger.warn("[PlayerManager] message send failed:", e.message); - } + if (typeof ch?.send === "function") ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)); }); this.playerMap.set(cleanChannelId, player); (async () => { - let statusMsg; - try { - statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining"))); - } catch (e) { - logger.warn("[PlayerManager] statusMsg reply failed:", e.message); - } + const statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining"))); try { await player.join(cid); - if (statusMsg?.edit) { - try { await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid }))); } catch (_) {} - } + await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid }))); const guildId = cleanId(channel.guildId ?? getMessageGuildId(message)); if (guildId) { @@ -939,9 +800,7 @@ export class PlayerManager { } else { errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message }); } - if (statusMsg?.edit) { - try { await statusMsg.edit(mkEmbed(errorMsg)); } catch (_) {} - } + await statusMsg.edit(mkEmbed(errorMsg)).catch(() => {}); this.playerMap.delete(cleanChannelId); player.destroy(); } diff --git a/src/RecoveryManager.mjs b/src/RecoveryManager.mjs index fa5105b..c71f352 100644 --- a/src/RecoveryManager.mjs +++ b/src/RecoveryManager.mjs @@ -1,9 +1,9 @@ import * as fs from "fs"; import { logger } from "./constants/Logger.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getVoiceManager } from "@fluxerjs/voice"; import { getGlobalColor } from "./MessageHandler.mjs"; import Player from "./Player.mjs"; +import { get247ChannelMode } from "./constants/Helpers247.mjs"; /** * RecoveryManager — handles session persistence, boot recovery, 24/7 auto-join, @@ -44,11 +44,24 @@ export class RecoveryManager { this.botReady = false; this.settingsReady = false; + // ── Auto-join guard ─────────────────────────────────────────────────────── + // Prevents concurrent tryAutoJoin() calls. Both settings "ready" and + // Events.Ready can trigger tryAutoJoin(); without this guard, two calls + // could overlap and attempt to spawn duplicate players. + this._autoJoinRunning = false; + this._autoJoinDone = false; + // ── Expose convenience methods on the Remix instance ────────────────────── // These are referenced by the shutdown hooks and dashboard. remix._buildRecoveryState = () => this.buildRecoveryState(); remix._writeRecoveryState = (state, label) => this.writeRecoveryState(state, label); remix._spawnPlayer = this.spawnPlayer.bind(this); + + // ── GatewayHandler reference (set after construction) ──────────────────── + // RecoveryManager is created before GatewayHandler, so we can't pass it + // in the constructor. Instead, index.mjs sets this reference after both + // objects are constructed. + this.gatewayHandler = null; } // ── Utility helpers ────────────────────────────────────────────────────────── @@ -76,11 +89,21 @@ export class RecoveryManager { const channelId = this.normalizeChannelId(player._channelId ?? channelKey); if (!guildId || !channelId) continue; - // ── Skip 24/7 channels ─────────────────────────────────────────── - // 24/7 on/auto already handles rejoin on boot via tryAutoJoin() which - // reads the stay_247 setting from MySQL. No need to save/restore - // these sessions in recovery.json — that's only for regular voice - // sessions where users had active queues. + // ── Save ALL active sessions including 24/7 ────────────────────── + // Previously, 24/7 channels were skipped because tryAutoJoin() + // handles reconnection on boot. However, this meant queue data + // (current track, queue, loop state) was lost on restart. + // Now we save 24/7 channels too, with their mode stored in the + // recovery data so tryAutoJoin() can restore both the connection + // and the music state. + + const dedupeKey = `${guildId}:${channelId}`; + if (seen.has(dedupeKey)) continue; + seen.add(dedupeKey); + + // Determine if this is a 24/7 channel and get its per-channel mode + let is247 = false; + let mode247 = null; try { const set = remix.settingsMgr.getServer(guildId); if (set) { @@ -91,17 +114,13 @@ export class RecoveryManager { ? raw247.map(id => this.normalizeChannelId(id)).filter(Boolean) : [this.normalizeChannelId(raw247)].filter(Boolean); if (channels247.includes(channelId) || channels247.includes(homeChannel)) { - logger.recovery(`[Recovery] Skipping 24/7 channel ${channelId} — auto-join handles this on boot.`); - continue; + is247 = true; + mode247 = get247ChannelMode(set, homeChannel || channelId); } } } } catch (_) {} - const dedupeKey = `${guildId}:${channelId}`; - if (seen.has(dedupeKey)) continue; - seen.add(dedupeKey); - const current = player.queue.getCurrent(); const queueData = player.queue.getQueue(); const tracksToSave = []; @@ -117,6 +136,8 @@ export class RecoveryManager { loopQueue: !!player.queue.loop, loopSong: !!player.queue.songLoop, preferredVolume: player.preferredVolume ?? 1, + is247, + mode247, // "on" | "auto" | null savedAt: Date.now(), }); } catch (e) { @@ -277,14 +298,35 @@ export class RecoveryManager { // Only enforce 24/7 check if we are NOT recovering from a reboot if (!recoveryData) { - const set = remix.settingsMgr.getServer(guildId); - const raw = set.get("stay_247"); - if (!raw || raw === "none") return; + // Try the guildId as-is first, then the cleaned version. + // The settingsMgr Map key might differ from the guildId format + // passed in (e.g. string vs number, or cleaned vs raw). + 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") { + // Diagnostic: log why we're skipping + logger.recovery( + `[PlayerSpawn] Skipping 24/7 channel ${cleanChannelId} in guild ${guildId}: ` + + `stay_247=${JSON.stringify(raw)}. ` + + `SettingsMgr has this guild: ${remix.settingsMgr.guilds.has(guildId)}` + ); + 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)) return; + 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. @@ -297,11 +339,10 @@ export class RecoveryManager { try { channel = await remix.client.channels.fetch(cleanChannelId); } catch (e) { - logger.warn("[PlayerSpawn] Could not fetch channel", cleanChannelId, e.message); - return; + throw new Error(`Could not fetch channel ${cleanChannelId}: ${e.message}`); } } - if (!channel) { logger.warn("[PlayerSpawn] Channel not found:", cleanChannelId); return; } + if (!channel) { throw new Error(`Channel not found: ${cleanChannelId}`); } remix.client.channels.set(cleanChannelId, channel); const p = new Player(remix.config.token, { @@ -325,17 +366,22 @@ export class RecoveryManager { : Array.isArray(raw2) ? raw2.map(id => String(id).replace(/\D/g, "")).filter(Boolean) : [String(raw2).replace(/\D/g, "")].filter(Boolean); - const mode2 = remix.settingsMgr.getServer(guildId).get("stay_247_mode") ?? "auto"; + + // 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 (channels2.includes(homeChannelId) || channels2.includes(activeChannelId)) { - if (mode2 === "on" || mode2 === "auto") { - this.scheduleSpawn(guildId, homeChannelId, this.T.rejoin247Delay, null, "247-autoleave"); - } + if (matchChannel && (mode2 === "on" || mode2 === "auto")) { + this.scheduleSpawn(guildId, homeChannelId, this.T.rejoin247Delay, null, "247-autoleave"); } else { // 24/7 is off — send inactivity message with hint to enable 247 try { @@ -353,7 +399,7 @@ export class RecoveryManager { `If you want me to stay in voice, use \`${prefix}247 on/auto\`` ) .toJSON(); - ch.send({ embeds: [embed] }).catch(() => {}); + if (typeof ch?.send === "function") ch.send({ embeds: [embed] }).catch(() => {}); } } catch (_) {} } @@ -387,7 +433,7 @@ export class RecoveryManager { } } } - ch?.send({ embeds: [{ description: String(m), color: getGlobalColor() }] }).catch(() => {}); + if (typeof ch?.send === "function") ch.send({ embeds: [{ description: String(m), color: getGlobalColor() }] }).catch(() => {}); }); // ── Join channel ─────────────────────────────────────────────────────── @@ -402,6 +448,30 @@ export class RecoveryManager { // Record the intended 247 home channel for this player. p._home247Channel = cleanChannelId; + // ── Re-seed voice states for this channel ──────────────────────────── + // After joining, the bot needs to know who's already in the channel. + // The initial seedVoiceStatesFromGuilds() may have missed users because + // the guild cache wasn't fully populated at boot, or because Discord + // sends voice states during GUILD_CREATE before the bot processes them. + // This re-reads the guild's voice_states cache and updates the + // observedVoiceUsers map so the bot detects humans already present. + try { + const humansFound = this.gatewayHandler.reseedVoiceStatesForChannel(guildId, cleanChannelId); + if (humansFound > 0) { + logger.recovery( + `[Recovery] Re-seeded voice states for ${cleanChannelId}: ` + + `${humansFound} human(s) already present — cancelling inactivity timer.` + ); + // Humans are present — stop any inactivity timer that Player.join() + // may have started (it starts one if the queue is empty). + if (typeof p._stopInactivityTimer === "function") { + p._stopInactivityTimer(); + } + } + } catch (reseedErr) { + logger.warn("[PlayerSpawn] Voice state reseed failed:", reseedErr?.message); + } + // ── Restore recovery state ─────────────────────────────────────────── if (recoveryData) { if (recoveryData.textChannelId) { @@ -433,52 +503,6 @@ export class RecoveryManager { } logger.recovery(`[Recovery] Restored session in ${cleanChannelId} (${recoveryData.queue?.length ?? 0} track(s)).`); } - - // ── Post-recovery voice state verification ───────────────────────── - // After a bot restart, voice state data may not be fully settled when - // the player first joins. Schedule a delayed check to: - // 1. Re-seed observedVoiceUsers from VoiceManager (which receives - // VoiceStatesSync events from READY/GUILD_CREATE) - // 2. Stop any incorrectly-started inactivity timers if humans are - // present in the channel - setTimeout(() => { - if (p._destroyed) return; - - // Re-seed observedVoiceUsers from VoiceManager for this guild - try { - const vm = getVoiceManager(remix.client); - const guildVoiceMap = vm?.voiceStates?.get?.(guildId); - if (guildVoiceMap) { - const cleanGuildId = String(guildId).replace(/\D/g, ""); - for (const [userId, channelId] of guildVoiceMap) { - if (!userId || !channelId) continue; - const guild = remix.client.guilds.get(guildId); - const member = guild?.members?.get?.(userId); - const isBot = member?.user?.bot ?? false; - if (!isBot) { - remix.observedVoiceUsers.set(userId, { channelId, guildId: cleanGuildId }); - } - } - } - } catch (_) {} - - // Check if humans are now detected in the channel - if (p._hasHumansInChannel()) { - logger.recovery( - `[Recovery] Post-join check: humans detected in ${cleanChannelId}, ` + - `stopping any inactivity timer.` - ); - p._stopInactivityTimer(); - } else if (!p._is247Enabled()) { - // No humans and not 24/7 — start inactivity timer if not already running - // (the bot may have been alone when it restarted) - logger.recovery( - `[Recovery] Post-join check: no humans in ${cleanChannelId}, ` + - `starting inactivity timer.` - ); - p._startInactivityTimer(); - } - }, 8_000); // 8s grace period for voice states to settle after join } catch (e) { remix.players.playerMap.delete(cleanChannelId); try { p.destroy(); } catch (_) {} @@ -610,6 +634,8 @@ export class RecoveryManager { */ async tryAutoJoin() { if (!this.botReady || !this.settingsReady) return; + if (this._autoJoinDone || this._autoJoinRunning) return; + this._autoJoinRunning = true; const { remix } = this; await new Promise(r => setTimeout(r, 2000)); @@ -645,8 +671,6 @@ export class RecoveryManager { for (const [guildId, serverSettings] of remix.settingsMgr.guilds) { const raw = serverSettings.get("stay_247"); if (!raw || raw === "none") continue; - const mode = serverSettings.get("stay_247_mode") ?? "auto"; - if (mode !== "auto" && mode !== "on") continue; const channelIds = Array.isArray(raw) ? raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean) @@ -654,21 +678,46 @@ export class RecoveryManager { for (const channelId of channelIds) { const clean = String(channelId).replace(/\D/g, ""); + // Per-channel mode: only join if this specific channel is on/auto + const mode = get247ChannelMode(serverSettings, clean); + if (mode !== "auto" && mode !== "on") continue; + if (clean && !recoveryChannels.has(clean)) { joinList.push({ guildId, channelId: clean, recoveryData: null }); + logger.recovery( + `[Recovery] Added 24/7 channel ${clean} (guild ${guildId}, mode ${mode}) to join list` + ); } } } + logger.recovery( + `[Recovery] Join list built: ${joinList.length} channel(s) ` + + `(${joinList.filter(j => j.recoveryData).length} recovery, ` + + `${joinList.filter(j => !j.recoveryData).length} 24/7)` + ); + // ── Filter out guilds the bot is no longer a member of ──────────────── const filteredList = []; for (const item of joinList) { - if (!remix.client.guilds.has(item.guildId)) { + // Try both the raw guildId and the cleaned (digits-only) version. + // The settings Map might use a different format than client.guilds + // (e.g. string vs number, or with/without non-digit chars). + const cleanGId = String(item.guildId).replace(/\D/g, ""); + const hasRaw = remix.client.guilds.has(item.guildId); + const hasClean = cleanGId && cleanGId !== String(item.guildId) && remix.client.guilds.has(cleanGId); + + if (!hasRaw && !hasClean) { logger.recovery( - `[Recovery] Skipping guild ${item.guildId} channel ${item.channelId} — bot is no longer in the server.` + `[Recovery] Skipping guild ${item.guildId} channel ${item.channelId} — bot is no longer in the server. ` + + `(hasRaw=${hasRaw}, hasClean=${hasClean}, cleanGId=${cleanGId}, ` + + `clientGuildsSample=[${[...remix.client.guilds.keys()].slice(0, 3).join(", ")}])` ); this.cleanStaleGuild(item.guildId); } else { + if (hasClean && !hasRaw) { + item.guildId = cleanGId; + } filteredList.push(item); } } @@ -707,38 +756,13 @@ export class RecoveryManager { `(${ok} ok, ${errors.length} failed).` ); - // ── Final voice state reconciliation ──────────────────────────────────── - // After all recovery spawns complete, do one final pass to re-seed - // observedVoiceUsers from VoiceManager. This ensures that even if some - // guilds' VoiceStatesSync events arrived late, the data is captured. - try { - const vm = getVoiceManager(remix.client); - if (vm?.voiceStates) { - let reconciled = 0; - for (const [guildId, userMap] of vm.voiceStates) { - if (!userMap) continue; - const cleanGuildId = String(guildId).replace(/\D/g, ""); - for (const [userId, channelId] of userMap) { - if (!userId || !channelId) continue; - const guild = remix.client.guilds.get(guildId); - const member = guild?.members?.get?.(userId); - const isBot = member?.user?.bot ?? false; - if (!isBot && !remix.observedVoiceUsers.has(userId)) { - remix.observedVoiceUsers.set(userId, { channelId, guildId: cleanGuildId }); - reconciled++; - } - } - } - if (reconciled > 0) { - logger.recovery(`[Recovery] Final reconciliation: added ${reconciled} user(s) to observedVoiceUsers.`); - } - } - } catch (_) {} - // Delete recovery file AFTER all spawns have been attempted (success or fail). // If the process crashes mid-recovery, the file still exists for next boot. if (recoveryFileExisted) { try { fs.unlinkSync(this.recoveryPath); } catch (_) {} } + + this._autoJoinRunning = false; + this._autoJoinDone = true; } } diff --git a/src/constants/Helpers247.mjs b/src/constants/Helpers247.mjs new file mode 100644 index 0000000..7741bab --- /dev/null +++ b/src/constants/Helpers247.mjs @@ -0,0 +1,69 @@ +/** + * Shared 24/7 mode helpers. + * + * The per-channel mode map (`stay_247_modes`) stores each channel's 24/7 mode + * independently so a guild can have channel A on "on" and channel B on "auto". + * + * Format in settings: + * stay_247_modes: { "1483577390731942416": "on", "1478011355626209606": "auto" } + * + * For backward compatibility, `stay_247_mode` (guild-wide string) is still + * written when any channel is updated. All reads go through + * `get247ChannelMode()` which prefers the per-channel entry and falls back + * to the guild-wide value. + */ + +/** + * Get the 24/7 mode for a specific channel. + * + * @param {{ get: (key: string) => any }} set ServerSettings instance + * @param {string} channelId Clean (digits-only) channel ID + * @returns {"on"|"auto"|"off"} + */ +export function get247ChannelMode(set, channelId) { + if (!set?.get) return "off"; + const modes = set.get("stay_247_modes"); + if (modes && typeof modes === "object" && !Array.isArray(modes)) { + const perChannel = modes[channelId]; + if (perChannel === "on" || perChannel === "auto" || perChannel === "off") return perChannel; + } + // Fallback: guild-wide mode (legacy) + const guildMode = set.get("stay_247_mode") ?? "off"; + return guildMode; +} + +/** + * Set the 24/7 mode for a specific channel. + * + * @param {{ get: (key: string) => any, set: (key: string, value: any) => void }} set + * @param {string} channelId Clean (digits-only) channel ID + * @param {"on"|"auto"|"off"} mode + */ +export function set247ChannelMode(set, channelId, mode) { + let modes = set.get("stay_247_modes"); + if (!modes || typeof modes !== "object" || Array.isArray(modes)) modes = {}; + modes[channelId] = mode; + set.set("stay_247_modes", modes); + // Also update guild-wide mode for backward compat + set.set("stay_247_mode", mode); +} + +/** + * Remove a channel from the per-channel modes map. + * + * @param {{ get: (key: string) => any, set: (key: string, value: any) => void }} set + * @param {string} channelId Clean channel ID + * @param {Set} currentChannels Current set of all 247 channels for this guild + */ +export function remove247ChannelMode(set, channelId, currentChannels) { + let modes = set.get("stay_247_modes"); + if (!modes || typeof modes !== "object" || Array.isArray(modes)) return; + delete modes[channelId]; + set.set("stay_247_modes", modes); + if (currentChannels.size === 0) { + set.set("stay_247_mode", "off"); + } else { + const firstChannel = [...currentChannels][0]; + set.set("stay_247_mode", modes[firstChannel] ?? "auto"); + } +} diff --git a/storage/defaults.json b/storage/defaults.json index fd0e075..49c296a 100644 --- a/storage/defaults.json +++ b/storage/defaults.json @@ -6,6 +6,7 @@ "locale": "en", "stay_247": "none", "stay_247_mode": "off", + "stay_247_modes": {}, "volume": 100, "announcementChannelId": null }, @@ -15,8 +16,9 @@ "pfp": "What profile picture the bot should use. Presets: `default | dark | light | mono | `.", "locale": "The preferred language of your server.", "stay_247": "24/7 saved voice channels for this server. Supports multiple channels and is managed automatically by %247 — do not edit manually.", - "stay_247_mode": "Controls 24/7 behaviour for the saved channel list. Set via %247 off/on/auto. off = disabled, on = keep channels saved and active, auto = keep channels saved and recovery-ready.", + "stay_247_mode": "Legacy guild-wide 24/7 mode. Superseded by stay_247_modes (per-channel). Kept for backward compatibility.", + "stay_247_modes": "Per-channel 24/7 mode map. Format: {\"channelId\": \"on\"|\"auto\"|\"off\"}. Managed automatically by %247 — do not edit manually.", "volume": "The default playback volume for this server (1-200). Saved automatically when you use %volume. Restored every time the bot joins a channel.", "announcementChannelId": "The channel where song announcements are sent. Managed automatically — do not edit manually." } -} \ No newline at end of file +}