import * as fs from "fs"; import path from "path"; import { initLogger, logger } from "./src/constants/Logger.mjs"; import { Client, Events } from "@fluxerjs/core"; import { get247ChannelMode, remove247ChannelMode } from "./src/constants/Helpers247.mjs"; import { CommandHandler, CommandLoader, PrefixManager } from "./src/CommandHandler.mjs"; import { MessageHandler, PageBuilder, HelpCommand, setGlobalColor } from "./src/MessageHandler.mjs"; import { RemoteSettingsManager } from "./src/Settings.mjs"; import { PlayerManager } from "./src/PlayerManager.mjs"; import childProcess from "node:child_process"; import { getVoiceManager } from "@fluxerjs/voice"; import { FluxerRevoice } from "./src/constants/FluxerRevoice.mjs"; import { MoonlinkManager } from "./src/MoonlinkManager.mjs"; import { Dashboard } from "./src/dashboard/Dashboard.mjs"; import { Locale } from "./src/constants/Locale.mjs"; import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs"; import { GatewayHandler } from "./src/GatewayHandler.mjs"; import { LastFmManager } from "./src/LastFmManager.mjs"; import { FluxerListManager } from "./src/FluxerListManager.mjs"; /** * Create a backward-compatible "bot view" wrapper around VoiceStateCache. * * The old code used separate Maps for observedVoiceUsers and observedVoiceBots. * VoiceStateCache merged both into one object, but the default iterator/size * only exposes human users. This wrapper provides the Map-like interface that * iterates BOT entries instead, so code that does `for (const [k, v] of observedVoiceBots)` * still gets bot data, not human data. */ function createBotView(voiceCache) { return { get size() { return voiceCache.botLocations.size; }, get(key) { return voiceCache.botLocations.get(key); }, set(key, val) { voiceCache.setBotUser(key, val); }, has(key) { return voiceCache.botLocations.has(key); }, delete(key) { voiceCache.deleteBotUser(key); }, forEach(fn) { for (const [k, v] of voiceCache.iterateBotUsers()) fn(v, k, this); }, *[Symbol.iterator]() { yield* voiceCache.iterateBotUsers(); }, *entries() { yield* voiceCache.iterateBotUsers(); }, *keys() { for (const [k] of voiceCache.iterateBotUsers()) yield k; }, *values() { for (const [, v] of voiceCache.iterateBotUsers()) yield v; }, get observedVoiceBotsSize() { return voiceCache.botLocations.size; }, }; } export class Remix { constructor() { // ── Config ─────────────────────────────────────────────────────────────── let config; try { config = JSON.parse(fs.readFileSync("config.json", "utf8")); } catch (e) { const reason = e.code === "ENOENT" ? "config.json not found. Copy config_example.json → config.json and fill in your values." : `config.json is malformed JSON: ${e.message}`; console.error(`[Startup] FATAL: ${reason}`); process.exit(1); } const REQUIRED_KEYS = ["token", "mysql"]; for (const key of REQUIRED_KEYS) { if (config[key] == null) { console.error(`[Startup] FATAL: config.json is missing required key "${key}".`); process.exit(1); } } this.config = config; // Apply embed color from config globally setGlobalColor(config.embedColor); // ── Locale (i18n) ──────────────────────────────────────────────────────── this.locale = new Locale(); this.locale.load(); this.dashboard = new Dashboard(this, { enabled: config.dashboard?.enabled, redis: config.dashboard?.redis, mysql: config.mysql, }); const presenceContents = config.presenceContents ?? []; const presenceInterval = config.presenceInterval ?? 30_000; // ── Timers config ───────────────────────────────────────────────────────── const timers = config.timers ?? {}; this.T = { aloneCheckInterval: timers.aloneCheckInterval ?? 30_000, aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, rejoin247Delay: timers.rejoin247Delay ?? 3_000, leave247RejoinDelay: timers.leave247RejoinDelay ?? 5_000, intentionalLeaveTTL: timers.intentionalLeaveTTL ?? 10_000, }; // ── Fluxer Client ──────────────────────────────────────────────────────── // Fluxer does NOT support intents — the value is always sent as 0 in the // gateway IDENTIFY payload regardless of what you set here. Setting a // non-zero value only produces a warning unless suppressIntentWarning // is true. Always use intents: 0 for Fluxer bots. const client = new Client({ intents: 0, suppressIntentWarning: true, waitForGuilds: true, ...config["fluxer.js"], presence: (() => { if (presenceContents.length === 0) return undefined; const entry = presenceContents[0]; const isObj = typeof entry === "object" && entry !== null; const custom_status = {}; if (isObj) { if (entry.text) custom_status.text = entry.text; if (entry.emoji_name) custom_status.emoji_name = entry.emoji_name; if (entry.emoji_id) custom_status.emoji_id = entry.emoji_id; } else { custom_status.text = String(entry); } const p = { status: "online", mobile: false, afk: false, custom_status, }; if (isObj && entry.activity) { p.activities = [{ name: entry.activity.name ?? "music", type: entry.activity.type ?? 0, url: entry.activity.url ?? undefined, }]; } return p; })(), }); client.setMaxListeners(50); this.client = client; // ── VoiceManager initialization (MUST be before login) ───────────────── try { getVoiceManager(client); logger.player("[Startup] VoiceManager initialized before login."); } catch (e) { logger.warn("[Startup] VoiceManager pre-login init failed:", e.message); } // ── Message & Settings handlers ────────────────────────────────────────── const messages = new MessageHandler(this.client); this.messages = messages; const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json"); this.settingsMgr = settings; // Override the default prefix with config.json value if set. // This ensures that when the bot joins a NEW server (no DB row yet), it uses // the config prefix instead of the hardcoded "%" from defaults.json. // Existing servers keep whatever prefix they already have in the DB. const configPrefix = config.prefix ?? null; if (configPrefix && settings.defaults) { settings.defaults.prefix = configPrefix; } this.locale.bind(this.settingsMgr); // ── Command handler ────────────────────────────────────────────────────── // config.prefix from config.json overrides the defaults.json prefix. // This way, if you run multiple bots in the same server (e.g. Remix + test bot), // each can have its own default prefix (Remix=%, test bot=!) without needing // a separate database or manual %prefix per server. const commands = new CommandHandler(messages, configPrefix); this.handler = commands; const prefixMgr = new PrefixManager(settings, configPrefix); commands.setPrefixManager(prefixMgr); commands.setLocale(this.locale); messages.setLocale(this.locale); // ── Help command ────────────────────────────────────────────────────────── new HelpCommand(commands, messages, (msg) => this.getSettings(msg)).register(); commands.onPing = (msg) => { msg.replyEmbed( this.handler.format( "My prefix in this server is `$prefix`\n\nRun `$prefix$helpCmd` to get started!", msg.message.guildId ), false, { icon_url: msg.channel.channel.guild?.icon ? `https://cdn.fluxer.app/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.icon}.webp` : null, title: msg.channel.channel.guild?.name ?? null, } ); }; commands.owners = config.owners ?? []; // ── MoonlinkManager (placeholder) ─────────────────────────────────────── this.moonlink = null; let moonlinkInitialised = false; // ── Voice state tracking — indexed cache with LRU eviction ────────── // Replaces raw observedVoiceUsers/observedVoiceBots Maps with O(1) // channel-member lookups, composite keys, and bounded memory. this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 }); // ── Backward-compat aliases (deprecated — use voiceCache directly) ─── // observedVoiceUsers iterates HUMAN users only (backward compat). // observedVoiceBots iterates BOT users only (backward compat). // Previously both pointed to the same VoiceStateCache, which caused // observedVoiceBots to return human users instead of bots. // We create thin wrapper objects that delegate to the correct // internal indexes while preserving the Map-like interface. this.observedVoiceUsers = this.voiceCache; // default iterator = human users this.observedVoiceBots = createBotView(this.voiceCache); // ── Caches ─────────────────────────────────────────────────────────────── // _announcementChannelCache: TTL-based (5 min), auto-evicts stale entries this._announcementChannelCache = new Map(); this._announcementChannelTTL = 5 * 60 * 1000; // 5 min this.intentionalLeaves = new Map(); // ── Gateway Handler ───────────────────────────────────────────────────── // Handles raw WS gateway events, voice-state tracking, presence rotation, // and high-level Fluxer event handlers (GuildCreate, GuildDelete, // VoiceStateUpdate). this.gatewayHandler = new GatewayHandler(this); // Register GuildCreate, GuildDelete, VoiceStateUpdate handlers now so they // are active before the first Ready event fires. this.gatewayHandler.setupEventHandlers(); // ── Last.fm Manager ───────────────────────────────────────────────────── // Handles Last.fm API auth, scrobbling, and user data. this.lastfm = new LastFmManager(config.lastfm, config.mysql); // ── FluxerList Manager ────────────────────────────────────────────────── // Handles FluxerList API voter data queries. this.fluxerlist = new FluxerListManager(config.fluxerlist); // ── Settings ready callback ────────────────────────────────────────────── settings.on("ready", () => { initLogger(config); logger.settings("[settings] Loaded from DB."); for (const [guildId, serverSettings] of settings.guilds) { const val = serverSettings.get("stay_247"); if (!val || val === "none") continue; // ── Sanitise stay_247 values ──────────────────────────────────────── // Strip any value that isn't a valid Fluxer ID (>= 15 digits). // This catches corruption from old JSON_SET paths or bad data. const rawArr = Array.isArray(val) ? val : [val]; const cleaned = rawArr .map(id => String(id).replace(/\D/g, "")) .filter(id => id.length >= 15 && id.length <= 22); const needsSave = JSON.stringify(cleaned) !== JSON.stringify(val); if (needsSave || !Array.isArray(val)) { const newVal = cleaned.length > 0 ? cleaned : "none"; serverSettings.set("stay_247", newVal); if (cleaned.length === 0 && (val && val !== "none")) { serverSettings.set("stay_247_mode", "off"); } logger.settings( `[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)}` ); } } } }); // ── Bot ready ───────────────────────────────────────────────────────────── client.on(Events.Ready, async () => { logger.player("Logged in as " + (client.user?.username ?? "bot")); // ── Attach proactive error handlers on WS shards ─────────────────── // @fluxerjs/ws throws "WebSocket error" on socket close/reconnect. // Without an error handler on the WS object, this escalates to // uncaughtException and produces noisy stack traces. By attaching // .on("error") handlers on every shard's WebSocket, we catch the // error at the source and log it cleanly instead. this._attachWsErrorHandlers(); // VoiceManager was already initialized before login (required for // VOICE_STATES_SYNC event registration). No need to re-initialize here. const botId = client.user?.id ?? "0"; // Set the bot ID on all managers that use the shared MySQL database. // This isolates each bot's data (settings, Last.fm users, Redis channels) // so multiple bots can share the same database without conflicts. await this.settingsMgr.setBotId(botId); await this.lastfm.setBotId(botId); this.dashboard.setBotId(botId); // MoonlinkManager initialisation — stays here because it's audio // infrastructure, not gateway handling. The guard prevents stacking // listeners on reconnect. if (!moonlinkInitialised) { moonlinkInitialised = true; this.moonlink = new MoonlinkManager(config.nodelink ?? {}, client); this.moonlink.on("ready", (sessionId) => { logger.moonlink(`[Moonlink] Session ready: ${sessionId}`); for (const player of this.players?.playerMap?.values() ?? []) { player._nl.sessionId = sessionId; } this.playerContext.moonlink = this.moonlink; }); try { await this.moonlink.init(botId); } catch (e) { logger.error("[Moonlink] Init failed:", e.message); } } else { logger.moonlink("[Moonlink] Reconnected — re-initialising node session."); try { await this.moonlink.init(botId); } catch (e) { logger.error("[Moonlink] Re-init failed:", e.message); } } // Delegate remaining Ready work to the gateway handler (voice-state // seeding, raw WS listener, presence rotation, tryAutoJoin). this.gatewayHandler.onReady(); }); // ── FluxerRevoice Instance (shared across all players) ───────────────── // Uses the Fluxer gateway (via @fluxerjs/voice) to join voice channels // instead of a third-party REST API. This avoids the 401 error that occurs // when a Fluxer bot token is sent to an incompatible API endpoint. // The FluxerRevoice class provides the same .join() interface as // revoice.js's Revoice class, returning FluxerVoiceConnection objects // that wrap LiveKit Rooms compatible with revoice.js's MediaPlayer. this.revoice = FluxerRevoice.getInstance(client); // ── Player Manager ─────────────────────────────────────────────────────── this.playerContext = { client: this.client, config, nodelink: config.nodelink, moonlink: null, revoice: this.revoice, }; this.players = new PlayerManager(settings, commands, { config, player: this.playerContext, dashboard: this.dashboard, locale: this.locale, timers: this.T, }); this.players.observedVoiceUsers = this.observedVoiceUsers; this.players.voiceCache = this.voiceCache; this.players._lastfm = this.lastfm; // ── Periodic alone-check ─────────────────────────────────────────────────── // Uses VoiceStateCache.channelMembers index for O(1) per-player lookup // instead of iterating ALL observedVoiceUsers (which was O(N×M)). const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval; setInterval(() => { for (const [mapKey, player] of this.players.playerMap) { let channelId; try { const guildId = player._guildId; if (!guildId) continue; if (player._isJoining) continue; channelId = player._channelId ?? mapKey; const cleanChanId = String(channelId).replace(/\D/g, ""); if (!cleanChanId) continue; const cleanGuildId = String(guildId).replace(/\D/g, ""); const channelGuildId = String( this.client?.channels?.get?.(channelId)?.guildId ?? this.client?.channels?.get?.(channelId)?.guild_id ?? "" ).replace(/\D/g, ""); if (channelGuildId && channelGuildId !== cleanGuildId) { logger.warn(`[AloneCheck] Skipping inconsistent player state channel=${channelId} playerGuild=${guildId} channelGuild=${channelGuildId}`); continue; } if (player._is247Enabled()) continue; // O(1) lookup via VoiceStateCache channelMembers index let hasHuman = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanChanId); // Fallback: check guild voice_states cache if voiceCache // didn't find anyone (can happen after bot restart before reseed). if (!hasHuman) { try { 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 voiceCache so future checks are O(1) if (stateUserId) { this.voiceCache.updateUser({ guildId: cleanGuildId, userId: stateUserId, channelId: cleanChanId, isBot: false }); } break; } } } } } catch (_) {} } // Fallback: check LiveKit remote participants if guild cache is empty. if (!hasHuman) { try { const room = player.connection?.room; if (room?.isConnected && room.remoteParticipants && room.remoteParticipants.size > 0) { hasHuman = true; logger.aloneCheck(`[AloneCheck] Found ${room.remoteParticipants.size} LiveKit remote participant(s) in ${channelId}`); } } catch (_) {} } logger.aloneCheck(`[AloneCheck] channel=${channelId} guild=${guildId} hasHuman=${hasHuman} paused=${player._paused}`); if (!hasHuman && !player._paused) { if (player.queue?.getCurrent() || !player.queue?.isEmpty()) { logger.aloneCheck(`[AloneCheck] Bot alone in ${channelId} (guild ${guildId}) with songs in queue — starting inactivity timer.`); player._startInactivityTimer?.(); } else { logger.aloneCheck(`[AloneCheck] Bot alone in ${channelId} (guild ${guildId}), leaving.`); player._stopInactivityTimer?.(); player.emit("autoleave"); } } else if (hasHuman) { player._stopInactivityTimer?.(); } } catch (e) { logger.warn("[AloneCheck] Error checking channel", channelId, e.message); } } }, ALONE_CHECK_INTERVAL); // ── Voice channel detection ────────────────────────────────────────────── const self = this; this.players.checkVoiceChannels = function (message) { const userId = message?.author?.id ?? message?.message?.author?.id; const guildId = message?.channel?.guildId ?? message?.channel?.guild?.id ?? message?.channel?.server_id ?? message?.channel?.serverId ?? message?.message?.guildId ?? message?.message?.guild?.id ?? message?.message?.channel?.guildId ?? message?.message?.channel?.guild?.id ?? message?.message?.channel?.server_id ?? message?.message?.channel?.serverId; logger.voice(`[checkVC] userId=${userId} guildId=${guildId}`); logger.voice(`[checkVC] channel keys: ${Object.keys(message?.channel ?? {}).join(",")}`); logger.voice(`[checkVC] voiceCache humans=${self.voiceCache.observedVoiceUsersSize} bots=${self.voiceCache.observedVoiceBotsSize}`); if (!userId || !guildId) { logger.voice(`[checkVC] BAIL — missing userId or guildId`); return null; } const cleanGuild = String(guildId).replace(/\D/g, ""); const seed = (channelId) => { if (!self.voiceCache.hasHumanUser(userId, cleanGuild)) { self.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId, isBot: false }); } return self.voiceCache.getUserChannel(cleanGuild, userId) ?? channelId; }; const observed = self.voiceCache.getUserLocation(cleanGuild, userId); logger.voice(`[checkVC] observed=${JSON.stringify(observed)} cleanGuild=${cleanGuild}`); if (observed && observed.channelId) { logger.voice(`[checkVC] HIT voiceCache → ${observed.channelId}`); return observed.channelId; } try { const vm = getVoiceManager(client); const channelId = vm?.getVoiceChannelId?.(guildId, userId); logger.voice(`[checkVC] vm.getVoiceChannelId → ${channelId}`); if (channelId) return seed(channelId); } catch (e) { logger.voice(`[checkVC] vm error: ${e.message}`); } const memberVoice = message?.member?.voice?.channelId ?? message?.message?.member?.voice?.channelId ?? null; logger.voice(`[checkVC] memberVoice=${memberVoice}`); if (memberVoice) return seed(memberVoice); try { const guild = client.guilds.get(guildId) ?? client.guilds.get(cleanGuild); logger.voice(`[checkVC] guild=${guild?.id ?? guild?._id ?? "null"}`); const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null; logger.voice(`[checkVC] voiceStates=${Array.isArray(voiceStates) ? "array["+voiceStates.length+"]" : typeof voiceStates}`); if (voiceStates) { if (!Array.isArray(voiceStates) && typeof voiceStates === "object") { const direct = voiceStates[userId]; logger.voice(`[checkVC] direct lookup voiceStates[userId]=${JSON.stringify(direct)}`); if (direct) { const sch = typeof direct === "string" ? direct : direct?.channelId ?? direct?.channel_id ?? null; if (sch) { logger.voice(`[checkVC] HIT direct obj lookup → ${sch}`); return seed(sch); } } const firstKey = Object.keys(voiceStates)[0]; if (firstKey) { logger.voice(`[checkVC] shape sample: key=${firstKey} val=${JSON.stringify(voiceStates[firstKey])}`); } } const entries = Array.isArray(voiceStates) ? voiceStates : typeof voiceStates.values === "function" ? voiceStates.values() : Object.values(voiceStates); for (const state of entries) { const sid = state?.userId ?? state?.user_id ?? state?.id; const sch = state?.channelId ?? state?.channel_id; const sgid = String(state?.guildId ?? state?.guild_id ?? guildId).replace(/\D/g, ""); logger.voice(`[checkVC] state: sid=${sid} sch=${sch} sgid=${sgid}`); if (sid === userId && sgid === cleanGuild && sch) { logger.voice(`[checkVC] HIT guild.voice_states iterate → ${sch}`); return seed(sch); } } } } catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); } try { const loc = self.voiceCache.getHumanUser(userId); // scan all guilds if (loc && String(loc.guildId ?? "").replace(/\D/g, "") === cleanGuild) { logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`); return loc.channelId; } } catch (e) { logger.voice(`[checkVC] last-resort error: ${e.message}`); } logger.voice(`[checkVC] MISS — returning null`); return null; }; // ── Git commit hash ─────────────────────────────────────────────────────── // Must be computed BEFORE comLink is built so the hash is available. const __dirname = import.meta.dirname; try { this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); } catch { logger.warn("[Git] comhash error"); this.comHash = "Newest"; this.comHashLong = null; } this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? ""); // ── Commands ────────────────────────────────────────────────────────────── const loader = new CommandLoader(commands, this); const dir = path.join(__dirname, "commands"); logger.commands("Started loading commands."); loader.loadFromDir(dir) .then(() => logger.commands("Commands loaded.")) .catch(e => logger.error("Failed to load commands:", e)); // ── Modules ─────────────────────────────────────────────────────────────── logger.commands("Loading Modules."); this.loadedModules = new Map(); try { this.modules = JSON.parse(fs.readFileSync("./storage/modules.json")); } catch (e) { const reason = e.code === "ENOENT" ? "storage/modules.json not found." : `storage/modules.json is malformed JSON: ${e.message}`; console.error(`[Startup] WARN: ${reason} — starting with no modules.`); this.modules = []; } Promise.allSettled(this.modules.map(async m => { if (!m.enabled) return; try { const exported = await import(m.index); const ModClass = exported.default; this.loadedModules.set(m.name, { instance: new ModClass(this), c: ModClass }); } catch (e) { logger.error(`[Module] Failed to load "${m.name}":`, e.message); } })) .then(results => { const succeeded = results.filter(r => r.status === "fulfilled").length; const failed = results.filter(r => r.status === "rejected").length; logger.commands(`Modules loaded (${succeeded} succeeded, ${failed} failed).`); }); // ── Login ───────────────────────────────────────────────────────────────── client.login(config.token); } // ─── Helpers ────────────────────────────────────────────────────────────── /** * Attach error handlers on all @fluxerjs/ws shard WebSockets. * * When the Fluxer gateway's underlying WebSocket closes (e.g. network * blip, server restart), @fluxerjs/ws throws a "WebSocket error" from * its internal error handler. Without an .on("error") listener on the * WS object itself, this escalates to Node's uncaughtException handler, * producing a noisy stack trace even though the bot recovers * automatically via gateway reconnection. * * By attaching .on("error") handlers here, we catch the error at the * source, log a single clean line, and prevent it from reaching * uncaughtException. */ _attachWsErrorHandlers() { try { const wsManager = this.client?.ws; if (!wsManager) return; // @fluxerjs/ws may use a single connection or a ShardManager. // Handle both patterns: const attachToSocket = (wsObj, label) => { if (!wsObj) return; // Avoid attaching duplicate handlers on reconnect if (wsObj._fluxerErrorHandled) return; wsObj._fluxerErrorHandled = true; if (typeof wsObj.on === "function") { wsObj.on("error", (err) => { logger.warn(`[WS] ${label} transport error (auto-recovering): ${err?.message ?? err}`); }); } if (typeof wsObj.addEventListener === "function") { wsObj.addEventListener("error", (event) => { const err = event?.error ?? event?.message ?? event; logger.warn(`[WS] ${label} transport error (auto-recovering): ${err?.message ?? err}`); }); } }; // Pattern 1: ws.shards is a Map (multi-shard) if (wsManager.shards && typeof wsManager.shards.forEach === "function") { wsManager.shards.forEach((shard, id) => { attachToSocket(shard?.ws, `Shard ${id}`); }); } // Pattern 2: ws itself has a .ws property (single-shard) if (wsManager.ws) { attachToSocket(wsManager.ws, "Gateway"); } // Pattern 3: ws is itself a WebSocket-like object if (typeof wsManager.on === "function" && !wsManager._fluxerErrorHandled) { attachToSocket(wsManager, "WSManager"); } // Also listen for new shards being created (future-proofing) if (typeof wsManager.on === "function" && !wsManager._shardCreateHandled) { wsManager._shardCreateHandled = true; wsManager.on("shardCreate", (shard) => { if (shard?.ws) { attachToSocket(shard.ws, `Shard ${shard.id ?? "?"}`); } }); } logger.player("[WS] Proactive error handlers attached to gateway sockets."); } catch (e) { logger.warn("[WS] Failed to attach WS error handlers:", e.message); } } markIntentionalLeave(channelId, ttlMs = null) { const clean = String(channelId).replace(/\D/g, ""); if (!clean) return; if (ttlMs === null) ttlMs = this.config?.timers?.intentionalLeaveTTL ?? 10_000; const existing = this.intentionalLeaves.get(clean); if (existing) clearTimeout(existing); this.intentionalLeaves.set(clean, setTimeout(() => { this.intentionalLeaves.delete(clean); }, ttlMs)); } /** * Spawn a player for a voice channel without requiring a user message. * Used by the 24/7 settings command and the leave command's auto-rejoin. * * @param {string} guildId — The guild ID * @param {string} channelId — The voice channel ID to join * @returns {Promise} The created player */ async _spawnPlayer(guildId, channelId) { const cleanGuildId = String(guildId).replace(/\D/g, ""); const cleanChannelId = String(channelId).replace(/\D/g, ""); if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId"); // Already have a player for this channel? // Use guild→player reverse index for O(1) lookup, fallback to playerMap.get() const existing = this.players.playerMap.get(cleanChannelId) ?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId); if (existing) return existing; // Guard: moonlink must be ready if (!this.moonlink) throw new Error("Audio node not ready yet — try again in a moment"); // Guard: channel must exist and be a voice channel const channel = this.client?.channels?.get?.(cleanChannelId); if (!channel) throw new Error("Channel not found"); if (channel.type !== 2) throw new Error("Not a voice channel"); // Guard: no duplicate pending join if (this.players._pendingJoins?.has?.(cleanChannelId)) { throw new Error("Join already in progress for this channel"); } const Player = (await import("./src/Player.mjs")).default; const player = new Player(this.config.token, { client: this.client, config: this.config, nodelink: this.config.nodelink, moonlink: this.moonlink ?? null, revoice: this.revoice ?? null, settingsMgr: this.settingsMgr ?? this.settings ?? null, observedVoiceUsers: this.observedVoiceUsers ?? null, voiceCache: this.voiceCache ?? null, locale: this.locale ?? null, }); // Set 24/7 home channel so _is247Enabled() works correctly player._home247Channel = cleanChannelId; // Set up dashboard and lifecycle events (same as normal joins) this.players.setupEvents(player, { channelId: cleanChannelId, guildId: cleanGuildId, }); // 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(); }); // Handle player messages (song announcements etc.) player.on("message", (m) => { // No text channel for headless spawns — skip announcements }); // Mark as pending join if (this.players._pendingJoins) { this.players._pendingJoins.add(cleanChannelId); } try { await player.join(cleanChannelId); // Add to playerMap only after join succeeds this.players.playerMap.set(cleanChannelId, player); this.players._indexPlayer(cleanGuildId, cleanChannelId); if (this.players._pendingJoins) { this.players._pendingJoins.delete(cleanChannelId); } // Restore saved volume for this guild const savedVol = this.settingsMgr?.getServer?.(cleanGuildId)?.get?.("volume"); if (savedVol !== undefined && savedVol !== null) { const vol = Number(savedVol); if (!isNaN(vol)) player.setVolume(vol / 100); } logger.player(`[_spawnPlayer] Spawned player for channel ${cleanChannelId} in guild ${cleanGuildId}`); return player; } catch (err) { if (this.players._pendingJoins) { this.players._pendingJoins.delete(cleanChannelId); } this.players.playerMap.delete(cleanChannelId); try { player.destroy(); } catch (_) {} logger.warn(`[_spawnPlayer] Failed to spawn player for channel ${cleanChannelId}:`, err.message); throw err; } } async leaveChannel(channelId, guildId, message, force = false) { const cleanId = String(channelId).replace(/\D/g, ""); const cleanGuildId = String(guildId).replace(/\D/g, ""); const set = this.settingsMgr.getServer(guildId); const raw = set.get("stay_247"); const channels = (!raw || raw === "none") ? new Set() : Array.isArray(raw) ? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean)) : new Set([String(raw).replace(/\D/g, "")]); // Use per-channel mode (not the guild-wide legacy mode) const channelMode = channels.has(cleanId) ? get247ChannelMode(set, cleanId) : "off"; if (channels.has(cleanId) && !force) { if (channelMode === "auto") { if (message) { const prefix = (() => { try { return set.get("prefix") ?? "%"; } catch (_) { return "%"; } })(); const guildIdForLocale = message?.channel?.channel?.guildId ?? message?.guildId ?? cleanGuildId; message.replyEmbed( this.locale.translate(guildIdForLocale, "responses.leave.autoRejoinHint", { channel: cleanId, prefix }) ); } return false; } } if (channels.has(cleanId)) { channels.delete(cleanId); set.set("stay_247", channels.size > 0 ? [...channels] : "none"); // Also clean up the per-channel mode entry (prevents orphaned mode data) remove247ChannelMode(set, cleanId, channels); } this.markIntentionalLeave(cleanId); const player = this.players.playerMap.get(cleanId); if (player) { this.players.playerMap.delete(cleanId); await player.leave().catch(() => {}); player.destroy(); } if (message) { const guildIdForLocale = message?.channel?.channel?.guildId ?? message?.guildId ?? cleanGuildId; message.replyEmbed(this.locale.translate(guildIdForLocale, "responses._common.successfullyLeft")); } return true; } /** @param {import("./src/MessageHandler.mjs").Message} message */ getSettings(message) { const guildId = message?.channel?.channel?.guildId ?? message?.guildId ?? null; return this.settingsMgr.getServer(guildId); } /** * Translate a key for the guild of the given message. * @param {import("./src/MessageHandler.mjs").Message} message * @param {string} key * @param {Object} [data={}] * @returns {string} */ t(message, key, data = {}) { const guildId = message?.channel?.channel?.guildId ?? message?.message?.guildId ?? message?.guildId ?? null; return this.locale.translate(guildId, key, data); } getPlayer(message, promptJoin, verifyUser, shouldJoin) { return this.players.getPlayer(message, promptJoin, verifyUser, shouldJoin); } /** * Return all guilds the given user shares with this bot. * No longer gated behind settingsMgr — works with or without MySQL. * Uses cached members first, falls back to observedVoiceUsers, then * an async REST fetch for large guilds where the member cache is incomplete. * * @param {import("@fluxerjs/core").User} user * @returns {Promise>} */ async getSharedServers(user) { if (!user) return []; const shared = []; for (const guild of this.client.guilds.values()) { let isMember = false; // 1. Fast path — check cached members if (guild.members?.has?.(user.id)) { isMember = true; } // 2. Fallback — check voiceCache for this guild (O(1) per guild) if (!isMember) { const cleanGuildId = String(guild.id).replace(/\D/g, ""); // Check if any human users are tracked in this guild const hasVoiceUsers = [...this.voiceCache.userLocations.values()].some( loc => loc.guildId === cleanGuildId ); if (hasVoiceUsers) isMember = true; } // 3. Slow path — REST fetch for large guilds with incomplete caches if (!isMember) { try { const member = await guild.members.fetch(user.id).catch(() => null); if (member) isMember = true; } catch (_) { /* not a member or fetch failed */ } } if (!isMember) continue; shared.push({ name: guild.name, id: guild.id, icon: guild.icon ? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp` : null, description: guild.description ?? null, ownerId: guild.ownerId ?? null, voiceChannels: guild.channels .filter(c => c.isVoiceBased?.() ?? false) .map(c => { // Build voice participants list for this channel const voiceParticipants = []; if (guild.voice_states) { const vs = Array.isArray(guild.voice_states) ? guild.voice_states : typeof guild.voice_states.values === "function" ? [...guild.voice_states.values()] : Object.values(guild.voice_states); for (const state of vs) { const scId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, ""); const chId = String(c.id ?? "").replace(/\D/g, ""); if (scId === chId) { const member = guild.members?.get?.(state?.userId ?? state?.user_id); if (member?.user && !member.user.bot) { voiceParticipants.push(Dashboard.convertUser(member.user)); } } } } return { name: c.name, displayName: c.name, id: c.id, icon: null, description: c.topic ?? null, isVoice: true, mature: c.nsfw ?? false, serverId: guild.id, voiceParticipants, }; }), }); } return shared; } pagination(form, content, msg, linesPerPage) { this.messages.initPagination( new PageBuilder(content).setForm(form).setMaxLines(linesPerPage), msg ); } } // ── Boot ────────────────────────────────────────────────────────────────────── const remix = new Remix(); // ── Error handling ──────────────────────────────────────────────────────────── const isIgnorableWsCrash = (err) => { const message = String(err?.message ?? err ?? ""); const stack = String(err?.stack ?? ""); // WebSocket transport errors from @fluxerjs/ws — these are recoverable // because the gateway client automatically reconnects. They should be // caught by the proactive .on("error") handlers in _attachWsErrorHandlers(), // but this acts as a safety net in case a new shard is created after the // initial handler attachment or the error slips through via a different path. return message === "WebSocket error" && ( stack.includes("@fluxerjs/ws/dist/index.mjs") || stack.includes("node:internal/deps/undici/undici") ); }; process.on("unhandledRejection", (reason, p) => { if (reason?.message?.includes("AudioSource is closed")) return; logger.error("[Error_Handling] Unhandled Rejection/Catch"); logger.error("Reason:", reason, p); }); process.on("uncaughtException", (err, origin) => { if (isIgnorableWsCrash(err)) { logger.warn("[Error_Handling] Suppressed recoverable websocket transport crash."); logger.warn("Error:", err?.stack ?? err, origin); return; } logger.error("[Error_Handling] Uncaught Exception/Catch"); logger.error("Error:", err, origin); process.exit(1); }); process.on("uncaughtExceptionMonitor", (err, origin) => { logger.error("[Error_Handling] Uncaught Exception/Catch (MONITOR)"); logger.error("Error:", err, origin); }); // ── Shutdown Hooks ────────────────────────────────────────────────────────── const saveAndExit = async () => { logger.recovery("\n[Shutdown] Cleaning up before exit..."); try { if (remix.dashboard?.redis?.destroy) { await remix.dashboard.redis.destroy(); } } catch (e) { logger.error("[Shutdown] Failed to close Redis:", e.message); } try { if (remix.dashboard?.db?.close) { await remix.dashboard.db.close(); } } catch (e) { logger.error("[Shutdown] Failed to close Dashboard DB:", e.message); } process.exit(0); }; process.once("SIGINT", saveAndExit); process.once("SIGTERM", saveAndExit); process.once("SIGUSR2", saveAndExit); // ── SIGPIPE handler ────────────────────────────────────────────────────────── // On some systems, writing to a broken pipe (e.g. Redis connection) raises // SIGPIPE which defaults to terminating the process. Ignoring it lets the // error surface through the normal exception/rejection handlers above so // recovery state is saved before exit. process.on("SIGPIPE", () => {});