feat: on-demand lyrics query, queue range clearing, and nodelink auto-reconnect (#13, #14, #20)

This commit is contained in:
NoLogicAlan committed 2026-10-22 01:16:33 +03:00
1 parent 08e5d363fc
commit 665be29a16
9 files changed
+303 -39

No files matched your search

+27 -4
View File
@@ -13,20 +13,43 @@ import { getGlobalColor } from "../src/ui/index.mjs";
*/
export const command = new CommandBuilder()
.setName("clear")
.setDescription("Remove all songs from the queue.", "commands.clear")
.setDescription("Remove all songs, or a slice of songs, from the queue.", "commands.clear")
.addAliases("c")
.setCategory("music");
.setCategory("music")
.addNumberOption(o =>
o.setName("from")
.setDescription("Starting queue position to clear from (optional, 1-based).")
.setRequired(false)
)
.addNumberOption(o =>
o.setName("to")
.setDescription("Ending queue position to clear to (optional, 1-based).")
.setRequired(false)
);
/**
* Run handler for the clear command.
* Clears the entire queue and sends a confirmation embed.
* Clears the entire queue, or a specified range of tracks, and sends a confirmation embed.
*
* @param {object} msg - The command message wrapper.
* @param {object} [data] - Parsed options.
* @returns {Promise<void>}
*/
export async function run(msg) {
export async function run(msg, data) {
const p = await this.getPlayer(msg, false, false, false);
if (!p) return;
const fromVal = data?.get?.("from")?.value;
const toVal = data?.get?.("to")?.value;
if (fromVal != null && fromVal !== undefined) {
if (fromVal < 1) return msg.replyEmbed("Queue position must be 1 or greater.").catch(() => {});
const startIdx = Math.floor(fromVal) - 1;
const endIdx = (toVal != null && toVal !== undefined && toVal >= 1) ? Math.floor(toVal) - 1 : startIdx;
const res = p.removeRange(startIdx, endIdx);
return msg.replyEmbed(res).catch(() => {});
}
p.clear();
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
+129 -16
View File
@@ -13,51 +13,164 @@ import { EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
/** @type {CommandBuilder} @description Command definition for the lyrics command. */
export const command = new CommandBuilder()
.setName("lyrics")
.setDescription("Display synced lyrics from NodeLink", "commands.lyrics")
.setDescription("Display synced or unsynced lyrics for the current track or a queried song.", "commands.lyrics")
.addAliases("lyric", "ly")
.setCategory("music");
.setCategory("music")
.addTextOption(o =>
o.setName("query")
.setDescription("The song title and artist to search lyrics for (optional).", "options.lyrics.query")
.setRequired(false)
);
/** @private @type {string[]} Loading animation frames. */
const LOADING_FRAMES = ["◐", "◓", "◑", "◒"];
/** @private @type {number} Session timeout in milliseconds (3 minutes). */
const SESSION_MS = 180_000;
/**
* @private
* Search LRCLIB and NodeLink directly for lyrics when no player is active or a custom query is passed.
* @param {object|null} lavalink
* @param {string} rawQuery
* @param {string} searchTitle
* @param {string|null} searchArtist
* @returns {Promise<object|null>}
*/
async function fetchDirectLyrics(lavalink, rawQuery, searchTitle, searchArtist) {
const headers = { "User-Agent": "FluxerBot/1.0 (music bot lyrics lookup)" };
const urls = [];
if (searchArtist) {
const p1 = new URLSearchParams({ track_name: searchTitle, artist_name: searchArtist });
urls.push("https://lrclib.net/api/search?" + p1.toString());
}
const p2 = new URLSearchParams({ q: rawQuery });
urls.push("https://lrclib.net/api/search?" + p2.toString());
let candidates = [];
for (const url of urls) {
try {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(10_000) });
if (!res.ok) continue;
const body = await res.json();
if (Array.isArray(body) && body.length) {
candidates = body;
break;
}
} catch (_) {}
}
if (candidates.length) {
const best = Utils.pickBestLyrics(candidates, {
title: searchTitle,
artist: searchArtist,
durationSec: null,
}) || candidates[0];
if (best) {
if (best.instrumental) {
return { text: "", source: "LRCLIB", synced: false, lines: [], title: best.trackName, artist: best.artistName };
}
const parsed = Utils.parseSyncedLyrics(best.syncedLyrics);
if (parsed) {
return {
text: parsed.map(l => l.text).join("\n"),
source: "LRCLIB",
synced: true,
lines: parsed,
title: best.trackName,
artist: best.artistName,
};
}
if (best.plainLyrics) {
const text = String(best.plainLyrics).trim();
return {
text,
source: "LRCLIB",
synced: false,
lines: text.split("\n").map(l => ({ text: l })),
title: best.trackName,
artist: best.artistName,
};
}
}
}
const node = lavalink?.getNode?.() ?? null;
if (node) {
try {
const path = `/loadlyrics?identifier=${encodeURIComponent(rawQuery)}`;
const results = await node.request(path);
if (results?.data?.lines?.length) {
return {
text: results.data.lines.map(l => l.text).join("\n"),
source: "Lavalink",
synced: results.data.lines.some(l => l.startTimeMs != null),
lines: results.data.lines,
title: searchTitle,
artist: searchArtist,
};
}
} catch (_) {}
}
return null;
}
/**
* @async
* Run handler for the lyrics command.
* Fetches lyrics for the currently playing track and displays them with
* paginated embeds and reaction-based navigation.
* @param {object} message - The command message wrapper.
* @param {object} [data] - Parsed options.
* @returns {Promise<void>}
*/
export async function run(message) {
export async function run(message, data) {
const query = data?.get?.("query")?.value?.trim() || null;
const p = await this.getPlayer(message, false, false, false);
if (!p) return;
const current = p.queue.getCurrent();
if (!current) {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.lyrics.nothingPlaying"));
return message.reply({ embeds: [embed] });
let searchTitle = null;
let searchArtist = null;
let current = null;
if (query) {
searchTitle = query;
const parts = query.split(/\s*[-–—]\s*/);
if (parts.length >= 2) {
searchArtist = parts[0].trim();
searchTitle = parts.slice(1).join(" - ").trim();
}
} else {
current = p?.queue?.getCurrent() ?? null;
if (!current) {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.lyrics.nothingPlaying"));
return message.reply({ embeds: [embed] });
}
searchTitle = current.title;
searchArtist = current.artists?.[0]?.name || current.author?.name || "Unknown Artist";
}
let frame = 0;
const loadingMsg = await message.reply({ embeds: [
new EmbedBuilder().setColor(getGlobalColor())
.setDescription(`${LOADING_FRAMES[0]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(current.title, 40) }))
.setDescription(`${LOADING_FRAMES[0]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(searchTitle, 40) }))
] });
const loadingInterval = setInterval(() => {
frame = (frame + 1) % LOADING_FRAMES.length;
loadingMsg.edit({ embeds: [
new EmbedBuilder().setColor(getGlobalColor())
.setDescription(`${LOADING_FRAMES[frame]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(current.title, 40) }))
.setDescription(`${LOADING_FRAMES[frame]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(searchTitle, 40) }))
] }).catch(() => {});
}, 800);
try {
const result = await p.lyrics();
let result = null;
if (p) {
result = await p.lyrics(query);
} else {
result = await fetchDirectLyrics(this.lavalink, query, searchTitle, searchArtist);
}
clearInterval(loadingInterval);
@@ -65,7 +178,7 @@ export async function run(message) {
return loadingMsg.edit({ embeds: [
new EmbedBuilder().setColor(getGlobalColor())
.setDescription(
this.t(message, "responses.lyrics.noLyrics", { title: Utils.truncate(current.title, 40) })
this.t(message, "responses.lyrics.noLyrics", { title: Utils.truncate(searchTitle, 40) })
)
] });
}
@@ -73,8 +186,8 @@ export async function run(message) {
try { await loadingMsg.message.delete(); } catch(e) { logger.warn("[Lyrics] Error:", e?.message); }
const syncIndicator = result.synced ? this.t(message, "responses.lyrics.syncedBadge") : "";
const displayTitle = Utils.cleanTitle(current.title);
const artist = current.artists?.[0]?.name || current.author?.name || "Unknown Artist";
const displayTitle = result.title || (current ? Utils.cleanTitle(current.title) : Utils.cleanTitle(searchTitle));
const artist = result.artist || (current?.artists?.[0]?.name || current?.author?.name) || searchArtist || "Unknown Artist";
const lines = result.text.split("\n").filter(l => l.trim());
const totalLines = lines.length;
+21 -9
View File
@@ -8,26 +8,38 @@ import { CommandBuilder } from "../src/commands/index.mjs";
/** @type {CommandBuilder} @description Command definition for the remove command. */
export const command = new CommandBuilder()
.setName("remove")
.setDescription("Remove a specific song from the queue.", "commands.remove")
.setDescription("Remove a specific song or range of songs (e.g. `3` or `3-6`) from the queue.", "commands.remove")
.setCategory("music")
.addNumberOption(opt =>
opt.setName("index")
.setDescription("The position of the song in the queue. You can view the indices with the 'list' command", "options.remove.index")
.addTextOption(opt =>
opt.setName("position")
.setDescription("The position or range of the song(s) to remove (e.g. `3` or `3-6`).", "options.remove.index")
.setRequired(true));
/**
* @async
* Run handler for the remove command.
* Removes a track at the specified 1-based index from the queue.
* Removes a track or range of tracks at the specified 1-based indices from the queue.
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing the index option.
* @param {object} data - Parsed command data containing the position option.
* @returns {Promise<void>}
*/
export async function run(message, data) {
const p = await this.getPlayer(message, false, false, false);
if (!p) return;
const index = data.get("index")?.value;
if (index === null || index === undefined || index < 1) return message.replyEmbed("Queue position must be 1 or greater.").catch(() => {});
const res = p.remove(index - 1);
const raw = String(data.get("position")?.value ?? "").trim();
if (!raw) return message.replyEmbed("Please provide a queue position or range (e.g. `3` or `3-6`).").catch(() => {});
const rangeMatch = raw.match(/^(\d+)\s*[-–—to:]+\s*(\d+)$/i) || raw.match(/^(\d+)\s+(\d+)$/);
if (rangeMatch) {
const from = parseInt(rangeMatch[1], 10);
const to = parseInt(rangeMatch[2], 10);
if (from < 1 || to < 1) return message.replyEmbed("Queue positions must be 1 or greater.").catch(() => {});
const res = p.removeRange(from - 1, to - 1);
return message.replyEmbed(res).catch(() => {});
}
const single = parseInt(raw, 10);
if (isNaN(single) || single < 1) return message.replyEmbed("Queue position must be 1 or greater.").catch(() => {});
const res = p.remove(single - 1);
message.replyEmbed(res).catch(() => {});
}