diff --git a/commands/debug.mjs b/commands/debug.mjs index fda726a..d96c41f 100644 --- a/commands/debug.mjs +++ b/commands/debug.mjs @@ -24,7 +24,7 @@ export async function run(msg, data) { const guild = guildId ? this.client.guilds.get(String(guildId).replace(/\D/g, "")) : null; const conn = s.connection; const room = conn?.room; - const roomState = room?.state ?? "no-room"; + const roomState = room?.connectionState ?? (room?.isConnected ? "connected" : "disconnected"); const hasMediaPlayer = !!s._mediaPlayer && !s._mediaPlayer?.destroyed; return { name: channel?.name ?? "unknown", diff --git a/commands/forceleave.mjs b/commands/forceleave.mjs index 1fb4e60..bbddc31 100644 --- a/commands/forceleave.mjs +++ b/commands/forceleave.mjs @@ -4,7 +4,7 @@ import { getGlobalColor } from "../src/MessageHandler.mjs"; export const command = new CommandBuilder() .setName("forceleave") - .addAlias("fl") + .addAliases("fl") .setDescription("Make Remix leave a channel even if you're not in it.") .setRequirement(r => r.addPermission("ManageChannels")) .setCategory("music") diff --git a/commands/invite.mjs b/commands/invite.mjs index 00130f3..63f4f87 100644 --- a/commands/invite.mjs +++ b/commands/invite.mjs @@ -11,8 +11,7 @@ export const command = new CommandBuilder() export async function run(message) { const description = this.t(message, "responses.invite.description"); - const botUser = message.handler.client.user; - + const botUser = this.client?.user; const botIcon = botUser?.displayAvatarURL?.() || null; const embed = new EmbedBuilder() diff --git a/commands/join.mjs b/commands/join.mjs index b1d3bdf..e54d428 100644 --- a/commands/join.mjs +++ b/commands/join.mjs @@ -69,8 +69,8 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { } catch (_) { return "%"; } })(); const desc = is247 - ? this.t(message, "responses.join.autoLeaveInactive", { channel: activeChannelId }) - : this.t(message, "responses.join.autoLeaveInactive247", { channel: activeChannelId, prefix }); + ? this.t(message, "responses.join.autoLeaveInactive247", { channel: activeChannelId, prefix }) + : this.t(message, "responses.join.autoLeaveInactive", { channel: activeChannelId }); const embed = new EmbedBuilder().setColor(getGlobalColor()) .setDescription(desc); message.channel.send({ embeds: [embed] }); diff --git a/commands/lastfm.mjs b/commands/lastfm.mjs index 685a5ae..6518fe2 100644 --- a/commands/lastfm.mjs +++ b/commands/lastfm.mjs @@ -380,7 +380,7 @@ export async function run(msg, data) { const statusEmoji = track.now ? "🎵 Now Playing" : "🕐 Last Played"; const embed = new EmbedBuilder() .setColor(getGlobalColor()) - .setAuthor({ name: `${statusEmoji} on Last.fm`, icon_url: track.image || undefined }) + .setAuthor({ name: `${statusEmoji} on Last.fm`, iconURL: track.image || undefined }) .setDescription(`**${track.name}** by **${track.artist}**\n[Open on Last.fm](${track.url})`) .setFooter({ text: `Last.fm: ${user.username}` }); @@ -406,7 +406,7 @@ export async function run(msg, data) { const embed = new EmbedBuilder() .setColor(getGlobalColor()) - .setAuthor({ name: `Last.fm Profile: ${info.name}`, icon_url: info.image?.[2]?.["#text"] || undefined, url: info.url }) + .setAuthor({ name: `Last.fm Profile: ${info.name}`, iconURL: info.image?.[2]?.["#text"] || undefined, url: info.url }) .setDescription([ `🎵 **${Utils.formatNumber(info.playcount ?? 0)}** scrobbles`, `👤 Registered: ${info.registered?.unixtime ? new Date(+info.registered.unixtime * 1000).toLocaleDateString() : "unknown"}`, @@ -504,7 +504,7 @@ export async function run(msg, data) { }); } - return msg.reply({ embeds: [buildTrackList(user.username, "❤️ Loved Tracks", tracks)] }); + return msg.reply({ embeds: [buildTrackList(user.username, "❤️ Loved Tracks", tracks, false, prefix)] }); } // ── Top tracks ───────────────────────────────────────────────────────── @@ -527,7 +527,7 @@ export async function run(msg, data) { }); } - return msg.reply({ embeds: [buildTrackList(user.username, "📊 Top Tracks", tracks, true)] }); + return msg.reply({ embeds: [buildTrackList(user.username, "📊 Top Tracks", tracks, true, prefix)] }); } // ── Leaderboard ───────────────────────────────────────────────────── @@ -648,7 +648,7 @@ export async function run(msg, data) { }); } - return msg.reply({ embeds: [buildTrackList(user.username, "🕐 Recent Tracks", tracks)] }); + return msg.reply({ embeds: [buildTrackList(user.username, "🕐 Recent Tracks", tracks, false, prefix)] }); } default: @@ -684,7 +684,7 @@ export async function run(msg, data) { // ── Track list embed builder ────────────────────────────────────────────────── -function buildTrackList(username, title, tracks, showPlaycount = false) { +function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") { const lines = tracks.map((t, i) => { const num = String(i + 1).padStart(2, " "); let name = t.name; @@ -700,7 +700,7 @@ function buildTrackList(username, title, tracks, showPlaycount = false) { .setColor(getGlobalColor()) .setTitle(`${title} — ${username}`) .setDescription(desc) - .setFooter({ text: `💡 Use %lastfm play loved to play these!` }); + .setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` }); } // ── Leaderboard embed builder ───────────────────────────────────────────────── diff --git a/commands/remove.mjs b/commands/remove.mjs index 1b88822..7e247e8 100644 --- a/commands/remove.mjs +++ b/commands/remove.mjs @@ -1,6 +1,4 @@ import { CommandBuilder } from "../src/CommandHandler.mjs"; -import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; export const command = new CommandBuilder() .setName("remove") @@ -14,10 +12,8 @@ export const command = new CommandBuilder() export async function run(message, data) { const p = await this.getPlayer(message, false, false, false); if (!p) return; - const res = p.remove(data.options[0].value - 1); - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setDescription(res) - ; - message.reply({ embeds: [embed] }); + const index = data.get("index")?.value; + if (index == null) return message.reply("Please provide a valid queue position."); + const res = p.remove(index - 1); + message.replyEmbed(res); } diff --git a/commands/stats.mjs b/commands/stats.mjs index b25011e..00a696f 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -91,11 +91,14 @@ function getLivePlayerCount(playerMap) { if (conn) { const room = conn.room; if (room) { - const state = room.state; + // Use @livekit/rtc-node Node.js SDK API: + // room.isConnected — boolean getter (true when connected) + // room.connectionState — ConnectionState enum (0=disconnected, 1=connected, 2=reconnecting) + // room.state does NOT exist in the Node.js SDK (browser-only API) + const isConnected = room.isConnected; + const connectionState = room.connectionState; // Explicitly dead states → skip - if (state === "disconnected" || state === "failed" || state === 0) continue; - // undefined = connected on some LiveKit builds (no persistent state prop) - // "connected" = explicitly connected + if (!isConnected && (connectionState === 0 || connectionState === "disconnected")) continue; } // conn exists but no room → still a valid LiveKit connection reference } else { diff --git a/settings/Settings.mjs b/settings/Settings.mjs index 3c6f93f..d0e2d41 100644 --- a/settings/Settings.mjs +++ b/settings/Settings.mjs @@ -50,6 +50,11 @@ export class MySqlSettingsManager extends SettingsManager { constructor(config, defaultsPath) { super(); this.db = mysql.createPool({ connectionLimit: 15, ...config }); + // Without this listener, any pool-level error (connection drop, timeout, protocol error) + // fires an unhandled 'error' event which crashes the entire process with no log output. + this.db.on("error", (err) => { + logger.error("[DB] MySQL pool error:", err.code ?? err.message); + }); if (defaultsPath) this.loadDefaultsSync(defaultsPath); this.load(); } @@ -64,7 +69,7 @@ export class MySqlSettingsManager extends SettingsManager { this._loadAttempts = (this._loadAttempts || 0) + 1; const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000); logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error); - return setTimeout(() => { this.load(); }, delay); + return setTimeout(() => { this.load().catch(err => logger.error("[Settings] Retry load error:", err?.message ?? err)); }, delay); } this._loadAttempts = 0; res.results.forEach((r) => { diff --git a/src/CommandHandler.mjs b/src/CommandHandler.mjs index f6596d6..26bcd06 100644 --- a/src/CommandHandler.mjs +++ b/src/CommandHandler.mjs @@ -553,7 +553,6 @@ export class CommandHandler extends EventEmitter { let usedArgumentCount = 0; for (let i = 0, argIndex = 1; i < options.length; i++) { - if (options[i] instanceof Flag) i++; const o = options[i]; if (o?.type === "text") { texts.push(o); continue; } if ((args[argIndex] || "").startsWith("-")) { diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index ce0aa74..aecbbab 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -538,7 +538,7 @@ export class GatewayHandler { logger.guild(`[GuildDelete] Removed from server ${guildId} — cleaning up.`); for (const [channelId, player] of remix.players.playerMap) { - if (!player._guildId || player._guildId === guildId) { + if (!player._guildId || String(player._guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) { remix.players.playerMap.delete(channelId); try { player.leave().catch(() => {}); } catch (_) {} try { player.destroy(); } catch (_) {} @@ -547,10 +547,10 @@ export class GatewayHandler { } for (const [userId, info] of [...remix.observedVoiceUsers]) { - if (info.guildId === guildId) remix.observedVoiceUsers.delete(userId); + if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) remix.observedVoiceUsers.delete(userId); } for (const [userId, info] of [...remix.observedVoiceBots]) { - if (info.guildId === guildId) remix.observedVoiceBots.delete(userId); + if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) remix.observedVoiceBots.delete(userId); } for (const [stateKey, info] of [...this._prevVoiceState]) { if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) diff --git a/src/MessageHandler.mjs b/src/MessageHandler.mjs index 993c906..01a6551 100644 --- a/src/MessageHandler.mjs +++ b/src/MessageHandler.mjs @@ -319,7 +319,7 @@ export class MessageHandler { async sendMessage(channel, message) { if (this.checkPermissions(["SendMessages"], channel).length !== 0) { logger.warn("[MessageHandler] Missing SendMessages permission in channel", channel.id); - return; + return null; } let opts; if (typeof message === "string") { diff --git a/src/Player.mjs b/src/Player.mjs index ff766f3..06f5da2 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -891,7 +891,7 @@ export default class Player extends EventEmitter { } if (![200, 204, 206].includes(res.statusCode)) { res.resume(); - return reject(new Error(`HTTP ${res.statusCode} at ${target}`)); + return reject(new Error(`HTTP ${res.statusCode}`)); } if (returnStream) return resolve(res); diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 5670d13..5d9cf18 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -921,7 +921,7 @@ export class PlayerManager { if (current.title !== song.title && current.url !== song.url) return; if (player._paused) return; // don't scrobble if paused - const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs); + const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs ?? Date.now()); if (lastfm.shouldScrobble(song, playedMs)) { for (const userId of humanUserIds) { lastfm.scrobble(userId, song, startedAtMs).catch(() => {}); diff --git a/src/Settings.mjs b/src/Settings.mjs index 67959b6..a8de513 100644 --- a/src/Settings.mjs +++ b/src/Settings.mjs @@ -71,7 +71,7 @@ export class RemoteSettingsManager extends EventEmitter { // exponential backoff with a cap of 30s instead of forever-at-2s const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000); logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error); - return setTimeout(() => { this.load(); }, delay); + return setTimeout(() => { this.load().catch(err => logger.error("[Settings] Retry load error:", err?.message ?? err)); }, delay); } this._loadAttempts = 0; res.results.forEach((r) => { diff --git a/src/constants/audio/StreamMerger.mjs b/src/constants/audio/StreamMerger.mjs index f838fab..9afe41b 100644 --- a/src/constants/audio/StreamMerger.mjs +++ b/src/constants/audio/StreamMerger.mjs @@ -13,6 +13,7 @@ class StreamMerger extends Transform { } _transform(chunk, _enc, cb) { if (!this.ffmpeg) { this.push(chunk); return cb(); } + if (!this.ffmpeg.stdio?.[3]?.writable) { this.push(chunk); return cb(); } this.ffmpeg.stdio[3].write(chunk); cb(); } diff --git a/src/constants/audio/Tuna.mjs b/src/constants/audio/Tuna.mjs index 2849743..cd85fae 100644 --- a/src/constants/audio/Tuna.mjs +++ b/src/constants/audio/Tuna.mjs @@ -38,28 +38,30 @@ class Tuna { }); } search(query, page = 1, size = 10) { - return new Promise(async res => { - const results = await this.get("/v1/sounds/search", { size, page, search: query }); + return this.get("/v1/sounds/search", { size, page, search: query }).then(results => { results.items = results.items.map(s => { s.download = function() { - return new Promise(resolve => { - https.get(this.oggPath, (r) => { resolve(r); }); + return new Promise((resolve, reject) => { + const req = https.get(this.oggPath, (r) => { resolve(r); }); + req.on("error", (err) => { reject(err); }); + req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); }); }); }; return s; }); - res(results); + return results; }); } getSound(id) { - return new Promise(async res => { - const sound = await this.get("/v1/sounds/" + id); + return this.get("/v1/sounds/" + id).then(sound => { sound.download = function() { - return new Promise(res => { - https.get(this.oggPath, (result) => { res(result); }); + return new Promise((resolve, reject) => { + const req = https.get(this.oggPath, (result) => { resolve(result); }); + req.on("error", (err) => { reject(err); }); + req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); }); }); }; - res(sound); + return sound; }); } } diff --git a/src/worker.mjs b/src/worker.mjs index b95ffc3..ac82270 100644 --- a/src/worker.mjs +++ b/src/worker.mjs @@ -300,7 +300,7 @@ class YTUtils extends EventEmitter { let tracks = []; if (data.loadType === "search") tracks = data.data ?? []; - else if (data.loadType === "track") tracks = [data.data]; + else if (data.loadType === "track") tracks = data.data ? [data.data] : []; else if (data.loadType === "playlist") tracks = data.data?.tracks ?? []; const resultTracks = this._rankTracks(tracks, provider); @@ -335,12 +335,18 @@ class YTUtils extends EventEmitter { } // Handle single track - if (data.loadType === "track") { + if (data.loadType === "track" && data.data) { const video = trackToVideo(data.data); + if (!video) return { type: "error", data: "Failed to parse track data." }; this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`); return { type: "video", data: video }; } + if (data.loadType === "track" && !data.data) { + this.emit("message", `**Track data was empty for '${query}'.**`); + return { type: "error", data: "Empty track data returned." }; + } + // Handle search results (take first) if (data.loadType === "search" && data.data?.length) { const bestTrack = this._pickBestTrack(data.data, provider) ?? data.data[0]; @@ -383,12 +389,18 @@ class YTUtils extends EventEmitter { } // Single track from search - if (data.loadType === "track") { + if (data.loadType === "track" && data.data) { const video = trackToVideo(data.data); + if (!video) return { type: "error", data: "Failed to parse track data." }; this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`); return { type: "video", data: video }; } + if (data.loadType === "track" && !data.data) { + this.emit("message", `**Track data was empty for '${query}'.**`); + return { type: "error", data: "Empty track data returned." }; + } + // Nothing found this.emit("message", `**No results found for '${query}'.**`); return { type: "error", data: null, error: "No results found" };