fix(voice): resolve voice channel detection after bot reboot

- Move voice state population outside settings conditional in GuildCreate
  (now runs on every gateway resume, not just new guild joins)
- Make checkVoiceChannels() async with Fluxer API fallback
  (fetches member voice state directly when cache is empty after reboot)
- Fix PlayerManager client reference passing
- Update all callers to properly await checkVoiceChannels()
- Fix leave command to work without requiring user in voice channel

Fixes issue where bot couldn't detect users already in voice channels
immediately after a reboot due to empty voice state cache.
This commit is contained in:
NoLogicAlan committed 2026-04-16 23:41:25 +03:00
1 parent b1e9964a56
commit 73c290e59c
7 files changed
+180 -403

No files matched your search

+127 -48
View File
@@ -1,18 +1,14 @@
/**
* 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 { getGlobalColor } from "./MessageHandler.mjs";
import { getVoiceManager } from "@fluxerjs/voice";
/** Helper — build a plain embed payload from a description string */
function mkEmbed(desc) {
@@ -35,58 +31,147 @@ export class PlayerManager {
/** @type {Object} */
playerConfig;
/** @type {Map<string, Object>} */
observedVoiceUsers = null;
/** @type {import('@fluxerjs/core').Client} */
client = null;
/**
* @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;
// Fix: Ensure we get the client from commands or config
this.client = commands.client || config.player?.client || config.config?.client;
}
// ═══════════════════════════════════════════════════════════════════════════
// Voice Channel Detection
// ═══════════════════════════════════════════════════════════════════════════
/**
* Attempt to detect the voice channel a user is currently in.
* Now async to support API fallback when cache is empty after reboot.
* @param {Message} message
* @returns {string|null} Voice channel ID or null
* @returns {Promise<string|null>} Voice channel ID or null
*/
checkVoiceChannels(message) {
async checkVoiceChannels(message) {
if (!message) return null;
const userId = message.author?.id;
const serverId = message.channel?.server_id ??
const userId = message.author?.id ?? message.message?.author?.id;
const guildId = message.channel?.server_id ??
message.channel?.serverId ??
message.channel?.guild?.id ??
message.message?.server_id ??
message.message?.serverId;
message.message?.serverId ??
message.message?.guildId;
if (!userId) return null;
if (!userId || !guildId) {
logger.voiceState(`[checkVoiceChannels] Missing userId or guildId`);
return null;
}
// Fallback: find any existing player in this server
if (serverId) {
for (const [channelId] of this.playerMap) {
const channel = this.commands.client?.channels?.get(channelId) ??
this.commands.client?.channels?.cache?.get(channelId);
if (channel?.guildId === serverId || channel?.server_id === serverId || channel?.serverId === serverId) {
return channelId;
}
logger.voiceState(`[checkVoiceChannels] Checking for user ${userId} in guild ${guildId}`);
// Helper to seed observedVoiceUsers cache
const seed = (channelId) => {
if (!this.observedVoiceUsers) return channelId;
if (!this.observedVoiceUsers.has(userId)) {
this.observedVoiceUsers.set(userId, { channelId, guildId });
logger.voiceState(`[checkVoiceChannels] Seeded cache: ${userId} -> ${channelId}`);
}
return this.observedVoiceUsers.get(userId)?.channelId ?? channelId;
};
// 1. Check observedVoiceUsers cache first (populated by GuildCreate)
if (this.observedVoiceUsers) {
const observed = this.observedVoiceUsers.get(userId);
if (observed && observed.guildId === guildId) {
logger.voiceState(`[checkVoiceChannels] Found in cache: ${observed.channelId}`);
return observed.channelId;
}
}
// 2. Try VoiceManager
try {
const vm = getVoiceManager(this.client);
const channelId = vm?.getVoiceChannelId?.(guildId, userId);
if (channelId) {
logger.voiceState(`[checkVoiceChannels] Found via VoiceManager: ${channelId}`);
return seed(channelId);
}
} catch (e) {
logger.voiceState(`[checkVoiceChannels] VoiceManager failed: ${e.message}`);
}
// 3. Try message member voice (if available)
const memberVoice =
message?.member?.voice?.channelId ??
message?.member?.voice?.channel?.id ??
message?.message?.member?.voice?.channelId ??
null;
if (memberVoice) {
logger.voiceState(`[checkVoiceChannels] Found via message.member.voice: ${memberVoice}`);
return seed(memberVoice);
}
// 4. Check guild voice states cache
try {
const guild = this.client?.guilds?.cache?.get(guildId);
if (!guild) {
logger.voiceState(`[checkVoiceChannels] Guild ${guildId} not in cache`);
} else {
const voiceStates = guild?.voice_states ?? guild?.voiceStates?.cache ?? guild?.voiceStates ?? null;
if (voiceStates) {
const entries = Array.isArray(voiceStates)
? voiceStates
: typeof voiceStates.values === "function"
? [...voiceStates.values()]
: Object.values(voiceStates);
logger.voiceState(`[checkVoiceChannels] Checking ${entries.length} voice states in cache`);
for (const state of entries) {
const sid = state.userId ?? state.user_id ?? state.id;
const sch = state.channelId ?? state.channel_id;
const sgid = state.guildId ?? state.guild_id ?? guildId;
if (sid === userId && sgid === guildId && sch) {
logger.voiceState(`[checkVoiceChannels] Found in guild cache: ${sch}`);
return seed(sch);
}
}
}
}
} catch (e) {
logger.voiceState(`[checkVoiceChannels] Guild cache check failed: ${e.message}`);
}
// 5. CRITICAL FIX: Fetch fresh member data from API when cache misses
try {
const guild = this.client?.guilds?.cache?.get(guildId);
if (guild?.members?.fetch) {
logger.voiceState(`[checkVoiceChannels] Fetching member ${userId} from API...`);
const member = await guild.members.fetch(userId);
const voiceChannelId = member?.voice?.channelId ?? member?.voice?.channel?.id ?? null;
if (voiceChannelId) {
logger.voiceState(`[checkVoiceChannels] API returned voice channel: ${voiceChannelId}`);
return seed(voiceChannelId);
} else {
logger.voiceState(`[checkVoiceChannels] API returned no voice channel for user`);
}
} else {
logger.voiceState(`[checkVoiceChannels] Cannot fetch members - no fetch method`);
}
} catch (err) {
logger.voiceState(`[checkVoiceChannels] API fetch failed: ${err.message}`);
}
logger.voiceState(`[checkVoiceChannels] Could not find voice channel for ${userId}`);
return null;
}
// ═══════════════════════════════════════════════════════════════════════════
// Player Retrieval
// ═══════════════════════════════════════════════════════════════════════════
/**
* Get or create a player for the user's voice channel.
* @param {Message} message
@@ -101,7 +186,8 @@ export class PlayerManager {
message.message?.server_id ??
message.message?.serverId;
const userChannelId = this.checkVoiceChannels(message);
// Added await here
const userChannelId = await this.checkVoiceChannels(message);
if (userChannelId) {
const player = this.playerMap.get(userChannelId);
@@ -123,7 +209,9 @@ export class PlayerManager {
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
if (!userChannelId) {
message.replyEmbed(mkEmbed(`⚠️ Please join a voice channel to use this command.`));
if (promptJoin) {
message.replyEmbed(mkEmbed(`⚠️ Please join a voice channel to use this command.`));
}
return null;
}
@@ -145,16 +233,19 @@ export class PlayerManager {
return this.settings.getServer(serverId)?.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.`));
if (promptJoin) {
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."));
if (promptJoin) {
message.replyEmbed(mkEmbed("⚠️ Please join a voice channel first."));
}
return null;
}
@@ -167,17 +258,13 @@ export class PlayerManager {
return null;
}
// ═══════════════════════════════════════════════════════════════════════════
// Channel Selection Prompt
// ═══════════════════════════════════════════════════════════════════════════
/**
* Prompt the user to select a voice channel.
* @param {Message} msg
* @returns {Promise<string|false>}
* @returns {Promise<Player|false>}
*/
async promptVC(msg) {
const autoDetected = this.checkVoiceChannels(msg);
const autoDetected = await this.checkVoiceChannels(msg);
if (autoDetected) {
return new Promise(resolve => this.initPlayer(msg, autoDetected, (p) => resolve(p)));
}
@@ -258,10 +345,6 @@ export class PlayerManager {
});
}
// ═══════════════════════════════════════════════════════════════════════════
// Leave
// ═══════════════════════════════════════════════════════════════════════════
/**
* Make the player leave its current voice channel.
* @param {Message} msg
@@ -289,10 +372,6 @@ export class PlayerManager {
player.destroy();
}
// ═══════════════════════════════════════════════════════════════════════════
// Player Initialisation
// ═══════════════════════════════════════════════════════════════════════════
/**
* Create and register a new Player for the given voice channel.
* @param {Message} message