feat: audio filters, rate limiting, stability fixes & new announcement channel

feat(filter): add %filter command with Bass Boost, Nightcore, Vaporwave,
  8D, Karaoke, Tremolo and more; filter status now shown in %player UI

feat(player): add Filter button (🎛️) to player controls; display active
  filter name/emoji in queue status line

feat(commands): add per-user command cooldown (1.5s) in CommandHandler;
  owners are exempt so %reload/%eval are never blocked

feat(settings): debounce rapid set() calls into a single remoteSave()
  80ms after the last write; prevents N parallel DB queries per command

feat(storage): add announcementChannelId field to defaults.json

fix(play): wrap statusMsg send in try/catch; fall back to fresh reply
  if the initial status message fails to send

fix(stats): normalise guild.members.fetch() result (Collection, array,
  or plain object) to avoid infinite pagination loop; use memberCount
  as primary member count

fix(search): normalise reaction event user ID across Fluxer event shapes
  (user_id / userId / user.id) so author filter works reliably

fix(forceleave): await this.players.leave() — was missing await, could
  silently swallow errors

fix(MessageHandler): guard register() against double-call on hot-reload;
  second call now returns early to prevent duplicate listeners

fix(MoonlinkManager): add getLiveSessionId() helper that walks active
  nodes to find a valid session before falling back to cached value

fix(reload): use pathToFileURL() for cache-busting import URL so Windows
  drive letters and spaces in paths are handled correctly

fix(eval): broaden sensitive-key list (mysql, nodelink, _nl, credential,
  apikey, webhook); increase scan depth to 6; handle circular refs in
  hasSensitive(); normalise keys to lowercase for matching

fix(worker): compile sanitize regexes once at module load instead of
  on every sanitizeError() call

fix(Player): cache compiled sanitize regexes keyed by host:port:password
  to avoid rebuilding identical RegExp objects on every error path

fix(index): wrap config.json read in try/catch with clear FATAL messages
  for missing file or malformed JSON; validate required keys at startup

config: add rest.timeout/retries and nodelink requestTimeout to
  config_example.json with explanatory comments
This commit is contained in:
NoLogicAlan committed 2026-04-23 17:19:49 +03:00
1 parent c339e32e9c
commit 57f018c815
17 files changed
+454 -218

No files matched your search

