From b581722c46facc30c138cfefa6375f49fc391a07 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Mon, 25 May 2026 19:22:20 +0300 Subject: [PATCH] fix: resolve bugs in voice, filter, dashboard, and stats handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix filter command using stale track reference instead of current queue track - Fix playnext null check before editing status message - Fix join command using raw channel ID before cleaning it - Fix GatewayHandler passing wrong isBot flag in voice state cache - Fix Dashboard shared server filtering (was returning empty, now filters correctly) - Fix avatar fallback using discriminator (deprecated) → use user ID instead - Refactor Player.mjs: extract ConnectionState/LKRoomEvent to FluxerRevoice constants - Refactor Player.mjs: replace local formatMsHelper with Utils.prettifyMS - Add Logger.guild() method; use it in GatewayHandler instead of logger.info() - Remove rbl-stats module from modules.json - Remove unused empty event listeners in PlayerManager - Remove unused CRITICAL_PERMISSIONS import from GatewayHandler --- commands/autoplay.mjs | 3 +-- commands/debug.mjs | 9 --------- commands/filter.mjs | 2 +- commands/forceleave.mjs | 2 +- commands/join.mjs | 4 ++-- commands/lastfm.mjs | 4 ++-- commands/player.mjs | 2 +- commands/playnext.mjs | 2 +- commands/stats.mjs | 4 ---- src/GatewayHandler.mjs | 8 ++++---- src/Player.mjs | 31 ++++++------------------------- src/PlayerManager.mjs | 5 ----- src/constants/FluxerRevoice.mjs | 7 +++++-- src/constants/Logger.mjs | 4 ++++ src/constants/VoiceStateCache.mjs | 6 +----- src/constants/audio/Tuna.mjs | 8 ++++---- src/dashboard/Dashboard.mjs | 19 ++++++++++++------- src/worker.mjs | 12 ------------ storage/modules.json | 5 ----- 19 files changed, 45 insertions(+), 92 deletions(-) diff --git a/commands/autoplay.mjs b/commands/autoplay.mjs index aee7bcd..4a7202f 100644 --- a/commands/autoplay.mjs +++ b/commands/autoplay.mjs @@ -9,7 +9,6 @@ export const command = new CommandBuilder() .addAliases("ap"); export async function run(msg, data) { - const prefix = this.handler?.getPrefix?.(msg.message?.guildId) ?? "%"; const p = await this.getPlayer(msg, true, true, false); if (!p) return; @@ -19,7 +18,7 @@ export async function run(msg, data) { if (!p._autoplayHandler) { p._autoplayHandler = async () => { if (!p._autoplay) return; - if (p.queue?.getCurrent() || !p.queue?.isEmpty()) return; + if (p.queue?.getCurrent() && !p.queue?.isEmpty()) return; const lastTrack = p._lastPlayedTrack; if (!lastTrack) return; diff --git a/commands/debug.mjs b/commands/debug.mjs index 25d86e2..6b15134 100644 --- a/commands/debug.mjs +++ b/commands/debug.mjs @@ -79,15 +79,6 @@ export async function run(msg, data) { { let groupJson = ""; - let groupStart = 0; - - const flushGroup = () => { - if (!groupJson) return; - const codeBlock = "```json\n" + groupJson + "\n```"; - pages.push(codeBlock.slice(0, MAX_DESC)); - groupJson = ""; - groupStart = i; - }; let i = 0; for (i = 0; i < servers.length; i++) { diff --git a/commands/filter.mjs b/commands/filter.mjs index 817af87..64f038a 100644 --- a/commands/filter.mjs +++ b/commands/filter.mjs @@ -403,7 +403,7 @@ export async function run(msg) { await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {}); await Utils.sleep(1500); await menuMsg.edit({ - embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, track)] + embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, player.queue.getCurrent())] }).catch(() => {}); return; } diff --git a/commands/forceleave.mjs b/commands/forceleave.mjs index bbddc31..abfbdb9 100644 --- a/commands/forceleave.mjs +++ b/commands/forceleave.mjs @@ -26,7 +26,7 @@ export async function run(msg, data) { const cid = cleanId(data.get("channelId").value); const targetChannel = this.client.channels.get(cid); if (!targetChannel) return msg.reply(embed(this.t(msg, "responses.forceleave.channelNotFound"))); - if (cleanId(msg.message.guildId) !== cleanId(targetChannel.guildId)) + if (cleanId(msg.message?.guildId) !== cleanId(targetChannel.guildId)) return msg.reply(embed(this.t(msg, "responses.forceleave.wrongServer"))); const p = this.players.playerMap.get(cid) ?? [...this.players.playerMap.values()].find((player) => cleanId(player?._channelId) === cid); diff --git a/commands/join.mjs b/commands/join.mjs index 27133e9..fd00b89 100644 --- a/commands/join.mjs +++ b/commands/join.mjs @@ -19,13 +19,13 @@ function cleanId(value) { } export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { - if (!this.client.channels.has(cid)) { + const cleanChannelId = cleanId(cid); + if (!this.client.channels.has(cleanChannelId)) { ecb(); const embed = new EmbedBuilder().setColor(getGlobalColor()) .setDescription(this.t(message, "responses.join.channelNotFound", { channel: cid })); return message.reply({ embeds: [embed] }); } - const cleanChannelId = cleanId(cid); const existing = this.players.playerMap.get(cleanChannelId) ?? [...this.players.playerMap.values()].find((player) => cleanId(player?._channelId) === cleanChannelId); if (existing) { diff --git a/commands/lastfm.mjs b/commands/lastfm.mjs index 3eb59ba..5b30ec1 100644 --- a/commands/lastfm.mjs +++ b/commands/lastfm.mjs @@ -991,7 +991,7 @@ export async function run(msg, data) { fields.push({ name: "Listeners", value: Utils.formatNumber(info.stats?.listeners ?? 0), inline: true }); fields.push({ name: "Global Plays", value: Utils.formatNumber(info.stats?.playcount ?? 0), inline: true }); - if (info.userplaycount !== null && user) { + if (info.userplaycount != null && user) { fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true }); } @@ -1085,7 +1085,7 @@ export async function run(msg, data) { fields.push({ name: "Artist", value: info.artist, inline: true }); } - if (info.userplaycount !== null && user) { + if (info.userplaycount != null && user) { fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true }); } diff --git a/commands/player.mjs b/commands/player.mjs index 831549d..a596114 100644 --- a/commands/player.mjs +++ b/commands/player.mjs @@ -294,7 +294,7 @@ export async function run(msg) { try { switch (control.action) { case "previous": - reply = this.t(msg, "responses.player.previousNotImplemented"); + reply = "Previous track is not available yet."; break; case "resume": diff --git a/commands/playnext.mjs b/commands/playnext.mjs index 8e3eca8..4a36289 100644 --- a/commands/playnext.mjs +++ b/commands/playnext.mjs @@ -55,6 +55,6 @@ export async function run(message, data) { const messages = p.playFirst(query, provider); messages.on("message", d => { const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d); - statusMsg.edit({ embeds: [embed] }).catch(() => {}); + if (statusMsg) statusMsg.edit({ embeds: [embed] }).catch(() => {}); }); } diff --git a/commands/stats.mjs b/commands/stats.mjs index 9ff3e69..548d0df 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -68,7 +68,6 @@ function getUserCount(client) { function getLivePlayerCount(playerMap) { let live = 0; - const seenGuilds = new Set(); for (const [mapKey, player] of playerMap ?? []) { if (!player || player._destroyed || player.leaving) continue; @@ -87,9 +86,6 @@ function getLivePlayerCount(playerMap) { } live++; - - const guildId = String(player._guildId ?? "").replace(/\D/g, ""); - if (guildId) seenGuilds.add(guildId); } return live; diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index d9a9760..027dd58 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -4,7 +4,7 @@ import { logger } from "./constants/Logger.mjs"; import { ServerSettings } from "./Settings.mjs"; import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.mjs"; import { VoiceStateCache } from "./constants/VoiceStateCache.mjs"; -import { REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS } from "./MessageHandler.mjs"; +import { REQUIRED_BOT_PERMISSIONS } from "./MessageHandler.mjs"; /** * GatewayHandler — manages raw WebSocket gateway events, voice-state tracking, @@ -126,7 +126,7 @@ export class GatewayHandler { ` All missing: ${missingNames.join(", ")}` ); } else { - logger.info( + logger.guild( `[GuildCreate] Server ${guildId} is missing optional permissions: ${result.optionalMissing.join(", ")}` ); } @@ -745,12 +745,12 @@ export class GatewayHandler { if (evictGuildId && evictUserId) { const currentLoc = remix.voiceCache.getUserLocation(evictGuildId, evictUserId); if (currentLoc && currentLoc.channelId === evictEntry.channelId) { - remix.voiceCache.updateUser({ guildId: evictGuildId, userId: evictUserId, channelId: null, isBot: false }); + remix.voiceCache.updateUser({ guildId: evictGuildId, userId: evictUserId, channelId: null, isBot: evictEntry.isBot ?? false }); } } } } - if (nextKey) this._prevVoiceState.set(nextKey, { channelId, guildId: guildId ?? prev?.guildId }); + if (nextKey) this._prevVoiceState.set(nextKey, { channelId, guildId: guildId ?? prev?.guildId, isBot: isBot === true }); } else { if (prevKey) this._prevVoiceState.delete(prevKey); } diff --git a/src/Player.mjs b/src/Player.mjs index 8c48279..32a2ccb 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -15,19 +15,7 @@ import Revoicejs from "revoice.js"; const { MediaPlayer } = Revoicejs; -const ConnectionState = Object.freeze({ - CONN_DISCONNECTED: 0, - CONN_CONNECTED: 1, - CONN_RECONNECTING: 2, -}); - -const LKRoomEvent = Object.freeze({ - ConnectionStateChanged: "connectionStateChanged", - Disconnected: "disconnected", - ParticipantConnected: "participantConnected", - ParticipantDisconnected:"participantDisconnected", -}); - +import { ConnectionState, LKRoomEvent } from "./constants/FluxerRevoice.mjs"; import { getVoiceManager } from "@fluxerjs/voice"; import { Utils } from "./Utils.mjs"; import { EventEmitter } from "node:events"; @@ -46,15 +34,6 @@ function mkEmbed(desc) { return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }; } -function formatMsHelper(ms) { - if (ms == null || ms < 0) return "0:00"; - const totalSeconds = Math.floor(ms / 1000); - const hours = Math.floor(totalSeconds / 3600); - const minutes = Math.floor((totalSeconds % 3600) / 60); - const seconds = totalSeconds % 60; - if (hours > 0) return `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`; - return `${minutes}:${String(seconds).padStart(2, "0")}`; -} /** NodeLink default password — centralised so it doesn't need to be hardcoded in two places. */ const NL_DEFAULT_PASSWORD = "youshallnotpass"; @@ -568,8 +547,10 @@ export default class Player extends EventEmitter { try { const room = this.connection?.room; if (room?.isConnected && room.remoteParticipants) { + const botId = this.client?.user?.id; for (const [, participant] of room.remoteParticipants) { - if (participant?.identity || participant?.sid) { + const pId = participant?.identity || participant?.sid; + if (pId && pId !== botId) { return true; } } @@ -1893,8 +1874,8 @@ export default class Player extends EventEmitter { const progressBar = this._createProgressBar(20); let trackOptLine = ""; if (this._activeTrackOpt) { - const optStart = formatMsHelper(this._activeTrackOpt.startMs); - const optEnd = this._activeTrackOpt.endMs > 0 ? formatMsHelper(this._activeTrackOpt.endMs) : "end"; + const optStart = Utils.prettifyMS(this._activeTrackOpt.startMs); + const optEnd = this._activeTrackOpt.endMs > 0 ? Utils.prettifyMS(this._activeTrackOpt.endMs) : "end"; trackOptLine = `\n✂️ Custom: ${optStart} → ${optEnd}`; } return { diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index caf843f..cd8e346 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -356,9 +356,6 @@ export class PlayerManager { this.dashboard.playerUpdate({ type: "update" }, player); }); - player.on("message", (message) => { - }); - player.on("autoleave", () => { sendUserUpdates("leave"); emitGlobal("close"); @@ -912,8 +909,6 @@ export class PlayerManager { } }); - player.on("leave", () => {}); - player.on("message", (m) => { let ch = player.textChannel; const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch })); diff --git a/src/constants/FluxerRevoice.mjs b/src/constants/FluxerRevoice.mjs index 5620d08..d979e47 100644 --- a/src/constants/FluxerRevoice.mjs +++ b/src/constants/FluxerRevoice.mjs @@ -29,19 +29,22 @@ import { EventEmitter } from "node:events"; import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice"; -const ConnectionState = Object.freeze({ +export const ConnectionState = Object.freeze({ CONN_DISCONNECTED: 0, CONN_CONNECTED: 1, CONN_RECONNECTING: 2, }); -const RoomEvent = Object.freeze({ +export const LKRoomEvent = Object.freeze({ ConnectionStateChanged: "connectionStateChanged", Disconnected: "disconnected", ParticipantConnected: "participantConnected", ParticipantDisconnected:"participantDisconnected", }); +/** @deprecated Use LKRoomEvent instead — kept for backward compat within this file */ +const RoomEvent = LKRoomEvent; + import { logger } from "./Logger.mjs"; { diff --git a/src/constants/Logger.mjs b/src/constants/Logger.mjs index 8824717..641d905 100644 --- a/src/constants/Logger.mjs +++ b/src/constants/Logger.mjs @@ -47,6 +47,10 @@ export const logger = { if (_config?.enabled === false) return; console.warn(`[${ts()}] ${tag}`, ...args); }, + info(tag, ...args) { + if (_config?.enabled === false) return; + console.log(`[${ts()}] ${tag}`, ...args); + }, player(...args) { if (isEnabled("player")) console.log(`[${ts()}]`, ...args); }, inactivity(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); }, diff --git a/src/constants/VoiceStateCache.mjs b/src/constants/VoiceStateCache.mjs index 502112f..0713cae 100644 --- a/src/constants/VoiceStateCache.mjs +++ b/src/constants/VoiceStateCache.mjs @@ -93,13 +93,9 @@ export class VoiceStateCache { if (!set) { set = new Set(); channelIdx.set(cKey, set); } set.add(cleanUser); + locations.delete(uKey); locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser }); - if (locations.has(uKey)) { - locations.delete(uKey); - locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser }); - } - while (locations.size > maxEntries) { const evictKey = locations.keys().next().value; if (evictKey === uKey) { diff --git a/src/constants/audio/Tuna.mjs b/src/constants/audio/Tuna.mjs index 407afde..2cd1d45 100644 --- a/src/constants/audio/Tuna.mjs +++ b/src/constants/audio/Tuna.mjs @@ -8,19 +8,19 @@ class Tuna { } get(path, params = {}) { return new Promise((resolve, rej) => { - var query = ""; + let query = ""; for (let key in params) { query += ((query.length === 0) ? "?" : "&") + key + "=" + encodeURIComponent(params[key]); } - var options = { + const options = { method: "GET", hostname: "tuna-api.voicemod.net", path: path + query, headers: { "x-api-key": this.apiKey }, maxRedirects: 20 }; - var req = https.request(options, function(res) { - var chunks = []; + const req = https.request(options, function(res) { + const chunks = []; res.on("data", (chunk) => { chunks.push(chunk); }); res.on("end", () => { try { diff --git a/src/dashboard/Dashboard.mjs b/src/dashboard/Dashboard.mjs index 6134833..3205611 100644 --- a/src/dashboard/Dashboard.mjs +++ b/src/dashboard/Dashboard.mjs @@ -76,21 +76,26 @@ export class Dashboard { } case "allServers": { + let guilds; try { - const guilds = await this.remix.client.user.fetchGuilds(); - return guilds.map(g => Dashboard.convertServer(g)); + guilds = await this.remix.client.user.fetchGuilds(); } catch (e) { const id = Utils.uid(); logger.dashboard("[Dashboard] allServers error:", id, e); return []; } + let result = guilds.map(g => Dashboard.convertServer(g)); if (data.accessor) { try { const accessorUser = await this.remix.client.users.fetch(data.accessor).catch(() => null); - if (accessorUser) return await this.remix.getSharedServers(accessorUser); + if (accessorUser) { + const shared = await this.remix.getSharedServers(accessorUser); + const sharedIds = new Set(shared.map(s => s.id)); + result = result.filter(g => sharedIds.has(g.id)); + } } catch (_) {} } - return []; + return result; } case "commands": { @@ -434,8 +439,8 @@ export class Dashboard { } else if (typeof user.avatarURL === "function") { try { avatarUrl = user.avatarURL() ?? ""; } catch (_) {} } - if (!avatarUrl && user.discriminator) { - avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.discriminator || "0") % 5}.png`; + if (!avatarUrl) { + avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.id?.slice(-4) ?? "0") % 5}.png`; } return { id: user.id, @@ -476,7 +481,7 @@ export class Dashboard { */ static convertChannel(channel) { const type = channel.type ?? 0; - const isVoice = channel.isVoice?.() ?? (type === 2) ?? false; + const isVoice = channel.isVoice?.() || type === 2; const isCategory = type === 4; const isText = !isVoice && !isCategory && ( type === 0 || type === 5 || type === 13 || diff --git a/src/worker.mjs b/src/worker.mjs index 8d25a71..bfabfa3 100644 --- a/src/worker.mjs +++ b/src/worker.mjs @@ -544,26 +544,14 @@ const post = (event, payload) => { }; utils.on("message", (m) => { - if (jobId === "dev") { logger.worker("[Message]", m); return; } post("message", m); }); utils.on("error", (m) => { - if (jobId === "dev") { logger.worker("[Error]", m); return; } post("error", m); }); (async () => { - if (jobId === "dev") { - try { - const result = await utils.getVideoData("Neoni funeral", "ytm"); - logger.worker("[Worker result]", result); - } catch (e) { - logger.error("[Worker error]", e); - } - return; - } - try { switch (jobId) { case "generalQuery": { diff --git a/storage/modules.json b/storage/modules.json index 1d0937b..f6acd72 100644 --- a/storage/modules.json +++ b/storage/modules.json @@ -3,10 +3,5 @@ "name": "wb-dashboard", "index": "./dashboard/index.js", "enabled": false - }, - { - "name": "rbl-stats", - "index": "./rbl.js", - "enabled": false } ]