/** * PlayerManager.mjs — Manages voice channel players across servers * * Updated for moonlink.js: passes the MoonlinkManager instance into every * new Player so it can resolve tracks and retrieve session IDs. */ import Player from "./Player.mjs"; import { CommandHandler } from "./CommandHandler.mjs"; import { Message } from "./MessageHandler.mjs"; import { SettingsManager } from "./Settings.mjs"; import { Utils } from "./Utils.mjs"; import { logger } from "./constants/Logger.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getVoiceManager } from "@fluxerjs/voice"; import { getGlobalColor } from "./MessageHandler.mjs"; /** Helper — build a plain embed payload from a description string */ function mkEmbed(desc) { return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] }; } function cleanId(value) { return String(value ?? "").replace(/\D/g, ""); } function getMessageGuildId(message) { return message?.channel?.guildId ?? message?.channel?.guild?.id ?? message?.message?.guildId ?? message?.message?.guild?.id ?? message?.channel?.server_id ?? message?.channel?.serverId ?? message?.message?.server_id ?? message?.message?.serverId ?? null; } function getPlayerGuildId(player, fallbackChannel = null) { return cleanId( player?._guildId ?? fallbackChannel?.guildId ?? fallbackChannel?.guild?.id ?? fallbackChannel?.server_id ?? fallbackChannel?.serverId ); } function getPlayerChannelId(player, fallbackChannelId = null) { return cleanId(player?._channelId ?? player?._home247Channel ?? fallbackChannelId); } export class PlayerManager { /** @type {SettingsManager} */ settings; /** @type {CommandHandler} */ commands; /** @type {Map} */ playerMap = new Map(); /** @type {Object} */ config; /** @type {Object} */ playerConfig; /** * @param {SettingsManager} settings * @param {CommandHandler} commands * @param {Object} config * @param {Object} config.config - Parsed config.json * @param {Object} config.player - Config data passed to new Player instances */ constructor(settings, commands, config) { this.commands = commands; this.settings = settings; this.config = config.config; this.playerConfig = config.player; } // ═══════════════════════════════════════════════════════════════════════════ // Voice Channel Detection // ═══════════════════════════════════════════════════════════════════════════ /** * Attempt to detect the voice channel a user is currently in. * @param {Message} message * @returns {string|null} Voice channel ID or null */ checkVoiceChannels(message) { if (!message) return null; const userId = message.author?.id ?? message.message?.author?.id; const guildId = getMessageGuildId(message); if (!userId) return null; if (!guildId) return null; const cleanGuild = cleanId(guildId); const seedObserved = (channelId) => { const cleanChannelId = cleanId(channelId); if (!cleanChannelId) return null; if (!this.observedVoiceUsers?.has(userId)) { this.observedVoiceUsers?.set(userId, { channelId: cleanChannelId, guildId: cleanGuild }); } return cleanId(this.observedVoiceUsers?.get(userId)?.channelId) || cleanChannelId; }; const observed = this.observedVoiceUsers?.get?.(userId); if (cleanId(observed?.guildId) === cleanGuild) { const observedChannelId = cleanId(observed?.channelId); if (observedChannelId) return observedChannelId; } try { const vm = getVoiceManager(this.commands.client); const voiceChannelId = vm?.getVoiceChannelId?.(guildId, userId); const seeded = seedObserved(voiceChannelId); if (seeded) return seeded; } catch (_) {} const memberVoiceChannelId = message?.member?.voice?.channelId ?? message?.message?.member?.voice?.channelId ?? null; { const seeded = seedObserved(memberVoiceChannelId); if (seeded) return seeded; } try { const guild = this.commands.client?.guilds?.cache?.get?.(guildId) ?? this.commands.client?.guilds?.cache?.get?.(cleanGuild); const voiceStates = guild?.voice_states ?? guild?.voiceStates?.cache ?? guild?.voiceStates ?? null; if (voiceStates) { if (!Array.isArray(voiceStates) && typeof voiceStates === "object") { const direct = voiceStates[userId]; const directChannelId = typeof direct === "string" ? direct : direct?.channelId ?? direct?.channel_id ?? null; const seeded = seedObserved(directChannelId); if (seeded) return seeded; } const entries = Array.isArray(voiceStates) ? voiceStates : typeof voiceStates.values === "function" ? voiceStates.values() : Object.values(voiceStates); for (const state of entries) { const stateUserId = state?.userId ?? state?.user_id ?? state?.id; const stateGuildId = cleanId(state?.guildId ?? state?.guild_id ?? guildId); if (stateUserId !== userId || stateGuildId !== cleanGuild) continue; const seeded = seedObserved(state?.channelId ?? state?.channel_id); if (seeded) return seeded; } } } catch (_) {} const liveGuildPlayers = [...this.playerMap.entries()].filter(([channelId, player]) => { const fallbackChannel = this.commands.client?.channels?.get?.(channelId) ?? this.commands.client?.channels?.cache?.get?.(channelId) ?? null; return getPlayerGuildId(player, fallbackChannel) === cleanGuild; }); if (liveGuildPlayers.length === 1) { return getPlayerChannelId(liveGuildPlayers[0][1], liveGuildPlayers[0][0]) || cleanId(liveGuildPlayers[0][0]); } return null; } // ═══════════════════════════════════════════════════════════════════════════ // Player Retrieval // ═══════════════════════════════════════════════════════════════════════════ /** * Get or create a player for the user's voice channel. * @param {Message} message * @param {boolean} [promptJoin=true] * @param {boolean} [verifyUser=true] * @param {boolean} [shouldJoin=false] * @returns {Promise} */ async getPlayer(message, promptJoin = true, verifyUser = true, shouldJoin = false) { const guildId = getMessageGuildId(message); const cleanGuildId = cleanId(guildId); const userChannelId = this.checkVoiceChannels(message); const cleanUserChannelId = cleanId(userChannelId); if (cleanUserChannelId) { const player = this.playerMap.get(cleanUserChannelId) ?? [...this.playerMap.values()].find(p => getPlayerChannelId(p) === cleanUserChannelId ); if (player) { player.textChannel = message.channel; return player; } } const serverPlayers = cleanGuildId ? [...this.playerMap.entries()].filter(([, player]) => { return getPlayerGuildId(player) === cleanGuildId; }) : []; if (serverPlayers.length > 0) { const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or "); if (!userChannelId) { // verifyUser=false: allow controlling the bot without being in voice // (e.g. volume, clear, remove — admin-style controls). if (!verifyUser) { const first = serverPlayers[0]; first[1].textChannel = message.channel; return first[1]; } message.replyEmbed(mkEmbed(`⚠️ You need to join a voice channel to use this command.`)); return null; } const match = serverPlayers.find(([, player]) => String(player?._channelId ?? "").replace(/\D/g, "") === cleanUserChannelId ); if (match) { match[1].textChannel = message.channel; return match[1]; } // User is in a different channel than existing players. if (shouldJoin) { return new Promise((resolve) => { this.initPlayer(message, userChannelId, (p) => resolve(p)); }); } const prefix = (() => { try { return this.settings.getServer(guildId)?.get("prefix") ?? "%"; } catch (_) { return "%"; } })(); message.replyEmbed(mkEmbed(`⚠️ I'm already playing in ${channelList}. Join that channel or use \`${prefix}play\` to start music in your channel.`)); return null; } if (!userChannelId) { if (shouldJoin) { // Auto-detect failed — fall back to interactive channel selection prompt return this.promptVC(message); } message.replyEmbed(mkEmbed("⚠️ Please join a voice channel first.")); return null; } if (shouldJoin) { return new Promise((resolve) => { this.initPlayer(message, userChannelId, (p) => resolve(p)); }); } return null; } // ═══════════════════════════════════════════════════════════════════════════ // Channel Selection Prompt // ═══════════════════════════════════════════════════════════════════════════ /** * Prompt the user to select a voice channel. * @param {Message} msg * @returns {Promise} */ async promptVC(msg) { const autoDetected = this.checkVoiceChannels(msg); if (autoDetected) { return new Promise(resolve => this.initPlayer(msg, autoDetected, (p) => resolve(p))); } const guildId = getMessageGuildId(msg); const cleanGuildId = cleanId(guildId); const allChannels = cleanGuildId ? [...(this.commands.client?.channels?.values?.() ?? this.commands.client?.channels?.cache?.values?.() ?? [])] .filter(c => { const channelGuildId = cleanId(c.guildId ?? c.guild?.id ?? c.server_id ?? c.serverId); const isVoice = c.channel_type === "VoiceChannel" || c.type === "VoiceChannel" || c.type === 2; return channelGuildId === cleanGuildId && isVoice; }) : []; const reactions = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣"]; const channelArr = allChannels.slice(0, 9); let channelSelection = ""; if (channelArr.length > 0) { channelSelection = "Please select one of the following channels by clicking on the reactions below\n\n"; channelArr.forEach((c, i) => { channelSelection += `${i + 1}. <#${c._id ?? c.id}>\n`; }); } const selectionMsg = await msg.replyEmbed(mkEmbed( (channelSelection ? channelSelection + "\n**..or**" : "Please") + " send a message with the voice channel! (Mention/Id/Name)\nSend 'x' to cancel." )); return new Promise(resolve => { let unsubscribeReactions; let unsubscribeMessages; const cleanup = () => { unsubscribeMessages?.(); unsubscribeReactions?.(); }; const timeout = setTimeout(() => { cleanup(); msg.replyEmbed(mkEmbed("⏱️ Voice selection timed out.")); resolve(false); }, 30_000); if (typeof selectionMsg?.onReaction === "function" && channelArr.length > 0) { unsubscribeReactions = selectionMsg.onReaction( reactions.slice(0, channelArr.length), (e) => { const idx = reactions.indexOf(e.emoji_id ?? e.emoji?.id ?? e.emoji); const channel = channelArr[idx]; if (!channel) return; clearTimeout(timeout); cleanup(); const cid = channel._id ?? channel.id; this.initPlayer(msg, cid, (p) => resolve(p)); }, msg.author ); } unsubscribeMessages = msg.channel.onMessageUser((m) => { const content = m.content?.toLowerCase() ?? ""; if (content === "x") { clearTimeout(timeout); cleanup(); m.replyEmbed(mkEmbed("Cancelled!")); resolve(false); return; } if (!this.commands.validateInput("voiceChannel", m.content, m)) { m.replyEmbed(mkEmbed("Invalid voice channel. Try again or type `x`.")); return; } const channel = this.commands.formatInput("voiceChannel", m.content, m); clearTimeout(timeout); cleanup(); this.initPlayer(m, channel, (p) => resolve(p)); }, msg.author); }); } // ═══════════════════════════════════════════════════════════════════════════ // Leave // ═══════════════════════════════════════════════════════════════════════════ /** * Make the player leave its current voice channel. * @param {Message} msg * @param {string} [cid] */ async leave(msg, cid) { if (!cid) { const serverId = msg.channel?.server_id ?? msg.channel?.serverId ?? msg.message?.server_id ?? msg.message?.serverId; if (serverId) { const matchedEntry = [...this.playerMap.entries()].find(([, player]) => String(player?._guildId ?? "").replace(/\D/g, "") === String(serverId).replace(/\D/g, "") ); cid = matchedEntry?.[0] ?? null; } } const player = cid ? this.playerMap.get(cid) : null; if (!player) return msg.replyEmbed(mkEmbed("I'm not in a voice channel.")); const activeChannelId = String(player._channelId ?? cid).replace(/\D/g, "") || cid; this.playerMap.delete(activeChannelId); if (activeChannelId !== cid) this.playerMap.delete(cid); await msg.replyEmbed(mkEmbed("✅ Successfully Left")); await player.leave(); player.destroy(); } // ═══════════════════════════════════════════════════════════════════════════ // Player Initialisation // ═══════════════════════════════════════════════════════════════════════════ /** * Create and register a new Player for the given voice channel. * @param {Message} message * @param {string} cid - Voice channel ID * @param {Function} [cb] */ initPlayer(message, cid, cb = () => {}) { const channel = this.commands.client?.channels?.get(cid) ?? this.commands.client?.channels?.cache?.get(cid); if (!channel) { return message.replyEmbed(mkEmbed( `Couldn't find the channel \`${cid}\`\nUse the help command to learn more about this.` )); } const isVoice = channel.channel_type === "VoiceChannel" || channel.type === "VoiceChannel" || channel.type === 2; if (!isVoice) { return message.replyEmbed(mkEmbed("❌ Please join a **voice channel** first before using this command!")); } const cleanChannelId = cleanId(cid); const existing = this.playerMap.get(cleanChannelId) ?? [...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId); if (existing) { existing.textChannel = message.channel; cb(existing); return message.replyEmbed(mkEmbed(`Already joined <#${cid}>.`)); } const player = new Player(this.config.token, { ...this.playerConfig, client: this.commands.client, config: this.config, nodelink: this.config.nodelink, moonlink: this.playerConfig?.moonlink ?? null, settingsMgr: this.settings, observedVoiceUsers: this.observedVoiceUsers ?? null, }); player.textChannel = message.channel; 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 })); const is247 = (() => { try { const raw = this.settings.getServer(guildId)?.get("stay_247"); return raw && raw !== "none"; } catch (_) { return false; } })(); const prefix = (() => { try { return this.settings.getServer(guildId)?.get("prefix") ?? "%"; } catch (_) { return "%"; } })(); const desc = is247 ? `Left channel <#${activeChannelId}> because of inactivity.` : `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``; ch?.sendEmbed(mkEmbed(desc)); this.playerMap.delete(activeChannelId); if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId); if (homeChannelId !== activeChannelId) this.playerMap.delete(homeChannelId); player.destroy(); }); player.on("leave", () => {}); 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; ch?.sendEmbed(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)); }); this.playerMap.set(cleanChannelId, player); (async () => { const statusMsg = await message.replyEmbed(mkEmbed("⏳ Joining Channel...")); try { await player.join(cid); await statusMsg.editEmbed(mkEmbed(`✅ Successfully joined <#${cid}>`)); const guildId = cleanId(channel.guildId ?? getMessageGuildId(message)); if (guildId) { const savedVol = this.settings.getServer(guildId)?.get("volume"); if (savedVol !== undefined && savedVol !== null) { const vol = Number(savedVol); if (!isNaN(vol)) player.setVolume(vol / 100); } } cb(player); } catch (err) { await statusMsg.editEmbed(mkEmbed(`❌ Failed to join: ${err.message}`)).catch(() => {}); this.playerMap.delete(cleanChannelId); player.destroy(); } })(); } async leave(msg, cid) { if (!cid) { const guildId = getMessageGuildId(msg); if (guildId) { const matchedEntry = [...this.playerMap.entries()].find(([, player]) => getPlayerGuildId(player) === cleanId(guildId) ); cid = getPlayerChannelId(matchedEntry?.[1], matchedEntry?.[0]) || matchedEntry?.[0] || null; } } const cleanChannelId = cleanId(cid); const player = cleanChannelId ? this.playerMap.get(cleanChannelId) ?? [...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId) : null; if (!player) return msg.replyEmbed(mkEmbed("I'm not in a voice channel.")); const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId; this.playerMap.delete(activeChannelId); if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId); await msg.replyEmbed(mkEmbed("✅ Successfully Left")); await player.leave(); player.destroy(); } }