+26 -9
View File
@@ -8,29 +8,46 @@ const EMOJI_REMOVE_TIMEOUT = 60000;
/** /**
* List of keys that should be redacted from objects before displaying in Discord. * List of keys that should be redacted from objects before displaying in Discord.
* Matches any key that *contains* one of these strings (case-insensitive).
*/ */
const RESTRICTED = [ const RESTRICTED = [
"token", "token",
"config", "config",
"key", "key",
"clientSecret", "clientsecret",
"clientId", "clientid",
"password", "password",
"secret", "secret",
"authorization" "authorization",
"mysql",
"nodelink",
"_nl",
"credential",
"apikey",
"webhook",
]; ];
function hasSensitive(obj, level = 0) { // Maximum depth for sensitive-key scanning and redaction.
if (level >= 3 || typeof obj !== "object" || obj === null) return false; // 6 covers deeply nested config objects (e.g. config.nodelink.password nested
// inside player config) without risking stack overflow on circular references.
const SCAN_DEPTH = 6;
// Track visited objects to handle circular references
function hasSensitive(obj, level = 0, visited = new WeakSet()) {
if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return false;
if (visited.has(obj)) return false;
visited.add(obj);
for (const key in obj) { for (const key in obj) {
if (RESTRICTED.some(r => key.toLowerCase().includes(r))) return true; if (RESTRICTED.some(r => key.toLowerCase().includes(r))) return true;
if (typeof obj[key] === "object" && hasSensitive(obj[key], level + 1)) return true; if (typeof obj[key] === "object" && hasSensitive(obj[key], level + 1, visited)) return true;
} }
return false; return false;
} }
function removeSensitive(obj, level = 0) { function removeSensitive(obj, level = 0, visited = new WeakSet()) {
if (level >= 3 || typeof obj !== "object" || obj === null) return obj; if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return obj;
if (visited.has(obj)) return "[Circular]";
visited.add(obj);
const isArray = Array.isArray(obj); const isArray = Array.isArray(obj);
const newObj = isArray ? [...obj] : { ...obj }; const newObj = isArray ? [...obj] : { ...obj };
@@ -43,7 +60,7 @@ function removeSensitive(obj, level = 0) {
newObj[key] = "[REDACTED]"; newObj[key] = "[REDACTED]";
modified = true; modified = true;
} else if (typeof newObj[key] === "object" && newObj[key] !== null) { } else if (typeof newObj[key] === "object" && newObj[key] !== null) {
const cleaned = removeSensitive(newObj[key], level + 1); const cleaned = removeSensitive(newObj[key], level + 1, visited);
if (cleaned !== newObj[key]) { if (cleaned !== newObj[key]) {
newObj[key] = cleaned; newObj[key] = cleaned;
modified = true; modified = true;
+1 -1
View File
@@ -27,5 +27,5 @@ export async function run(msg, data) {
const p = this.players.playerMap.get(cid); const p = this.players.playerMap.get(cid);
if (!p) return msg.replyEmbed(embed("❌ Player not found.")); if (!p) return msg.replyEmbed(embed("❌ Player not found."));
if (!p.connection) return msg.replyEmbed(embed("❌ Player not initialized.")); if (!p.connection) return msg.replyEmbed(embed("❌ Player not initialized."));
this.players.leave(msg, cid); await this.players.leave(msg, cid);
} }
+12 -1
View File
@@ -58,11 +58,22 @@ export async function run(message, data) {
.setColor(getGlobalColor()) .setColor(getGlobalColor())
.setDescription("🔍 Searching...") .setDescription("🔍 Searching...")
.toJSON(); .toJSON();
const statusMsg = await message.replyEmbed({ embeds: [searchEmbed] });
let statusMsg = null;
try {
statusMsg = await message.replyEmbed({ embeds: [searchEmbed] });
} catch (err) {
// Fluxer API timed out sending the status message — continue without it
}
const messages = p.play(query, false, provider); const messages = p.play(query, false, provider);
messages.on("message", d => { messages.on("message", d => {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d).toJSON(); const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d).toJSON();
if (statusMsg) {
statusMsg.editEmbed({ embeds: [embed] }).catch(() => {}); statusMsg.editEmbed({ embeds: [embed] }).catch(() => {});
} else {
// statusMsg failed to send earlier, fall back to a fresh reply
message.replyEmbed({ embeds: [embed] }).catch(() => {});
}
}); });
} }
+36 -31
View File
@@ -28,6 +28,7 @@ const CONTROLS = {
volDown: { emoji: "🔉", action: "voldown", desc: "Volume Down" }, volDown: { emoji: "🔉", action: "voldown", desc: "Volume Down" },
volUp: { emoji: "🔊", action: "volup", desc: "Volume Up" }, volUp: { emoji: "🔊", action: "volup", desc: "Volume Up" },
lyrics: { emoji: "📜", action: "lyrics", desc: "Lyrics" }, lyrics: { emoji: "📜", action: "lyrics", desc: "Lyrics" },
filter: { emoji: "🎛️", action: "filter", desc: "Audio Filters" },
close: { emoji: "❌", action: "close", desc: "Close" } close: { emoji: "❌", action: "close", desc: "Close" }
}; };
@@ -51,7 +52,7 @@ export async function run(msg) {
const controlsLayout = [ const controlsLayout = [
[CONTROLS.prev, CONTROLS.play, CONTROLS.pause, CONTROLS.stop, CONTROLS.next], [CONTROLS.prev, CONTROLS.play, CONTROLS.pause, CONTROLS.stop, CONTROLS.next],
[CONTROLS.loop, CONTROLS.shuffle, CONTROLS.volDown, CONTROLS.volUp, CONTROLS.lyrics], [CONTROLS.loop, CONTROLS.shuffle, CONTROLS.volDown, CONTROLS.volUp, CONTROLS.lyrics],
[CONTROLS.close] [CONTROLS.filter, CONTROLS.close]
]; ];
const allControls = controlsLayout.flat(); const allControls = controlsLayout.flat();
@@ -83,7 +84,6 @@ export async function run(msg) {
PROGRESS.empty.repeat(emptyCount) + PROGRESS.empty.repeat(emptyCount) +
PROGRESS.end; PROGRESS.end;
// Use Utils.prettifyMS instead of local formatTime
const elapsedStr = Utils.prettifyMS(elapsed); const elapsedStr = Utils.prettifyMS(elapsed);
const totalStr = Utils.prettifyMS(totalMs); const totalStr = Utils.prettifyMS(totalMs);
timeDisplay = `\`${elapsedStr} / ${totalStr}\``; timeDisplay = `\`${elapsedStr} / ${totalStr}\``;
@@ -98,8 +98,17 @@ export async function run(msg) {
const queueSize = player.queue.size(); const queueSize = player.queue.size();
const loopStatus = player.queue.songLoop ? "🔂 Song" : player.queue.loop ? "🔁 Queue" : "❌ Off"; const loopStatus = player.queue.songLoop ? "🔂 Song" : player.queue.loop ? "🔁 Queue" : "❌ Off";
// FIXED: Show stacked filters if multiple are active
let filterStatus = "🔇 Off";
if (player.activeFilter) {
if (player.activeFilter.label.includes("+")) {
filterStatus = `🔥 **${player.activeFilter.label}**`;
} else {
filterStatus = `${player.activeFilter.emoji ?? "🎛️"} **${player.activeFilter.label}**`;
}
}
const nowPlaying = current const nowPlaying = current
// Use Utils.truncate instead of local truncate
? `[${Utils.truncate(current.title, 45)}](${current.spotifyUrl || current.url})` ? `[${Utils.truncate(current.title, 45)}](${current.spotifyUrl || current.url})`
: "*Nothing playing*"; : "*Nothing playing*";
@@ -111,15 +120,13 @@ export async function run(msg) {
`${timeDisplay}`, `${timeDisplay}`,
``, ``,
`🔊 Volume: \`${volPercent}%\` ${volumeBar}`, `🔊 Volume: \`${volPercent}%\` ${volumeBar}`,
`📋 Queue: \`${queueSize}\` tracks | Loop: ${loopStatus}`, `📋 Queue: \`${queueSize}\` tracks | Loop: ${loopStatus} | Filter: ${filterStatus}`,
``, ``,
state.message ? `💬 *${state.message}*` : "💡 *React to control playback*", state.message ? `💬 *${state.message}*` : "💡 *React to control playback*",
``, ``,
`⏱️ Session expires in ${Math.ceil(timeout / 60000)}m of inactivity` `⏱️ Session expires in ${Math.ceil(timeout / 60000)}m of inactivity`
].join("\n"); ].join("\n");
// avatarURL may be a plain property (Fluxer) or a method— call it if
// it's a function, otherwise use it as-is so the footer icon works in both cases.
const avatarUrl = typeof msg.author?.avatarURL === "function" const avatarUrl = typeof msg.author?.avatarURL === "function"
? msg.author.avatarURL() ? msg.author.avatarURL()
: msg.author?.avatarURL ?? null; : msg.author?.avatarURL ?? null;
@@ -132,7 +139,6 @@ export async function run(msg) {
text: `Requested by ${msg.author?.username || "Unknown"} • Controls active`, text: `Requested by ${msg.author?.username || "Unknown"} • Controls active`,
iconURL: avatarUrl iconURL: avatarUrl
}); });
// setTimestamp() is not verified on @fluxerjs/core's EmbedBuilder — guard it.
if (typeof builder.setTimestamp === "function") builder.setTimestamp(); if (typeof builder.setTimestamp === "function") builder.setTimestamp();
if (current?.thumbnail) builder.setThumbnail(current.thumbnail); if (current?.thumbnail) builder.setThumbnail(current.thumbnail);
return builder.toJSON(); return builder.toJSON();
@@ -141,12 +147,11 @@ export async function run(msg) {
const message = await msg.replyEmbed({ embeds: [buildEmbed()] }); const message = await msg.replyEmbed({ embeds: [buildEmbed()] });
if (!message?.message) return; if (!message?.message) return;
// Add reactions with staggered animation
for (const row of controlsLayout) { for (const row of controlsLayout) {
for (const control of row) { for (const control of row) {
try { try {
await message.message.react(control.emoji); await message.message.react(control.emoji);
await Utils.sleep(200); // Use Utils.sleep instead of inline Promise await Utils.sleep(200);
} catch (_) {} } catch (_) {}
} }
} }
@@ -156,12 +161,10 @@ export async function run(msg) {
let emojiRemoveTimeout; let emojiRemoveTimeout;
let lastState = {}; let lastState = {};
// Track active lyrics message
let activeLyricsMsg = null; let activeLyricsMsg = null;
let lyricsUnobserve = null; let lyricsUnobserve = null;
let lyricsEmojiTimeout = null; let lyricsEmojiTimeout = null;
// Helper: Clear all reactions
const clearReactions = async () => { const clearReactions = async () => {
try { try {
await message.message.removeAllReactions(); await message.message.removeAllReactions();
@@ -174,7 +177,6 @@ export async function run(msg) {
} }
}; };
// Helper: Reset emoji removal timer
const resetEmojiTimer = () => { const resetEmojiTimer = () => {
clearTimeout(emojiRemoveTimeout); clearTimeout(emojiRemoveTimeout);
emojiRemoveTimeout = setTimeout(async () => { emojiRemoveTimeout = setTimeout(async () => {
@@ -185,7 +187,6 @@ export async function run(msg) {
}, EMOJI_REMOVE_TIMEOUT); }, EMOJI_REMOVE_TIMEOUT);
}; };
// Helper: Clear lyrics reactions
const clearLyricsReactions = async (lyricsMsg) => { const clearLyricsReactions = async (lyricsMsg) => {
if (!lyricsMsg?.message) return; if (!lyricsMsg?.message) return;
try { try {
@@ -211,15 +212,14 @@ export async function run(msg) {
clearInterval(updateInterval); clearInterval(updateInterval);
unobserve?.(); unobserve?.();
// Remove all player event listeners added by this session
player.off("startplay", onStartPlay); player.off("startplay", onStartPlay);
player.off("playback", onPlayback); player.off("playback", onPlayback);
player.off("stopplay", onStopPlay); player.off("stopplay", onStopPlay);
player.off("queue", onQueue); player.off("queue", onQueue);
player.off("volume", onVolume); player.off("volume", onVolume);
player.off("filter", onFilter);
player.off("autoleave", onAutoLeave); player.off("autoleave", onAutoLeave);
// Cleanup any active lyrics
if (lyricsUnobserve) { if (lyricsUnobserve) {
lyricsUnobserve(); lyricsUnobserve();
clearTimeout(lyricsEmojiTimeout); clearTimeout(lyricsEmojiTimeout);
@@ -233,7 +233,6 @@ export async function run(msg) {
const closedEmbed = buildEmbed({ const closedEmbed = buildEmbed({
message: `Session closed${reason !== "timeout" ? ` • ${reason}` : " due to inactivity"}` message: `Session closed${reason !== "timeout" ? ` • ${reason}` : " due to inactivity"}`
}); });
// Override title and footer on the plain object returned by toJSON()
closedEmbed.color = getGlobalColor(); closedEmbed.color = getGlobalColor();
closedEmbed.footer = { text: "Session ended" }; closedEmbed.footer = { text: "Session ended" };
closedEmbed.title = "🎧 Music Player (Inactive)"; closedEmbed.title = "🎧 Music Player (Inactive)";
@@ -249,14 +248,12 @@ export async function run(msg) {
sessionTimeout = setTimeout(() => closeSession("timeout"), timeout); sessionTimeout = setTimeout(() => closeSession("timeout"), timeout);
}; };
// Live progress updates
updateInterval = setInterval(() => { updateInterval = setInterval(() => {
if (!player.paused && player.queue.getCurrent()) { if (!player.paused && player.queue.getCurrent()) {
refresh(lastState); refresh(lastState);
} }
}, this.config?.timers?.playerUpdateInterval ?? 5000); }, this.config?.timers?.playerUpdateInterval ?? 5000);
// Player events — store named handlers so we can remove them on closeSession
const onStartPlay = () => refresh({ message: "▶️ Started playing" }); const onStartPlay = () => refresh({ message: "▶️ Started playing" });
const onPlayback = (playing) => refresh({ message: playing ? "▶️ Resumed" : "⏸️ Paused" }); const onPlayback = (playing) => refresh({ message: playing ? "▶️ Resumed" : "⏸️ Paused" });
const onStopPlay = () => refresh({ message: "⏹️ Stopped" }); const onStopPlay = () => refresh({ message: "⏹️ Stopped" });
@@ -265,6 +262,15 @@ export async function run(msg) {
if (e.type === "add") refresh({ message: `➕ Added: ${Utils.truncate(e.data.data.title, 30)}` }); if (e.type === "add") refresh({ message: `➕ Added: ${Utils.truncate(e.data.data.title, 30)}` });
}; };
const onVolume = (v) => refresh({ message: `🔊 Volume: ${Math.round(v * 100)}%` }); const onVolume = (v) => refresh({ message: `🔊 Volume: ${Math.round(v * 100)}%` });
const onFilter = (f) => {
if (!f) {
refresh({ message: "🔇 Filters cleared" });
} else if (f.label.includes("+")) {
refresh({ message: `🔥 Filters: **${f.label}** applied` });
} else {
refresh({ message: `${f.emoji ?? "🎛️"} Filter: **${f.label}** applied` });
}
};
const onAutoLeave = () => closeSession("disconnected"); const onAutoLeave = () => closeSession("disconnected");
player.on("startplay", onStartPlay); player.on("startplay", onStartPlay);
@@ -272,9 +278,9 @@ export async function run(msg) {
player.on("stopplay", onStopPlay); player.on("stopplay", onStopPlay);
player.on("queue", onQueue); player.on("queue", onQueue);
player.on("volume", onVolume); player.on("volume", onVolume);
player.on("filter", onFilter);
player.on("autoleave", onAutoLeave); player.on("autoleave", onAutoLeave);
// Reaction handler
const unobserve = message.onReaction(controlEmojis, async (e) => { const unobserve = message.onReaction(controlEmojis, async (e) => {
const control = allControls.find(c => c.emoji === e.emoji_id); const control = allControls.find(c => c.emoji === e.emoji_id);
if (!control) return; if (!control) return;
@@ -349,12 +355,22 @@ export async function run(msg) {
break; break;
} }
case "filter":
reply = "🎛️ Opening filter picker — check the filter menu above or use the `filter` command.";
shouldUpdate = true;
try {
const { run: runFilter } = await import("./filter.mjs");
runFilter.call(this, msg);
} catch (err) {
reply = `⚠️ Filter error: ${Utils.truncate(err.message, 50)}`;
}
break;
case "lyrics": case "lyrics":
reply = "📜 Fetching lyrics..."; reply = "📜 Fetching lyrics...";
refresh({ message: reply }); refresh({ message: reply });
try { try {
// Cleanup previous lyrics
if (lyricsUnobserve) { if (lyricsUnobserve) {
lyricsUnobserve(); lyricsUnobserve();
clearTimeout(lyricsEmojiTimeout); clearTimeout(lyricsEmojiTimeout);
@@ -374,7 +390,6 @@ export async function run(msg) {
const LINES_PER_PAGE = 25; const LINES_PER_PAGE = 25;
const totalPages = Math.ceil(totalLines / LINES_PER_PAGE); const totalPages = Math.ceil(totalLines / LINES_PER_PAGE);
// Build pages
const pages = []; const pages = [];
for (let i = 0; i < totalLines; i += LINES_PER_PAGE) { for (let i = 0; i < totalLines; i += LINES_PER_PAGE) {
pages.push(lines.slice(i, i + LINES_PER_PAGE).join('\n')); pages.push(lines.slice(i, i + LINES_PER_PAGE).join('\n'));
@@ -403,17 +418,14 @@ export async function run(msg) {
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText }).toJSON()] }; return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText }).toJSON()] };
}; };
// Send initial lyrics
activeLyricsMsg = await msg.replyEmbed(buildLyricsContent(0)); activeLyricsMsg = await msg.replyEmbed(buildLyricsContent(0));
// Add pagination and close button if needed
if (activeLyricsMsg?.message && totalPages > 1) { if (activeLyricsMsg?.message && totalPages > 1) {
const navEmojis = ["⬅️", "➡️", "❌"]; const navEmojis = ["⬅️", "➡️", "❌"];
for (const emoji of navEmojis) { for (const emoji of navEmojis) {
await activeLyricsMsg.message.react(emoji).catch(() => {}); await activeLyricsMsg.message.react(emoji).catch(() => {});
} }
// Reset timer helper
const resetLyricsTimer = () => { const resetLyricsTimer = () => {
clearTimeout(lyricsEmojiTimeout); clearTimeout(lyricsEmojiTimeout);
lyricsEmojiTimeout = setTimeout(async () => { lyricsEmojiTimeout = setTimeout(async () => {
@@ -422,9 +434,7 @@ export async function run(msg) {
}, EMOJI_REMOVE_TIMEOUT); }, EMOJI_REMOVE_TIMEOUT);
}; };
// Navigation handler
lyricsUnobserve = activeLyricsMsg.onReaction(navEmojis, async (e) => { lyricsUnobserve = activeLyricsMsg.onReaction(navEmojis, async (e) => {
// Close button
if (e.emoji_id === "❌") { if (e.emoji_id === "❌") {
lyricsUnobserve(); lyricsUnobserve();
clearTimeout(lyricsEmojiTimeout); clearTimeout(lyricsEmojiTimeout);
@@ -433,7 +443,6 @@ export async function run(msg) {
return; return;
} }
// Reset timer on navigation
resetLyricsTimer(); resetLyricsTimer();
if (e.emoji_id === "⬅️") { if (e.emoji_id === "⬅️") {
@@ -445,10 +454,8 @@ export async function run(msg) {
await activeLyricsMsg.editEmbed(buildLyricsContent(currentPage)); await activeLyricsMsg.editEmbed(buildLyricsContent(currentPage));
}); });
// Start 1 minute timer
resetLyricsTimer(); resetLyricsTimer();
} else if (activeLyricsMsg?.message) { } else if (activeLyricsMsg?.message) {
// Single page - just add close button
await activeLyricsMsg.message.react("❌").catch(() => {}); await activeLyricsMsg.message.react("❌").catch(() => {});
const resetLyricsTimer = () => { const resetLyricsTimer = () => {
@@ -474,7 +481,6 @@ export async function run(msg) {
reply = `Lyrics displayed (${totalLines} lines, ${totalPages} pages)`; reply = `Lyrics displayed (${totalLines} lines, ${totalPages} pages)`;
} catch (err) { } catch (err) {
// Use Utils.truncate instead of local truncate
reply = `⚠️ Lyrics error: ${Utils.truncate(err.message, 50)}`; reply = `⚠️ Lyrics error: ${Utils.truncate(err.message, 50)}`;
} }
shouldUpdate = true; shouldUpdate = true;
@@ -491,7 +497,6 @@ export async function run(msg) {
if (shouldUpdate) refresh({ message: reply }); if (shouldUpdate) refresh({ message: reply });
}); });
// Start timers
resetTimeout(); resetTimeout();
resetEmojiTimer(); resetEmojiTimer();
} }
+3 -2
View File
@@ -40,8 +40,9 @@ async function reloadCommand(ctx, name) {
ctx.runnables.delete(command.uid); ctx.runnables.delete(command.uid);
ctx.commandFiles.delete(command.uid); ctx.commandFiles.delete(command.uid);
// Re-import with cache-buster // Re-import with cache-buster — use pathToFileURL so Windows drive letters and
const url = "file://" + file + "?t=" + Date.now(); // spaces in paths are handled correctly (plain "file://" + path breaks on Windows).
const url = pathToFileURL(file).href + "?t=" + Date.now();
const cData = await import(url); const cData = await import(url);
const raw = cData.command ?? cData.default?.command; const raw = cData.command ?? cData.default?.command;
+3 -2
View File
@@ -127,8 +127,9 @@ export async function run(msg, data) {
const authorId = msg.message?.author?.id ?? msg.authorId; const authorId = msg.message?.author?.id ?? msg.authorId;
const unobserve = wrapped.onReaction(allReactions, async (e, reactionMsg) => { const unobserve = wrapped.onReaction(allReactions, async (e, reactionMsg) => {
// Only react to the command author // Only react to the command author — normalise across Fluxer reaction event shapes
if (e.user_id && e.user_id !== authorId) return; const reactorId = e.user_id ?? e.userId ?? e.user?.id ?? null;
if (reactorId && reactorId !== authorId) return;
clearTimeout(timer); clearTimeout(timer);
unobserve(); unobserve();
+17 -5
View File
@@ -33,15 +33,27 @@ async function fetchGuildMemberCount(guild) {
try { try {
let after = undefined; let after = undefined;
let total = 0; let total = 0;
while (true) { // Guard against runaway pagination: Fluxer may have far fewer than 1000 members
const batch = await guild.members.fetch({ limit: 1000, after }); // but return a Collection (Map-like) instead of an array, causing batch.length
// to be undefined and the loop to run forever. Normalise to an array first.
for (let page = 0; page < 1000; page++) {
const raw = await guild.members.fetch({ limit: 1000, after });
// Normalise: Collection (Map), array, or plain object → array
const batch = Array.isArray(raw)
? raw
: typeof raw?.values === "function"
? [...raw.values()]
: Object.values(raw ?? {});
total += batch.length; total += batch.length;
if (batch.length < 1000) break; if (batch.length < 1000) break;
after = batch.reduce((max, m) => (m.id > max ? m.id : max), "0"); after = batch.reduce((max, m) => {
const id = m.id ?? m.user?.id ?? "";
return id > max ? id : max;
}, "0");
} }
return total; return total;
} catch { } catch {
return guild.members.size ?? 0; return guild.memberCount ?? guild.members?.size ?? 0;
} }
} }
@@ -104,7 +116,7 @@ export async function run(message) {
const hasCached = cachedUserCount !== null; const hasCached = cachedUserCount !== null;
// Measure real Discord round-trip latency // Measure real round-trip latency
const start = Date.now(); const start = Date.now();
const msg = await message.replyEmbed({ const msg = await message.replyEmbed({
embeds: [buildEmbed({ ...shared, userCount: hasCached ? cachedUserCount : 0, ping: 0, loading: !hasCached })] embeds: [buildEmbed({ ...shared, userCount: hasCached ? cachedUserCount : 0, ping: 0, loading: !hasCached })]
+9 -2
View File
@@ -1,7 +1,12 @@
{ {
"token": "your bot token", "token": "your bot token",
"fluxer.js": { "fluxer.js": {
"Comment": "Configuration data for @fluxerjs/core Client options. See: https://github.com/fluxerjs/core" "Comment": "Configuration data for @fluxerjs/core Client options. See: https://github.com/fluxerjs/core",
"rest": {
"Comment": "REST client options. 'timeout' is ms before a request to api.fluxer.app is aborted (default: 15000). Raise if you see DOMException AbortError in logs.",
"timeout": 30000,
"retries": 3
}
}, },
"fluxer-api": { "fluxer-api": {
"Comment": "Configuration options for a fluxer REST client if self-hosting. See: https://docs.fluxer.app" "Comment": "Configuration options for a fluxer REST client if self-hosting. See: https://docs.fluxer.app"
@@ -16,7 +21,9 @@
"nodelink": { "nodelink": {
"host": "localhost", "host": "localhost",
"port": 3000, "port": 3000,
"password": "youshallnotpass" "password": "youshallnotpass",
"requestTimeout": 60000,
"Comment": "requestTimeout: ms before a NodeLink HTTP request is aborted. Default: 60000 (60s). Raise if you see 'NodeLink request timeout' errors."
}, },
"comment-radio": { "comment-radio": {
"message": "If you have radio stations you'd like to connect, add them to the array below. Radio stations must be rendered like following:", "message": "If you have radio stations you'd like to connect, add them to the array below. Radio stations must be rendered like following:",
+75 -16
View File
@@ -14,7 +14,24 @@ import mysql from "mysql";
class Remix { class Remix {
constructor() { constructor() {
const config = JSON.parse(fs.readFileSync("config.json")); let config;
try {
config = JSON.parse(fs.readFileSync("config.json", "utf8"));
} catch (e) {
const reason = e.code === "ENOENT"
? "config.json not found. Copy config_example.json → config.json and fill in your values."
: `config.json is malformed JSON: ${e.message}`;
console.error(`[Startup] FATAL: ${reason}`);
process.exit(1);
}
// Validate required top-level keys so missing config fails fast with a clear message
const REQUIRED_KEYS = ["token", "mysql"];
for (const key of REQUIRED_KEYS) {
if (config[key] == null) {
console.error(`[Startup] FATAL: config.json is missing required key "${key}".`);
process.exit(1);
}
}
this.config = config; this.config = config;
// Apply embed color from config globally // Apply embed color from config globally
@@ -34,7 +51,11 @@ class Remix {
}; };
const client = new Client({ const client = new Client({
intents: 0, // Fluxer uses server-side intent declarations; intents here are informational.
// Set to the bitmask your bot actually has enabled on the developer dashboard so
// that a missing-intent failure is visible at startup rather than silently breaking
// voice state tracking. 0 = inherit from gateway (Fluxer default).
intents: config["fluxer.js"]?.intents ?? 0,
...config["fluxer.js"], ...config["fluxer.js"],
presence: presenceContents.length > 0 ? { presence: presenceContents.length > 0 ? {
status: "online", status: "online",
@@ -189,9 +210,15 @@ class Remix {
["false", "0", "no", "off", "disable"].includes(String(raw).toLowerCase().trim()); ["false", "0", "no", "off", "disable"].includes(String(raw).toLowerCase().trim());
if (disabled) return; if (disabled) return;
const guild = this.client.guilds.cache.get(guildId); const guild = this.client.guilds.cache.get(guildId);
// _announcementChannelCache is always a Map — no null check needed. // Announcement channel lookup order:
const cachedChId = this._announcementChannelCache.get(guildId); // 1. In-memory cache (fastest — populated on first find after startup)
let ch = cachedChId ? guild?.channels?.cache?.get(cachedChId) : null; // 2. Persisted setting "announcementChannelId" (survives restarts)
// 3. Channel scan (expensive — only on first use per guild per process lifetime)
const serverSet = this.settingsMgr.getServer(guildId);
const cachedChId = this._announcementChannelCache.get(guildId)
?? serverSet.get("announcementChannelId")
?? null;
let ch = cachedChId ? guild?.channels?.cache?.get(String(cachedChId)) : null;
// if cached channel is gone (deleted/uncached), clear the stale // if cached channel is gone (deleted/uncached), clear the stale
// entry immediately so we don't re-scan on every subsequent message event. // entry immediately so we don't re-scan on every subsequent message event.
if (cachedChId && !ch) { if (cachedChId && !ch) {
@@ -202,7 +229,13 @@ class Remix {
(c.isTextBased?.() ?? c.channel_type === "TextChannel" ?? true) && (c.isTextBased?.() ?? c.channel_type === "TextChannel" ?? true) &&
(c.permissionsFor?.(this.client.user)?.has?.("SendMessages") ?? true) (c.permissionsFor?.(this.client.user)?.has?.("SendMessages") ?? true)
); );
if (ch) this._announcementChannelCache.set(guildId, ch.id); if (ch) {
this._announcementChannelCache.set(guildId, ch.id);
// Persist so future restarts skip the expensive channel scan
if (serverSet.get("announcementChannelId") !== ch.id) {
serverSet.set("announcementChannelId", ch.id);
}
}
} }
ch?.send({ embeds: [{ description: String(m), color: getGlobalColor() }] }).catch(() => {}); ch?.send({ embeds: [{ description: String(m), color: getGlobalColor() }] }).catch(() => {});
}); });
@@ -540,6 +573,17 @@ class Remix {
if (!guildId) return; if (!guildId) return;
// ── Part 1: Voice state population ────────────────────────────────────── // ── Part 1: Voice state population ──────────────────────────────────────
// Purge stale entries for this guild first so old voice state from a previous
// READY cycle or an offline period doesn't persist after reconnect.
for (const [uid, info] of [...this.observedVoiceUsers]) {
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, ""))
this.observedVoiceUsers.delete(uid);
}
for (const [uid, info] of [...this.observedVoiceBots]) {
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, ""))
this.observedVoiceBots.delete(uid);
}
const voiceStatesRaw = const voiceStatesRaw =
guild.voice_states ?? guild.voice_states ??
guild.voiceStates?.cache ?? guild.voiceStates?.cache ??
@@ -583,8 +627,11 @@ class Remix {
if (!this.settingsMgr.guilds.has(guildId)) { if (!this.settingsMgr.guilds.has(guildId)) {
logger.guild(`[GuildCreate] (Re-)joined server ${guildId} — initialising settings.`); logger.guild(`[GuildCreate] (Re-)joined server ${guildId} — initialising settings.`);
try { try {
// Validate guildId is a non-empty snowflake string before using in query
const cleanGuildId = String(guildId).replace(/\D/g, "");
if (!cleanGuildId) throw new Error("Invalid guildId: " + guildId);
const res = await this.settingsMgr.query( const res = await this.settingsMgr.query(
`SELECT * FROM settings WHERE id=${mysql.escape(guildId)}` `SELECT * FROM settings WHERE id=${mysql.escape(cleanGuildId)}`
); );
if (res?.results?.length) { if (res?.results?.length) {
const row = res.results[0]; const row = res.results[0];
@@ -607,6 +654,12 @@ class Remix {
} }
}); });
// Track previous voice state per-user so we can detect channel moves.
// @fluxerjs/core fires VoiceStateUpdate with ONE arg (raw gateway data),
// not two args (oldState, newState) We maintain prev state manually.
// Declared before GuildDelete so the delete handler can purge stale entries.
const _prevVoiceState = new Map(); // userId → { channelId, guildId }
// ── Bot kicked / banned / server deleted ───────────────────────────────── // ── Bot kicked / banned / server deleted ─────────────────────────────────
client.on(Events.GuildDelete, (guild) => { client.on(Events.GuildDelete, (guild) => {
const guildId = guild?.id ?? guild?._id; const guildId = guild?.id ?? guild?._id;
@@ -634,6 +687,11 @@ class Remix {
for (const [userId, info] of [...this.observedVoiceBots]) { for (const [userId, info] of [...this.observedVoiceBots]) {
if (info.guildId === guildId) this.observedVoiceBots.delete(userId); if (info.guildId === guildId) this.observedVoiceBots.delete(userId);
} }
// Also purge _prevVoiceState entries for this guild so the Map doesn't grow unbounded
for (const [userId, info] of [..._prevVoiceState]) {
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, ""))
_prevVoiceState.delete(userId);
}
// Drop the cached settings so stale data can't be read back // Drop the cached settings so stale data can't be read back
this.settingsMgr.removeServer(guildId); this.settingsMgr.removeServer(guildId);
@@ -644,11 +702,6 @@ class Remix {
logger.guild(`[GuildDelete] Cleanup complete for server ${guildId}.`); logger.guild(`[GuildDelete] Cleanup complete for server ${guildId}.`);
}); });
// Track previous voice state per-user so we can detect channel moves.
// @fluxerjs/core fires VoiceStateUpdate with ONE arg (raw gateway data),
// not two args (oldState, newState) We maintain prev state manually.
const _prevVoiceState = new Map(); // userId → { channelId, guildId }
client.on(Events.VoiceStateUpdate, (data) => { client.on(Events.VoiceStateUpdate, (data) => {
// data is the raw GatewayVoiceStateUpdateDispatchData — always snake_case // data is the raw GatewayVoiceStateUpdateDispatchData — always snake_case
const userId = data?.user_id; const userId = data?.user_id;
@@ -893,7 +946,7 @@ class Remix {
const self = this; const self = this;
this.players.checkVoiceChannels = function (message) { this.players.checkVoiceChannels = function (message) {
const userId = message?.author?.id ?? message?.message?.author?.id; const userId = message?.author?.id ?? message?.message?.author?.id;
// Fluxer uses server_id (snake_case); Discord.js uses guildId; probe all known shapes. // Fluxer uses server_id (snake_case); uses guildId; probe all known shapes.
const guildId = const guildId =
message?.channel?.server_id ?? message?.channel?.server_id ??
message?.channel?.serverId ?? message?.channel?.serverId ??
@@ -1131,10 +1184,16 @@ const saveAndExit = () => {
for (const [channelId, player] of remix.players.playerMap.entries()) { for (const [channelId, player] of remix.players.playerMap.entries()) {
const current = player.queue.getCurrent(); const current = player.queue.getCurrent();
const queueData = player.queue.getQueue(); const queueData = player.queue.getQueue();
const tracksToSave = [];
if (current) tracksToSave.push(current); // Deep-clone track data to capture a stable snapshot.
tracksToSave.push(...queueData); // Without this, a concurrent skip() or playNext() can mutate the array
// between capture and writeFileSync, producing a corrupted recovery file.
const cloneTrack = (t) => {
try { return JSON.parse(JSON.stringify(t)); } catch { return t; }
};
const tracksToSave = [];
if (current) tracksToSave.push(cloneTrack(current));
for (const t of queueData) tracksToSave.push(cloneTrack(t));
// Save ALL active sessions unconditionally so the bot always rejoins // Save ALL active sessions unconditionally so the bot always rejoins
// the channel it was in before rebooting (queue or not, 24/7 or not) // the channel it was in before rebooting (queue or not, 24/7 or not)
+9 -1
View File
@@ -44,6 +44,8 @@ export class MySqlSettingsManager extends SettingsManager {
descriptions = {}; descriptions = {};
defaults = {}; defaults = {};
db = null; db = null;
// Per-server debounce timers — collapses rapid set() calls into one remoteSave()
_debounceTimers = new Map();
constructor(config, defaultsPath) { constructor(config, defaultsPath) {
super(); super();
@@ -122,7 +124,13 @@ export class MySqlSettingsManager extends SettingsManager {
if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); } if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); }
const s = this.guilds.get(server.id); const s = this.guilds.get(server.id);
s.data[key] = server.data[key]; s.data[key] = server.data[key];
this.remoteUpdate(server, key); // Debounce: batch rapid consecutive set() calls into a single remoteSave() 80ms later
const existing = this._debounceTimers.get(server.id);
if (existing) clearTimeout(existing);
this._debounceTimers.set(server.id, setTimeout(() => {
this._debounceTimers.delete(server.id);
this.remoteSave(s);
}, 80));
} }
isOption(key) { return key in this.defaults; } isOption(key) { return key in this.defaults; }
hasServer(id) { return this.guilds.has(id); } hasServer(id) { return this.guilds.has(id); }
+24
View File
@@ -376,6 +376,12 @@ export class CommandHandler extends EventEmitter {
invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`"; invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`";
textWrapError = "Malformed string `$value`: Missing a closing quote character (`$quote`) after the desired string."; textWrapError = "Malformed string `$value`: Missing a closing quote character (`$quote`) after the desired string.";
// Per-user rate limiting: userId → timestamp of last processed command
// Prevents command spam that could saturate worker threads and fill the searches Map.
// Owners are exempt so they can always use debug/reload commands.
_cmdCooldowns = new Map();
_cmdCooldownMs = 1500; // 1.5 seconds between commands per user
constructor(handler, prefix = "!") { constructor(handler, prefix = "!") {
super(); super();
this.messages = handler; this.messages = handler;
@@ -421,6 +427,24 @@ export class CommandHandler extends EventEmitter {
} }
return; return;
} }
// Per-user rate limit — skip spam commands silently.
// Owners are always exempt so %reload and %eval are never blocked.
const userId = msg.message?.author?.id ?? msg.author?.id;
if (userId && !this.owners.includes(userId)) {
const now = Date.now();
const last = this._cmdCooldowns.get(userId) ?? 0;
if (now - last < this._cmdCooldownMs) return;
this._cmdCooldowns.set(userId, now);
// Evict stale entries periodically to keep the Map from growing unbounded.
// 500 entries × 8 bytes ≈ negligible, but good hygiene on busy bots.
if (this._cmdCooldowns.size > 500) {
const cutoff = now - this._cmdCooldownMs * 2;
for (const [uid, ts] of this._cmdCooldowns) {
if (ts < cutoff) this._cmdCooldowns.delete(uid);
}
}
}
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
const prefix = this.getPrefix(guildId); const prefix = this.getPrefix(guildId);
const ping = `<@${this.client.user?.id}>`; const ping = `<@${this.client.user?.id}>`;
+6
View File
@@ -1046,6 +1046,12 @@ export class HelpCommand {
* Call once during bot startup, after commands have been loaded. * Call once during bot startup, after commands have been loaded.
*/ */
register() { register() {
// Guard: if register() is called more than once (e.g. via hot-reload), bail out.
// A second call would stack another MessageCreate listener and re-wrap the format/reply
// handlers a second time, causing duplicate help responses and doubled logic.
if (this._registered) return;
this._registered = true;
const HELP_ALIASES = ["help", "h", "commands"]; const HELP_ALIASES = ["help", "h", "commands"];
// Neutralize built-in help interceptor // Neutralize built-in help interceptor
+17 -47
View File
@@ -2,7 +2,6 @@
* MoonlinkManager.mjs * MoonlinkManager.mjs
* *
* Wraps moonlink.js Manager with a custom connector for Fluxer. * Wraps moonlink.js Manager with a custom connector for Fluxer.
* FIXED: Correct payload format for packetUpdate
*/ */
import { Manager } from "moonlink.js"; import { Manager } from "moonlink.js";
@@ -28,7 +27,7 @@ export class MoonlinkManager extends EventEmitter {
*/ */
constructor(nodeCfg, client) { constructor(nodeCfg, client) {
super(); super();
this.setMaxListeners(50); // reconnects temporarily stack listeners during re-init this.setMaxListeners(50);
this._nodeCfg = nodeCfg; this._nodeCfg = nodeCfg;
this._client = client; this._client = client;
@@ -59,10 +58,8 @@ export class MoonlinkManager extends EventEmitter {
}, },
}); });
// Set up voice state forwarding from Fluxer to moonlink
this._setupVoiceForwarding(client); this._setupVoiceForwarding(client);
// Forward key events
this.manager.on("nodeReady", (node) => { this.manager.on("nodeReady", (node) => {
this.sessionId = node.sessionId ?? null; this.sessionId = node.sessionId ?? null;
logger.moonlink(`[Moonlink] Node ready: ${node.identifier} | session: ${this.sessionId}`); logger.moonlink(`[Moonlink] Node ready: ${node.identifier} | session: ${this.sessionId}`);
@@ -98,6 +95,21 @@ export class MoonlinkManager extends EventEmitter {
}); });
} }
/**
* Get the current live session ID from the connected node.
* Walks active nodes to find a valid session, fallback to cached.
* @returns {string|null}
*/
getLiveSessionId() {
try {
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
if (node.sessionId) return node.sessionId;
if (node.ws?.sessionId) return node.ws.sessionId;
}
} catch (_) {}
return this.sessionId;
}
/** /**
* Send voice payload to Fluxer's WebSocket * Send voice payload to Fluxer's WebSocket
* @param {string} guildId * @param {string} guildId
@@ -106,14 +118,11 @@ export class MoonlinkManager extends EventEmitter {
*/ */
_sendPayload(guildId, payload) { _sendPayload(guildId, payload) {
try { try {
// Prefer the public ws.send(shardId, payload) API — shards is a private field
// in @fluxerjs/ws and accessing it directly risks breaking on internal refactors.
if (typeof this._client?.ws?.send === "function") { if (typeof this._client?.ws?.send === "function") {
this._client.ws.send(0, payload); this._client.ws.send(0, payload);
return; return;
} }
// Fallback: access shard directly only if the public API is unavailable
const shard = this._client?.ws?.shards?.get?.(0); const shard = this._client?.ws?.shards?.get?.(0);
if (!shard) { if (!shard) {
logger.warn("[MoonlinkManager] No WebSocket shard available"); logger.warn("[MoonlinkManager] No WebSocket shard available");
@@ -138,21 +147,16 @@ export class MoonlinkManager extends EventEmitter {
* @private * @private
*/ */
_setupVoiceForwarding(client) { _setupVoiceForwarding(client) {
// @fluxerjs/core emits VoiceStateUpdate with a SINGLE argument:
// (data: GatewayVoiceStateUpdateDispatchData) — raw gateway snake_case fields.
client.on(Events.VoiceStateUpdate, (data) => { client.on(Events.VoiceStateUpdate, (data) => {
try { try {
// data is the raw GatewayVoiceStateUpdateDispatchData — always snake_case
const guildId = data.guild_id; const guildId = data.guild_id;
if (!guildId) { if (!guildId) {
logger.warn("[MoonlinkManager] voiceStateUpdate: No guild_id found in data", data); logger.warn("[MoonlinkManager] voiceStateUpdate: No guild_id found in data", data);
return; return;
} }
// Build the proper payload format that moonlink expects:
// { op: 0, t: "VOICE_STATE_UPDATE", d: { guild_id, user_id, channel_id, ... } }
const payload = { const payload = {
op: 0, // Dispatch op: 0,
t: "VOICE_STATE_UPDATE", t: "VOICE_STATE_UPDATE",
d: { d: {
guild_id: guildId, guild_id: guildId,
@@ -176,9 +180,6 @@ export class MoonlinkManager extends EventEmitter {
} }
}); });
// Raw WS — only for VOICE_SERVER_UPDATE (VOICE_STATE_UPDATE is handled above via Events listener)
// Store the handler reference so we can remove the stale listener before re-attaching
// on gateway reconnects. Without this, each reconnect stacks another handler on the socket.
const attachRawWs = () => { const attachRawWs = () => {
try { try {
const shard0 = client.ws?.shards?.get?.(0); const shard0 = client.ws?.shards?.get?.(0);
@@ -196,7 +197,6 @@ export class MoonlinkManager extends EventEmitter {
} catch (_) {} } catch (_) {}
} }
// Skip re-attaching if it's the same socket object (spurious Ready re-fire)
if (wsObj === this._rawWsObj) return; if (wsObj === this._rawWsObj) return;
this._rawWsHandler = (rawData) => { this._rawWsHandler = (rawData) => {
@@ -213,7 +213,6 @@ export class MoonlinkManager extends EventEmitter {
} catch (_) {} } catch (_) {}
}; };
// Absorb socket-level errors so they don't escape to uncaughtException.
this._rawWsErrorHandler = (err) => { this._rawWsErrorHandler = (err) => {
logger.warn("[MoonlinkManager] Raw WS socket error (will reconnect):", err?.message ?? err); logger.warn("[MoonlinkManager] Raw WS socket error (will reconnect):", err?.message ?? err);
}; };
@@ -233,26 +232,13 @@ export class MoonlinkManager extends EventEmitter {
}; };
attachRawWs(); attachRawWs();
// Re-attach after every gateway reconnect so the new socket gets the listener
client.on(Events.Ready, attachRawWs); client.on(Events.Ready, attachRawWs);
} }
/**
* Call after client.login() resolves and client.user.id is available.
* Safe to call on every reconnect — removes stale internal listeners before re-init
* to prevent the MaxListenersExceededWarning that moonlink.js triggers by adding
* a new nodeReady/nodeConnected listener to the node socket on every init() call.
* @param {string} clientId
*/
async init(clientId) { async init(clientId) {
// Raise the limit on both this emitter and the internal manager so reconnects
// don't spam MaxListenersExceededWarning while we're between socket teardown
// and the re-init completing.
this.setMaxListeners(50); this.setMaxListeners(50);
try { this.manager.setMaxListeners?.(50); } catch (_) {} try { this.manager.setMaxListeners?.(50); } catch (_) {}
// Strip any stale nodeReady listeners the previous init() call registered
// so they don't stack up across gateway reconnects.
try { try {
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) { for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
const sock = node.socket ?? node.ws ?? null; const sock = node.socket ?? node.ws ?? null;
@@ -268,30 +254,14 @@ export class MoonlinkManager extends EventEmitter {
await this.manager.init(clientId); await this.manager.init(clientId);
} }
/**
* Search for tracks. Returns a moonlink SearchResult.
* @param {string} query
* @param {string} [source] e.g. "ytmsearch", "spsearch"
* @param {*} [requester]
*/
search(query, source, requester) { search(query, source, requester) {
return this.manager.search({ query, source, requester }); return this.manager.search({ query, source, requester });
} }
/**
* Get or create a moonlink Player for a guild.
* @param {{ guildId: string, voiceChannelId: string, textChannelId?: string, volume?: number }} opts
* @returns {import("moonlink.js").Player}
*/
createPlayer(opts) { createPlayer(opts) {
return this.manager.players.create(opts); return this.manager.players.create(opts);
} }
/**
* Get an existing player by guildId.
* @param {string} guildId
* @returns {import("moonlink.js").Player|undefined}
*/
getPlayer(guildId) { getPlayer(guildId) {
return this.manager.players.get(guildId); return this.manager.players.get(guildId);
} }
+173 -77
View File
@@ -26,30 +26,51 @@ function mkEmbed(desc) {
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] }; return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] };
} }
/** NodeLink default password — centralised so it doesn't need to be hardcoded in two places. */
const NL_DEFAULT_PASSWORD = "youshallnotpass";
// Cache compiled sanitize regexes keyed by "host:port:password" to avoid
// rebuilding identical RegExp objects on every error path.
const _sanitizeCache = new Map();
/** /**
* Strip NodeLink host, port, and password from a string so they are never * Strip NodeLink host, port, and password from a string so they are never
* shown to end-users in Discord messages. * shown to end-users in Fluxer messages.
* @param {string} msg * @param {string} msg
* @param {Object} nl - The player's _nl config object { host, port, password } * @param {Object} nl - The player's _nl config object { host, port, password }
* @returns {string} * @returns {string}
*/ */
function sanitizeError(msg, nl = {}) { function sanitizeError(msg, nl = {}) {
if (!msg) return msg; if (!msg) return msg;
let s = String(msg); const host = nl.host ?? "";
const host = nl.host; const port = nl.port ?? 0;
const port = nl.port; const password = nl.password ?? NL_DEFAULT_PASSWORD;
const password = nl.password; const cacheKey = `${host}:${port}:${password}`;
let regexes = _sanitizeCache.get(cacheKey);
if (!regexes) {
regexes = [];
if (host && host !== "localhost") { if (host && host !== "localhost") {
const escapedHost = host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const eh = host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
s = s.replace(new RegExp(`https?://${escapedHost}(:\\d+)?[^\\s"']*`, "gi"), "[internal]"); regexes.push(new RegExp(`https?://${eh}(:\\d+)?[^\\s"']*`, "gi"));
if (port) s = s.replace(new RegExp(`${escapedHost}:${port}`, "g"), "[internal]"); if (port) regexes.push(new RegExp(`${eh}:${port}`, "g"));
} }
if (port) { if (port) {
s = s.replace(new RegExp(`https?://localhost:${port}[^\\s"']*`, "gi"), "[internal]"); regexes.push(new RegExp(`https?://localhost:${port}[^\\s"']*`, "gi"));
} }
if (password && password !== "youshallnotpass") { if (password && password !== NL_DEFAULT_PASSWORD) {
const escapedPw = password.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const ep = password.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
s = s.replace(new RegExp(escapedPw, "g"), "[redacted]"); regexes.push(new RegExp(ep, "g"));
}
// Cap cache size — in practice there's only one NodeLink config, but guard anyway
if (_sanitizeCache.size >= 20) _sanitizeCache.clear();
_sanitizeCache.set(cacheKey, regexes);
}
let s = String(msg);
for (const re of regexes) {
re.lastIndex = 0; // reset stateful global regexes between calls
s = s.replace(re, re.source.includes("redacted") ? "[redacted]" : "[internal]");
} }
return s; return s;
} }
@@ -186,9 +207,10 @@ export default class Player extends EventEmitter {
_playingNext = false; _playingNext = false;
_isRecovering = false; _isRecovering = false;
startedPlaying = null; startedPlaying = null;
// searches Map with max-size eviction to prevent memory leak on busy servers // searches Map with max-size eviction to prevent memory leak on busy servers.
// Map preserves insertion order natively, so we use keys().next() for LRU eviction
// instead of a separate _searchOrder array (which could hold ghost keys after playResult()).
searches = new Map(); searches = new Map();
_searchOrder = []; // insertion-order tracker for LRU eviction
_searchMaxSize = 50; // cap: max concurrent pending search sessions _searchMaxSize = 50; // cap: max concurrent pending search sessions
resultLimit = 5; resultLimit = 5;
preferredVolume = 1; preferredVolume = 1;
@@ -200,6 +222,9 @@ export default class Player extends EventEmitter {
_wasRadio = false; _wasRadio = false;
_radioAnnounced = false; _radioAnnounced = false;
// Active audio filter — { key, label, payload } or null
activeFilter = null;
// Inactivity timeout // Inactivity timeout
_inactivityTimer = null; _inactivityTimer = null;
_inactivityLimit = 3 * 60 * 1000; // 3 min default _inactivityLimit = 3 * 60 * 1000; // 3 min default
@@ -213,6 +238,7 @@ export default class Player extends EventEmitter {
port: 3000, port: 3000,
password: "youshallnotpass", password: "youshallnotpass",
sessionId: null, sessionId: null,
requestTimeout: 60_000, // ms before a NodeLink HTTP request is aborted (raise in config if needed)
}; };
constructor(token, opts = {}) { constructor(token, opts = {}) {
@@ -242,16 +268,20 @@ export default class Player extends EventEmitter {
// moonlink.js manager reference — injected by PlayerManager // moonlink.js manager reference — injected by PlayerManager
this._moonlink = opts.moonlink ?? null; this._moonlink = opts.moonlink ?? null;
// Keep session ID in sync when moonlink establishes/re-establishes it. // FIXED: Robust session sync that handles reconnection and stale sessions
// Use a named handler stored on the instance so it can be removed in destroy()
// and doesn't stack up across player replacements on the same moonlink instance.
if (this._moonlink) { if (this._moonlink) {
this._onMoonlinkReady = (sessionId) => { this._onMoonlinkReady = (sessionId) => {
const oldId = this._nl.sessionId;
this._nl.sessionId = sessionId; this._nl.sessionId = sessionId;
if (oldId && oldId !== sessionId) {
logger.moonlink(`[Player] Session ID updated: ${oldId} → ${sessionId}`);
}
}; };
this._moonlink.on("ready", this._onMoonlinkReady); this._moonlink.on("ready", this._onMoonlinkReady);
if (this._moonlink.sessionId) { // Immediate sync if moonlink is already ready
this._nl.sessionId = this._moonlink.sessionId; const existingSession = this._moonlink.getLiveSessionId?.() ?? this._moonlink.sessionId;
if (existingSession) {
this._nl.sessionId = existingSession;
} }
} }
} }
@@ -267,7 +297,6 @@ export default class Player extends EventEmitter {
_is247Enabled() { _is247Enabled() {
if (!this._guildId) return false; if (!this._guildId) return false;
// Helper: check a single settings object
const checkSettings = (set) => { const checkSettings = (set) => {
if (!set?.get) return false; if (!set?.get) return false;
const raw = set.get("stay_247"); const raw = set.get("stay_247");
@@ -333,7 +362,18 @@ export default class Player extends EventEmitter {
logger.mediaplayer(`[Player] Rejoining channel ${this._channelId}`); logger.mediaplayer(`[Player] Rejoining channel ${this._channelId}`);
await this.join(this._channelId); await this.join(this._channelId);
// Resume playing the interrupted track // Verify the join actually produced a healthy connection before resuming playback.
// Releasing _isRecovering here (rather than in finally) means a second "disconnected"
// event that fires while join() is in-flight cannot enter a concurrent recovery cycle.
const roomState = this.connection?.room?.state;
const isConnected = roomState === 1 || roomState === "connected" || roomState === "connecting";
if (!isConnected) {
throw new Error(`Room in unexpected state after rejoin: ${roomState}`);
}
// Release the guard only after confirming the connection is live
this._isRecovering = false;
const current = this.queue.getCurrent(); const current = this.queue.getCurrent();
if (current) { if (current) {
logger.player(`[Player] Resuming track after recovery: ${current.title}`); logger.player(`[Player] Resuming track after recovery: ${current.title}`);
@@ -347,9 +387,8 @@ export default class Player extends EventEmitter {
} }
} catch (e) { } catch (e) {
logger.error("[Player] Recovery failed:", e.message); logger.error("[Player] Recovery failed:", e.message);
this.emit("autoleave"); // Fallback to full recreate if recovery fails entirely
} finally {
this._isRecovering = false; this._isRecovering = false;
this.emit("autoleave");
} }
} }
@@ -359,13 +398,9 @@ export default class Player extends EventEmitter {
/** /**
* Returns true if there is at least one non-bot human in the bot's current voice channel. * Returns true if there is at least one non-bot human in the bot's current voice channel.
* Uses the observedVoiceUsers map maintained by the gateway voice state handler,
* since this bot uses intents: 0 and channel.members is never populated.
*/ */
_hasHumansInChannel() { _hasHumansInChannel() {
if (!this._channelId || !this._guildId) return false; if (!this._channelId || !this._guildId) return false;
// Normalize to digits-only — IDs can arrive from different sources
// (gateway snake_case vs API camelCase) with inconsistent formatting.
const cleanChan = String(this._channelId).replace(/\D/g, ""); const cleanChan = String(this._channelId).replace(/\D/g, "");
const cleanGuild = String(this._guildId).replace(/\D/g, ""); const cleanGuild = String(this._guildId).replace(/\D/g, "");
try { try {
@@ -380,7 +415,6 @@ export default class Player extends EventEmitter {
return false; return false;
} }
} catch (_) {} } catch (_) {}
// Fallback: try channel.members cache (works if privileged intents are enabled)
try { try {
const channel = this.client?.channels?.cache?.get(this._channelId); const channel = this.client?.channels?.cache?.get(this._channelId);
const members = channel?.members; const members = channel?.members;
@@ -407,7 +441,6 @@ export default class Player extends EventEmitter {
return; return;
} }
// Don't start the inactivity timer if there are humans in the channel
if (this._hasHumansInChannel()) { if (this._hasHumansInChannel()) {
logger.inactivity(`[Player] Humans present in channel ${this._channelId}, skipping inactivity timer`); logger.inactivity(`[Player] Humans present in channel ${this._channelId}, skipping inactivity timer`);
return; return;
@@ -419,7 +452,6 @@ export default class Player extends EventEmitter {
logger.inactivity("[Player] 24/7 mode enabled during inactivity wait, aborting leave"); logger.inactivity("[Player] 24/7 mode enabled during inactivity wait, aborting leave");
return; return;
} }
// Double-check: abort if a human joined during the wait
if (this._hasHumansInChannel()) { if (this._hasHumansInChannel()) {
logger.inactivity("[Player] Human joined during inactivity wait, aborting leave"); logger.inactivity("[Player] Human joined during inactivity wait, aborting leave");
return; return;
@@ -484,23 +516,10 @@ export default class Player extends EventEmitter {
} }
} }
/**
* Monitor MediaPlayer for ghost connections via event — not polling.
* The connection.on("disconnected") handler in join() already calls
* _cleanupMediaPlayer() + _recoverConnection(), so this method is intentionally
* lightweight: it only validates the room state once before playing.
* @private
*/
_setupMediaPlayerMonitoring() { _setupMediaPlayerMonitoring() {
// No-op: recovery is fully handled by connection.on("disconnected") in join(). // No-op: recovery is fully handled by connection.on("disconnected") in join().
// The old setInterval(5000) approach polled LiveKit state unnecessarily and
// risked acting on a stale captured MediaPlayer reference.
} }
/**
* Clean up MediaPlayer properly.
* @private
*/
async _cleanupMediaPlayer() { async _cleanupMediaPlayer() {
try { try {
await this._mediaPlayer?.stop(); await this._mediaPlayer?.stop();
@@ -571,16 +590,21 @@ export default class Player extends EventEmitter {
} }
if (returnStream) return resolve(res); if (returnStream) return resolve(res);
// 204 No Content — valid success with no body
if (res.statusCode === 204) { res.resume(); return resolve(null); }
const chunks = []; const chunks = [];
res.on("data", d => chunks.push(d)); res.on("data", d => chunks.push(d));
res.on("end", () => { res.on("end", () => {
try { resolve(JSON.parse(Buffer.concat(chunks).toString())); } const raw = Buffer.concat(chunks).toString().trim();
if (!raw) return resolve(null);
try { resolve(JSON.parse(raw)); }
catch (e) { reject(new Error(`JSON parse error from ${target}`)); } catch (e) { reject(new Error(`JSON parse error from ${target}`)); }
}); });
}); });
req.on("error", reject); req.on("error", reject);
req.setTimeout(options.timeout || 30_000, () => { req.setTimeout(options.timeout || this._nl.requestTimeout || 60_000, () => {
req.destroy(); req.destroy();
reject(new Error("Request timeout")); reject(new Error("Request timeout"));
}); });
@@ -627,7 +651,8 @@ export default class Player extends EventEmitter {
cleanup(); cleanup();
if (this._streamingStopped || this._skipping) return resolve(); if (this._streamingStopped || this._skipping) return resolve();
const graceful = ["aborted", "ECONNRESET", "ERR_STREAM_DESTROYED", "ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED"]; const graceful = ["aborted", "ECONNRESET", "ERR_STREAM_DESTROYED", "ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED"];
if (graceful.includes(e.code) || graceful.includes(e.message)) return resolve(); // Use substring matching so "Input stream error: aborted" (from NodeLink) is also caught
if (graceful.some(g => e.code === g || e.message?.includes(g))) return resolve();
reject(e); reject(e);
}); });
@@ -636,13 +661,20 @@ export default class Player extends EventEmitter {
this._mediaPlayer.removeAllListeners("finish"); this._mediaPlayer.removeAllListeners("finish");
this._mediaPlayer.removeAllListeners("error"); this._mediaPlayer.removeAllListeners("error");
// revoice.js MediaPlayer.playStream() pipes through FFmpeg but the FFmpeg
// error handler is a no-op (// TODO). Wire it up manually so errors surface.
const onFfmpegError = (err) => { const onFfmpegError = (err) => {
logger.error("[Player] FFmpeg error:", err?.message ?? err); const ffMsg = err?.message ?? String(err);
// "Input stream error: aborted" means NodeLink dropped the HTTP stream
// (e.g. filter PATCH restarted the player before voice state arrived).
// Treat it as graceful so the queue can advance normally.
if (ffMsg.includes("aborted") || ffMsg.includes("Input stream error")) {
logger.player("[Player] FFmpeg stream aborted gracefully (NodeLink stream closed)");
cleanup();
return resolve();
}
logger.error("[Player] FFmpeg error:", ffMsg);
cleanup(); cleanup();
if (this._streamingStopped || this._skipping) return resolve(); if (this._streamingStopped || this._skipping) return resolve();
reject(new Error(`FFmpeg: ${err?.message ?? err}`)); reject(new Error(`FFmpeg: ${ffMsg}`));
}; };
try { try {
@@ -659,8 +691,6 @@ export default class Player extends EventEmitter {
return reject(e); return reject(e);
} }
// Safety timeout — FFmpeg errors emit nothing in revoice.js, this ensures
// the queue always advances even if a future silent failure slips through.
const safetyMs = 10 * 60 * 1000; const safetyMs = 10 * 60 * 1000;
const safetyTimer = setTimeout(() => { const safetyTimer = setTimeout(() => {
logger.warn("[Player] Stream safety timeout — advancing queue"); logger.warn("[Player] Stream safety timeout — advancing queue");
@@ -708,8 +738,6 @@ export default class Player extends EventEmitter {
if (!isNodeLink) return this._streamViaRevoice(url); if (!isNodeLink) return this._streamViaRevoice(url);
// NodeLink /v4/trackstream returns { "url": "https://..." } — a JSON wrapper
// pointing to the actual CDN audio URL. Extract it then stream that.
try { try {
const json = await this._request(url, { const json = await this._request(url, {
headers: { headers: {
@@ -722,8 +750,6 @@ export default class Player extends EventEmitter {
return this._streamViaRevoice(json.url); return this._streamViaRevoice(json.url);
} catch (err) { } catch (err) {
logger.error("[Player] NodeLink resolve error:", err.message); logger.error("[Player] NodeLink resolve error:", err.message);
// Sanitize before re-throwing — this error eventually becomes a user-visible
// "Error streaming X — skipping..." message, so the NodeLink URL must not appear.
throw new Error(sanitizeError(err.message, this._nl)); throw new Error(sanitizeError(err.message, this._nl));
} }
} }
@@ -825,7 +851,7 @@ export default class Player extends EventEmitter {
if (!this.leaving) { if (!this.leaving) {
logger.mediaplayer("[Player] Unexpected disconnect detected"); logger.mediaplayer("[Player] Unexpected disconnect detected");
this._cleanupMediaPlayer(); this._cleanupMediaPlayer();
this._recoverConnection(); // Trigger recovery instead of giving up this._recoverConnection();
} else { } else {
try { connection.destroy(); } catch (_) {} try { connection.destroy(); } catch (_) {}
} }
@@ -898,8 +924,6 @@ export default class Player extends EventEmitter {
destroy() { destroy() {
try { try {
// Remove the moonlink "ready" listener registered in the constructor
// so it doesn't stack up across player replacements on the same manager.
if (this._moonlink && this._onMoonlinkReady) { if (this._moonlink && this._onMoonlinkReady) {
try { this._moonlink.off("ready", this._onMoonlinkReady); } catch (_) {} try { this._moonlink.off("ready", this._onMoonlinkReady); } catch (_) {}
this._onMoonlinkReady = null; this._onMoonlinkReady = null;
@@ -907,10 +931,6 @@ export default class Player extends EventEmitter {
this.leaving = true; this.leaving = true;
this._streamingStopped = true; this._streamingStopped = true;
this._stopInactivityTimer(); this._stopInactivityTimer();
// _stopMediaPlayer is async; we fire it and swallow the promise here
// (destroy is intentionally sync/fire-and-forget), but we do wait for it
// before disconnecting via the chained .then so the media player stops
// cleanly before the connection tears down — preventing "AudioSource is closed" errors.
this._stopMediaPlayer().catch(() => {}).then(() => { this._stopMediaPlayer().catch(() => {}).then(() => {
setTimeout(() => { setTimeout(() => {
const disconnectPromise = this.connection?.disconnect?.(); const disconnectPromise = this.connection?.disconnect?.();
@@ -941,10 +961,7 @@ export default class Player extends EventEmitter {
this._paused = true; this._paused = true;
this._mediaPlayer?.pause(); this._mediaPlayer?.pause();
this.emit("playback", false); this.emit("playback", false);
// patiently waits in the VC forever until you resume!
this._stopInactivityTimer(); this._stopInactivityTimer();
return ":pause_button: Paused"; return ":pause_button: Paused";
} }
@@ -956,7 +973,6 @@ export default class Player extends EventEmitter {
this._paused = false; this._paused = false;
this._mediaPlayer?.resume(); this._mediaPlayer?.resume();
this.emit("playback", true); this.emit("playback", true);
this._stopInactivityTimer(); this._stopInactivityTimer();
return ":arrow_forward: Resumed"; return ":arrow_forward: Resumed";
} }
@@ -1017,6 +1033,81 @@ export default class Player extends EventEmitter {
return `Volume changed to \`${Math.round(this.preferredVolume * 100)}%\`.`; return `Volume changed to \`${Math.round(this.preferredVolume * 100)}%\`.`;
} }
// ═══════════════════════════════════════════════════════════════════════════
// Audio Filter Control (NodeLink PATCH /v4/sessions/:id/players/:guildId)
// ═══════════════════════════════════════════════════════════════════════════
/**
* Apply (or clear) an audio filter by sending a PATCH to NodeLink.
* Includes encodedTrack so NodeLink doesn't create a ghost player.
* Uses live session ID from moonlink to avoid stale sessions.
* Auto-retries once on stale session detection.
*
* @param {Object} filterPayload - Lavalink v4 filters object. Pass {} to clear all filters.
* @param {{ key: string, label: string, emoji?: string }|null} meta - Filter metadata to store, or null to clear.
* @returns {Promise<{ ok: boolean, reason?: string }>}
*/
async applyFilter(filterPayload, meta = null, _retryCount = 0) {
const guildId = this._guildId;
if (!guildId) {
return { ok: false, reason: "Player not bound to a guild." };
}
// CRITICAL: Get session ID directly from moonlink manager, not cached _nl
const liveSessionId = this._moonlink?.getLiveSessionId?.() ?? this._moonlink?.sessionId ?? this._nl.sessionId;
if (!liveSessionId) {
return { ok: false, reason: "No active NodeLink session. Try again in a few seconds." };
}
const { host, port } = this._nl;
const url = `http://${host}:${port}/v4/sessions/${liveSessionId}/players/${guildId}`;
// Per NodeLink REST API: send ONLY the filters object when updating filters.
// Including track.encoded causes NodeLink to restart playback (triggers play()),
// which leads to "No voice state" spam and eventually FFmpeg "Input stream error: aborted".
const current = this.queue.getCurrent();
if (!current?.encoded) {
return { ok: false, reason: "No active track loaded. Start playback first." };
}
const body = JSON.stringify({ filters: filterPayload });
try {
await this._request(url, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body),
},
body,
});
// Sync local session ID if it changed under us
if (liveSessionId !== this._nl.sessionId) {
this._nl.sessionId = liveSessionId;
logger.moonlink(`[Player] Synced session ID after filter apply: ${liveSessionId}`);
}
this.activeFilter = meta ?? null;
this.emit("filter", this.activeFilter);
return { ok: true };
} catch (e) {
// Detect stale session specifically — allow exactly one retry with a fresh session ID.
// The _retryCount guard prevents infinite recursion if back-to-back reconnects keep
// producing stale IDs faster than this method runs.
const errMsg = e.message ?? "";
if (_retryCount === 0 && (errMsg.includes("404") || errMsg.includes("not found") || errMsg.includes("Session-ID") || errMsg.includes("does not exist"))) {
logger.warn("[Player] Filter apply failed with stale session, forcing re-sync...");
const freshSession = this._moonlink?.getLiveSessionId?.() ?? this._moonlink?.sessionId;
if (freshSession && freshSession !== liveSessionId) {
this._nl.sessionId = freshSession;
return this.applyFilter(filterPayload, meta, 1); // Single retry with depth guard
}
}
return { ok: false, reason: sanitizeError(errMsg, this._nl) };
}
}
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
// Queue Management // Queue Management
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
@@ -1272,8 +1363,14 @@ export default class Player extends EventEmitter {
worker.on("exit", (code) => { if (code !== 0) reject(new Error(`Worker exited ${code}`)); }); worker.on("exit", (code) => { if (code !== 0) reject(new Error(`Worker exited ${code}`)); });
}); });
return Utils.timeout(job, 60_000, "Worker timeout after 60s") const raced = Utils.timeout(job, 60_000, "Worker timeout after 60s");
.finally(() => worker.terminate().catch(() => {}));
// Absorb any late "error" events emitted after the timeout has already settled
// the promise. Without this no-op, a worker error arriving post-timeout produces
// an unhandled rejection / uncaughtException on some Node versions.
worker.on("error", () => {});
return raced.finally(() => worker.terminate().catch(() => {}));
} }
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
@@ -1292,13 +1389,15 @@ export default class Player extends EventEmitter {
}); });
list += "\nSend the number of the result. Example: `2`\nSend 'x' to cancel."; list += "\nSend the number of the result. Example: `2`\nSend 'x' to cancel.";
// FIX: evict oldest search session if we're at the cap, preventing unbounded growth // LRU eviction: Map preserves insertion order; the first key() is always the oldest.
// This avoids the ghost-key bug that existed when _searchOrder tracked keys separately
// from the Map — playResult() could remove a key from searches but leave it in the
// order array, causing the eviction to silently skip the true oldest live entry.
if (this.searches.size >= this._searchMaxSize) { if (this.searches.size >= this._searchMaxSize) {
const oldestKey = this._searchOrder.shift(); const oldestKey = this.searches.keys().next().value;
if (oldestKey) this.searches.delete(oldestKey); if (oldestKey !== undefined) this.searches.delete(oldestKey);
} }
this.searches.set(id, data.data); this.searches.set(id, data.data);
this._searchOrder.push(id);
return { m: list, count: data.data.length }; return { m: list, count: data.data.length };
} catch (err) { } catch (err) {
@@ -1314,10 +1413,7 @@ export default class Player extends EventEmitter {
const res = searchResults[result]; const res = searchResults[result];
this.addToQueue(res, next); this.addToQueue(res, next);
// Clean up this search session once the user has picked a result
this.searches.delete(id); this.searches.delete(id);
const orderIdx = this._searchOrder.indexOf(id);
if (orderIdx !== -1) this._searchOrder.splice(orderIdx, 1);
if (!this.queue.getCurrent()) { if (!this.queue.getCurrent()) {
this.playNext(); this.playNext();
@@ -1475,7 +1571,7 @@ export default class Player extends EventEmitter {
this.queue.current = null; this.queue.current = null;
this._playingNext = false; this._playingNext = false;
} }
this._recoverConnection(); // Safely recover the broken LiveKit connection this._recoverConnection();
return; return;
} }
+14 -1
View File
@@ -96,6 +96,11 @@ export class RemoteSettingsManager extends EventEmitter {
// track retry count and apply exponential backoff on load failures // track retry count and apply exponential backoff on load failures
_loadAttempts = 0; _loadAttempts = 0;
// Per-server debounce timers: serverId → NodeJS.Timeout
// Batches rapid set() calls (e.g. 24/7 mode changes that write stay_247 + stay_247_mode)
// into a single remoteSave() 80ms after the last write, rather than firing one UPDATE
// per key.
_debounceTimers = new Map();
constructor(config, defaultsPath) { constructor(config, defaultsPath) {
super(); super();
@@ -177,7 +182,15 @@ export class RemoteSettingsManager extends EventEmitter {
if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); } if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); }
const s = this.guilds.get(server.id); const s = this.guilds.get(server.id);
s.data[key] = server.data[key]; s.data[key] = server.data[key];
this.remoteUpdate(server, key); // Debounce: collapse rapid successive set() calls (e.g. stay_247 + stay_247_mode written
// together) into a single remoteSave() 80ms after the last write for this server.
// This prevents N parallel UPDATE queries when multiple keys change in one command handler.
const existing = this._debounceTimers.get(server.id);
if (existing) clearTimeout(existing);
this._debounceTimers.set(server.id, setTimeout(() => {
this._debounceTimers.delete(server.id);
this.remoteSave(s);
}, 80));
} }
isOption(key) { return key in this.defaults; } isOption(key) { return key in this.defaults; }
+24 -20
View File
@@ -19,34 +19,38 @@ import { logger } from "./constants/Logger.mjs";
const nl = workerData?.data?.nodelink ?? {}; const nl = workerData?.data?.nodelink ?? {};
const NL_HOST = nl.host ?? "localhost"; const NL_HOST = nl.host ?? "localhost";
const NL_PORT = nl.port ?? 3000; const NL_PORT = nl.port ?? 3000;
const NL_PASSWORD = nl.password ?? "youshallnotpass"; // Shared default — must match NL_DEFAULT_PASSWORD in Player.mjs
const NL_DEFAULT_PASSWORD = "youshallnotpass";
const NL_PASSWORD = nl.password ?? NL_DEFAULT_PASSWORD;
const NL_SESSION_ID = nl.sessionId ?? null; // provided by moonlink.js Manager const NL_SESSION_ID = nl.sessionId ?? null; // provided by moonlink.js Manager
const NL_GUILD_ID = workerData?.data?.guildId ?? null; const NL_GUILD_ID = workerData?.data?.guildId ?? null;
// ─── Error sanitizer ────────────────────────────────────────────────────────── // ─── Error sanitizer ──────────────────────────────────────────────────────────
// Compile regexes once at module load (constants are fixed for the worker's lifetime).
// Re-compiling on every sanitizeError() call was wasteful and identical each time.
const _sanitizeRegexes = (() => {
const r = [];
if (NL_HOST && NL_HOST !== "localhost") {
const eh = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
r.push({ re: new RegExp(`https?://${eh}(:\\d+)?[^\\s"']*`, "gi"), sub: "[internal]" });
r.push({ re: new RegExp(`${eh}:${NL_PORT}`, "g"), sub: "[internal]" });
}
r.push({ re: new RegExp(`https?://localhost:${NL_PORT}[^\\s"']*`, "gi"), sub: "[internal]" });
if (NL_PASSWORD && NL_PASSWORD !== NL_DEFAULT_PASSWORD) {
const ep = NL_PASSWORD.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
r.push({ re: new RegExp(ep, "g"), sub: "[redacted]" });
}
return r;
})();
// Strips the NodeLink host, port, and password from any string so they are // Strips the NodeLink host, port, and password from any string so they are
// never shown to end-users in Discord messages. Called on every user-visible // never shown to end-users in messages.
// error string before it is emitted or returned.
function sanitizeError(msg) { function sanitizeError(msg) {
if (!msg) return msg; if (!msg) return msg;
let s = String(msg); let s = String(msg);
// Remove full URLs containing the NodeLink host (http://host:port/...) for (const { re, sub } of _sanitizeRegexes) {
if (NL_HOST && NL_HOST !== "localhost") { re.lastIndex = 0; // reset stateful global regexes between calls
// Escape special regex chars in the host string s = s.replace(re, sub);
const escapedHost = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
s = s.replace(new RegExp(`https?://${escapedHost}(:\\d+)?[^\\s"']*`, "gi"), "[internal]");
}
// Remove localhost:port combos
s = s.replace(new RegExp(`https?://localhost:${NL_PORT}[^\\s"']*`, "gi"), "[internal]");
// Remove bare host:port if it somehow appears without a protocol
if (NL_HOST && NL_HOST !== "localhost") {
const escapedHost = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
s = s.replace(new RegExp(`${escapedHost}:${NL_PORT}`, "g"), "[internal]");
}
// Remove the password just in case it ever leaks into an error message
if (NL_PASSWORD && NL_PASSWORD !== "youshallnotpass") {
const escapedPw = NL_PASSWORD.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
s = s.replace(new RegExp(escapedPw, "g"), "[redacted]");
} }
return s; return s;
} }
+5 -3
View File
@@ -6,7 +6,8 @@
"locale": "en", "locale": "en",
"stay_247": "none", "stay_247": "none",
"stay_247_mode": "off", "stay_247_mode": "off",
"volume": 100 "volume": 100,
"announcementChannelId": null
}, },
"descriptions": { "descriptions": {
"songAnnouncements": "Whether the bot should announce every song in a new message when it starts playing. Set to `true` or `1` to enable.", "songAnnouncements": "Whether the bot should announce every song in a new message when it starts playing. Set to `true` or `1` to enable.",
@@ -14,7 +15,8 @@
"pfp": "What profile picture the bot should use. Presets: `default | dark | light | mono | <custom url>`.", "pfp": "What profile picture the bot should use. Presets: `default | dark | light | mono | <custom url>`.",
"locale": "The preferred language of your server.", "locale": "The preferred language of your server.",
"stay_247": "24/7 mode channels. Managed automatically by %247 — do not edit manually.", "stay_247": "24/7 mode channels. Managed automatically by %247 — do not edit manually.",
"stay_247_mode": "Controls 247 behaviour. Set via %247 off/on/auto. off = disabled, on = stay but no rejoin on force-kick, auto = stay and always rejoin.", "stay_247_mode": "Controls 247 behaviour. Set via %247 off/on/auto. off = disabled, on = stay but no rejoin on force-kick, auto = stay and always rejoins.",
"volume": "The default playback volume for this server (1-200). Saved automatically when you use %volume. Restored every time the bot joins a channel." "volume": "The default playback volume for this server (1-200). Saved automatically when you use %volume. Restored every time the bot joins a channel.",
"announcementChannelId": "The channel where song announcements are sent. Managed automatically — do not edit manually."
} }
} }