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
+468 -232

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.
* Matches any key that *contains* one of these strings (case-insensitive).
*/
const RESTRICTED = [
"token",
"config",
"key",
"clientSecret",
"clientId",
"clientsecret",
"clientid",
"password",
"secret",
"authorization"
"authorization",
"mysql",
"nodelink",
"_nl",
"credential",
"apikey",
"webhook",
];
function hasSensitive(obj, level = 0) {
if (level >= 3 || typeof obj !== "object" || obj === null) return false;
// Maximum depth for sensitive-key scanning and redaction.
// 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) {
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;
}
function removeSensitive(obj, level = 0) {
if (level >= 3 || typeof obj !== "object" || obj === null) return obj;
function removeSensitive(obj, level = 0, visited = new WeakSet()) {
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 newObj = isArray ? [...obj] : { ...obj };
@@ -43,7 +60,7 @@ function removeSensitive(obj, level = 0) {
newObj[key] = "[REDACTED]";
modified = true;
} 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]) {
newObj[key] = cleaned;
modified = true;
+1 -1
View File
@@ -27,5 +27,5 @@ export async function run(msg, data) {
const p = this.players.playerMap.get(cid);
if (!p) return msg.replyEmbed(embed("❌ Player not found."));
if (!p.connection) return msg.replyEmbed(embed("❌ Player not initialized."));
this.players.leave(msg, cid);
await this.players.leave(msg, cid);
}
+13 -2
View File
@@ -58,11 +58,22 @@ export async function run(message, data) {
.setColor(getGlobalColor())
.setDescription("🔍 Searching...")
.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);
messages.on("message", d => {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d).toJSON();
statusMsg.editEmbed({ embeds: [embed] }).catch(() => {});
if (statusMsg) {
statusMsg.editEmbed({ embeds: [embed] }).catch(() => {});
} else {
// statusMsg failed to send earlier, fall back to a fresh reply
message.replyEmbed({ embeds: [embed] }).catch(() => {});
}
});
}
+39 -34
View File
@@ -28,6 +28,7 @@ const CONTROLS = {
volDown: { emoji: "🔉", action: "voldown", desc: "Volume Down" },
volUp: { emoji: "🔊", action: "volup", desc: "Volume Up" },
lyrics: { emoji: "📜", action: "lyrics", desc: "Lyrics" },
filter: { emoji: "🎛️", action: "filter", desc: "Audio Filters" },
close: { emoji: "❌", action: "close", desc: "Close" }
};
@@ -51,7 +52,7 @@ export async function run(msg) {
const controlsLayout = [
[CONTROLS.prev, CONTROLS.play, CONTROLS.pause, CONTROLS.stop, CONTROLS.next],
[CONTROLS.loop, CONTROLS.shuffle, CONTROLS.volDown, CONTROLS.volUp, CONTROLS.lyrics],
[CONTROLS.close]
[CONTROLS.filter, CONTROLS.close]
];
const allControls = controlsLayout.flat();
@@ -83,7 +84,6 @@ export async function run(msg) {
PROGRESS.empty.repeat(emptyCount) +
PROGRESS.end;
// Use Utils.prettifyMS instead of local formatTime
const elapsedStr = Utils.prettifyMS(elapsed);
const totalStr = Utils.prettifyMS(totalMs);
timeDisplay = `\`${elapsedStr} / ${totalStr}\``;
@@ -98,8 +98,17 @@ export async function run(msg) {
const queueSize = player.queue.size();
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
// Use Utils.truncate instead of local truncate
? `[${Utils.truncate(current.title, 45)}](${current.spotifyUrl || current.url})`
: "*Nothing playing*";
@@ -111,15 +120,13 @@ export async function run(msg) {
`${timeDisplay}`,
``,
`🔊 Volume: \`${volPercent}%\` ${volumeBar}`,
`📋 Queue: \`${queueSize}\` tracks | Loop: ${loopStatus}`,
`📋 Queue: \`${queueSize}\` tracks | Loop: ${loopStatus} | Filter: ${filterStatus}`,
``,
state.message ? `💬 *${state.message}*` : "💡 *React to control playback*",
``,
`⏱️ Session expires in ${Math.ceil(timeout / 60000)}m of inactivity`
].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"
? msg.author.avatarURL()
: msg.author?.avatarURL ?? null;
@@ -132,7 +139,6 @@ export async function run(msg) {
text: `Requested by ${msg.author?.username || "Unknown"} • Controls active`,
iconURL: avatarUrl
});
// setTimestamp() is not verified on @fluxerjs/core's EmbedBuilder — guard it.
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
if (current?.thumbnail) builder.setThumbnail(current.thumbnail);
return builder.toJSON();
@@ -141,12 +147,11 @@ export async function run(msg) {
const message = await msg.replyEmbed({ embeds: [buildEmbed()] });
if (!message?.message) return;
// Add reactions with staggered animation
for (const row of controlsLayout) {
for (const control of row) {
try {
await message.message.react(control.emoji);
await Utils.sleep(200); // Use Utils.sleep instead of inline Promise
await Utils.sleep(200);
} catch (_) {}
}
}
@@ -156,12 +161,10 @@ export async function run(msg) {
let emojiRemoveTimeout;
let lastState = {};
// Track active lyrics message
let activeLyricsMsg = null;
let lyricsUnobserve = null;
let lyricsEmojiTimeout = null;
// Helper: Clear all reactions
const clearReactions = async () => {
try {
await message.message.removeAllReactions();
@@ -174,7 +177,6 @@ export async function run(msg) {
}
};
// Helper: Reset emoji removal timer
const resetEmojiTimer = () => {
clearTimeout(emojiRemoveTimeout);
emojiRemoveTimeout = setTimeout(async () => {
@@ -185,7 +187,6 @@ export async function run(msg) {
}, EMOJI_REMOVE_TIMEOUT);
};
// Helper: Clear lyrics reactions
const clearLyricsReactions = async (lyricsMsg) => {
if (!lyricsMsg?.message) return;
try {
@@ -211,15 +212,14 @@ export async function run(msg) {
clearInterval(updateInterval);
unobserve?.();
// Remove all player event listeners added by this session
player.off("startplay", onStartPlay);
player.off("playback", onPlayback);
player.off("stopplay", onStopPlay);
player.off("queue", onQueue);
player.off("volume", onVolume);
player.off("filter", onFilter);
player.off("autoleave", onAutoLeave);
// Cleanup any active lyrics
if (lyricsUnobserve) {
lyricsUnobserve();
clearTimeout(lyricsEmojiTimeout);
@@ -233,7 +233,6 @@ export async function run(msg) {
const closedEmbed = buildEmbed({
message: `Session closed${reason !== "timeout" ? ` • ${reason}` : " due to inactivity"}`
});
// Override title and footer on the plain object returned by toJSON()
closedEmbed.color = getGlobalColor();
closedEmbed.footer = { text: "Session ended" };
closedEmbed.title = "🎧 Music Player (Inactive)";
@@ -249,14 +248,12 @@ export async function run(msg) {
sessionTimeout = setTimeout(() => closeSession("timeout"), timeout);
};
// Live progress updates
updateInterval = setInterval(() => {
if (!player.paused && player.queue.getCurrent()) {
refresh(lastState);
}
}, this.config?.timers?.playerUpdateInterval ?? 5000);
// Player events — store named handlers so we can remove them on closeSession
const onStartPlay = () => refresh({ message: "▶️ Started playing" });
const onPlayback = (playing) => refresh({ message: playing ? "▶️ Resumed" : "⏸️ Paused" });
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)}` });
};
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");
player.on("startplay", onStartPlay);
@@ -272,9 +278,9 @@ export async function run(msg) {
player.on("stopplay", onStopPlay);
player.on("queue", onQueue);
player.on("volume", onVolume);
player.on("filter", onFilter);
player.on("autoleave", onAutoLeave);
// Reaction handler
const unobserve = message.onReaction(controlEmojis, async (e) => {
const control = allControls.find(c => c.emoji === e.emoji_id);
if (!control) return;
@@ -349,12 +355,22 @@ export async function run(msg) {
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":
reply = "📜 Fetching lyrics...";
refresh({ message: reply });
try {
// Cleanup previous lyrics
if (lyricsUnobserve) {
lyricsUnobserve();
clearTimeout(lyricsEmojiTimeout);
@@ -374,7 +390,6 @@ export async function run(msg) {
const LINES_PER_PAGE = 25;
const totalPages = Math.ceil(totalLines / LINES_PER_PAGE);
// Build pages
const pages = [];
for (let i = 0; i < totalLines; i += LINES_PER_PAGE) {
pages.push(lines.slice(i, i + LINES_PER_PAGE).join('\n'));
@@ -384,8 +399,8 @@ export async function run(msg) {
const buildLyricsContent = (pageIdx, expired = false, closed = false) => {
const title = Utils.truncate(
player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '',
50
player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '',
50
);
const footerText = closed
? `👋 Lyrics closed • NodeLink • ${totalLines} lines`
@@ -403,17 +418,14 @@ export async function run(msg) {
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText }).toJSON()] };
};
// Send initial lyrics
activeLyricsMsg = await msg.replyEmbed(buildLyricsContent(0));
// Add pagination and close button if needed
if (activeLyricsMsg?.message && totalPages > 1) {
const navEmojis = ["⬅️", "➡️", "❌"];
for (const emoji of navEmojis) {
await activeLyricsMsg.message.react(emoji).catch(() => {});
}
// Reset timer helper
const resetLyricsTimer = () => {
clearTimeout(lyricsEmojiTimeout);
lyricsEmojiTimeout = setTimeout(async () => {
@@ -422,9 +434,7 @@ export async function run(msg) {
}, EMOJI_REMOVE_TIMEOUT);
};
// Navigation handler
lyricsUnobserve = activeLyricsMsg.onReaction(navEmojis, async (e) => {
// Close button
if (e.emoji_id === "❌") {
lyricsUnobserve();
clearTimeout(lyricsEmojiTimeout);
@@ -433,7 +443,6 @@ export async function run(msg) {
return;
}
// Reset timer on navigation
resetLyricsTimer();
if (e.emoji_id === "⬅️") {
@@ -445,10 +454,8 @@ export async function run(msg) {
await activeLyricsMsg.editEmbed(buildLyricsContent(currentPage));
});
// Start 1 minute timer
resetLyricsTimer();
} else if (activeLyricsMsg?.message) {
// Single page - just add close button
await activeLyricsMsg.message.react("❌").catch(() => {});
const resetLyricsTimer = () => {
@@ -474,7 +481,6 @@ export async function run(msg) {
reply = `Lyrics displayed (${totalLines} lines, ${totalPages} pages)`;
} catch (err) {
// Use Utils.truncate instead of local truncate
reply = `⚠️ Lyrics error: ${Utils.truncate(err.message, 50)}`;
}
shouldUpdate = true;
@@ -491,7 +497,6 @@ export async function run(msg) {
if (shouldUpdate) refresh({ message: reply });
});
// Start timers
resetTimeout();
resetEmojiTimer();
}
}
+3 -2
View File
@@ -40,8 +40,9 @@ async function reloadCommand(ctx, name) {
ctx.runnables.delete(command.uid);
ctx.commandFiles.delete(command.uid);
// Re-import with cache-buster
const url = "file://" + file + "?t=" + Date.now();
// Re-import with cache-buster — use pathToFileURL so Windows drive letters and
// 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 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 unobserve = wrapped.onReaction(allReactions, async (e, reactionMsg) => {
// Only react to the command author
if (e.user_id && e.user_id !== authorId) return;
// Only react to the command author — normalise across Fluxer reaction event shapes
const reactorId = e.user_id ?? e.userId ?? e.user?.id ?? null;
if (reactorId && reactorId !== authorId) return;
clearTimeout(timer);
unobserve();
+17 -5
View File
@@ -33,15 +33,27 @@ async function fetchGuildMemberCount(guild) {
try {
let after = undefined;
let total = 0;
while (true) {
const batch = await guild.members.fetch({ limit: 1000, after });
// Guard against runaway pagination: Fluxer may have far fewer than 1000 members
// 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;
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;
} 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;
// Measure real Discord round-trip latency
// Measure real round-trip latency
const start = Date.now();
const msg = await message.replyEmbed({
embeds: [buildEmbed({ ...shared, userCount: hasCached ? cachedUserCount : 0, ping: 0, loading: !hasCached })]