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

+3 -70
View File
@@ -1,12 +1,5 @@
/**
* worker.mjs — NodeLink REST edition (moonlink.js session-aware)
*
* Track resolution runs in a Worker thread so it never blocks the main loop.
* The Manager's active session ID is forwarded via workerData so all REST
* requests carry the correct Session-Id header (populated by moonlink.js).
*
* No direct moonlink.js import here — Worker threads can't share the Manager
* instance, so we call NodeLink REST directly (same protocol moonlink uses).
*/
import { workerData, parentPort } from "worker_threads";
@@ -17,26 +10,13 @@ import { Utils } from "./Utils.mjs";
import { PROVIDERS } from "./constants/providers.mjs";
import { logger } from "./constants/Logger.mjs";
// ═══════════════════════════════════════════════════════════════════════════════
// NodeLink Configuration (forwarded from Player via workerData)
// ═══════════════════════════════════════════════════════════════════════════════
const nl = workerData?.data?.nodelink ?? {};
const NL_HOST = nl.host ?? "localhost";
const NL_PORT = nl.port ?? 3000;
const NL_PASSWORD = nl.password ?? "youshallnotpass";
const NL_SESSION_ID = nl.sessionId ?? null; // provided by moonlink.js Manager
const NL_SESSION_ID = nl.sessionId ?? null;
const NL_GUILD_ID = workerData?.data?.guildId ?? null;
// ═══════════════════════════════════════════════════════════════════════════════
// HTTP Helper
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Make a GET request to NodeLink and return the parsed JSON body.
* @param {string} path - API path (e.g. "/v4/loadtracks?identifier=…")
* @returns {Promise<object>}
*/
function nlGet(path) {
return new Promise((resolve, reject) => {
const isHttps = NL_PORT === 443;
@@ -65,7 +45,7 @@ function nlGet(path) {
}
);
req.on("error", reject);
req.on("error", () => reject(new Error("NodeLink connection failed.")));
req.setTimeout(30_000, () => {
req.destroy();
reject(new Error("NodeLink request timeout"));
@@ -73,24 +53,10 @@ function nlGet(path) {
});
}
/**
* Call NodeLink /v4/loadtracks.
* @param {string} identifier
* @returns {Promise<object>}
*/
async function loadTracks(identifier) {
return nlGet(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`);
}
// ═══════════════════════════════════════════════════════════════════════════════
// Track Conversion
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Convert a NodeLink track object to the internal video format.
* @param {object} track
* @returns {object|null}
*/
function trackToVideo(track) {
if (!track || typeof track !== "object") return null;
@@ -102,7 +68,7 @@ function trackToVideo(track) {
encoded: track.encoded ?? "",
sourceName: info.sourceName ?? "unknown",
title: Utils.cleanTitle(info.title ?? "Unknown"),
url: info.uri ?? `https://www.youtube.com/watch?v=${info.identifier}`,
url: info.uri ?? info.identifier ?? "",
thumbnail: info.artworkUrl ?? null,
spotifyUrl: null,
duration: {
@@ -117,16 +83,8 @@ function trackToVideo(track) {
};
}
// ═══════════════════════════════════════════════════════════════════════════════
// Provider Configuration (imported from constants/providers.mjs)
// ═══════════════════════════════════════════════════════════════════════════════
const TYPE_MODIFIERS = ["track","playlist","album","artist","channel","user"];
// ═══════════════════════════════════════════════════════════════════════════════
// YTUtils Class
// ═══════════════════════════════════════════════════════════════════════════════
class YTUtils extends EventEmitter {
constructor() { super(); }
@@ -144,31 +102,21 @@ class YTUtils extends EventEmitter {
return `${prefix}:track:${query}`;
}
/**
* Clean YouTube Radio/Mix URLs to extract just the video
* YouTube Radio URLs (list=RD...) often cause metadata mismatches
*/
_cleanYouTubeUrl(url) {
try {
const urlObj = new URL(url);
// Check if it's a YouTube Radio/Mix URL
const list = urlObj.searchParams.get("list");
if (list && list.startsWith("RD")) {
// Extract just the video ID and create clean URL
const videoId = urlObj.searchParams.get("v");
if (videoId) {
logger.worker(`[Worker] Cleaning YouTube Radio URL, extracted video: ${videoId}`);
return `https://www.youtube.com/watch?v=${videoId}`;
}
}
// Remove start_radio parameter if present
if (urlObj.searchParams.has("start_radio")) {
urlObj.searchParams.delete("start_radio");
return urlObj.toString();
}
return url;
} catch (e) {
return url;
@@ -200,11 +148,9 @@ class YTUtils extends EventEmitter {
}
async getVideoData(query, provider = "ytm") {
// Handle URLs (including YouTube Radio/Mix)
if (this.isValidUrl(query)) {
this.emit("message", "Loading...");
// Clean YouTube Radio URLs to prevent metadata mismatches
const cleanedUrl = this._cleanYouTubeUrl(query);
if (cleanedUrl !== query) {
logger.worker(`[Worker] URL cleaned: ${query} -> ${cleanedUrl}`);
@@ -218,7 +164,6 @@ class YTUtils extends EventEmitter {
return { type: "error", data: null, error: e.message };
}
// Handle playlist results
if (data.loadType === "playlist") {
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
tracks.forEach(t => { t.playlistName = data.data?.info?.name ?? null; });
@@ -226,26 +171,22 @@ class YTUtils extends EventEmitter {
return { type: "list", data: tracks };
}
// Handle single track
if (data.loadType === "track") {
const video = trackToVideo(data.data);
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video };
}
// Handle search results (take first)
if (data.loadType === "search" && data.data?.length) {
const video = trackToVideo(data.data[0]);
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video };
}
// No recognizable loadType
this.emit("message", `**Could not load that URL.** (loadType: ${data.loadType || "unknown"})`);
return { type: "error", data: null, error: "Unknown loadType: " + (data.loadType || "none") };
}
// Handle search queries (non-URLs)
this.emit("message", `Searching ${this._providerLabel(provider)}...`);
let data;
@@ -256,7 +197,6 @@ class YTUtils extends EventEmitter {
return { type: "error", data: null, error: e.message };
}
// Handle search results
if (data.loadType === "search" && data.data?.length) {
const validTrack = data.data.find(track => {
const info = track.info ?? {};
@@ -272,7 +212,6 @@ class YTUtils extends EventEmitter {
return { type: "video", data: video };
}
// Handle playlist from search
if (data.loadType === "playlist") {
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
if (tracks.length > 0) {
@@ -281,23 +220,17 @@ class YTUtils extends EventEmitter {
}
}
// Single track from search
if (data.loadType === "track") {
const video = trackToVideo(data.data);
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video };
}
// Nothing found
this.emit("message", `**No results found for '${query}'.**`);
return { type: "error", data: null, error: "No results found" };
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// Worker Entry Point
// ═══════════════════════════════════════════════════════════════════════════════
const jobId = workerData?.jobId;
const data = workerData?.data;