From 665be29a16ccf0d1150108e167e35bbb68732886 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Thu, 22 Oct 2026 01:16:33 +0300 Subject: [PATCH] feat: on-demand lyrics query, queue range clearing, and nodelink auto-reconnect (#13, #14, #20) --- commands/clear.mjs | 31 +++++- commands/lyrics.mjs | 145 +++++++++++++++++++++++++---- commands/remove.mjs | 30 ++++-- src/core/Bot.mjs | 9 ++ src/music/LavalinkManager.mjs | 5 + src/music/PlayerManager.mjs | 17 +++- src/music/player/PlaybackMixin.mjs | 34 +++++-- src/music/player/Player.mjs | 54 +++++++++++ src/music/player/Queue.mjs | 17 ++++ 9 files changed, 303 insertions(+), 39 deletions(-) diff --git a/commands/clear.mjs b/commands/clear.mjs index 45a8766..a2a2e67 100644 --- a/commands/clear.mjs +++ b/commands/clear.mjs @@ -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} */ -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()) diff --git a/commands/lyrics.mjs b/commands/lyrics.mjs index 8687cf0..13ab05c 100644 --- a/commands/lyrics.mjs +++ b/commands/lyrics.mjs @@ -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} + */ +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} */ -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; diff --git a/commands/remove.mjs b/commands/remove.mjs index 714183e..2c38e94 100644 --- a/commands/remove.mjs +++ b/commands/remove.mjs @@ -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} */ 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(() => {}); } diff --git a/src/core/Bot.mjs b/src/core/Bot.mjs index e445b0a..8b22273 100644 --- a/src/core/Bot.mjs +++ b/src/core/Bot.mjs @@ -288,12 +288,21 @@ class Remix { this.lavalink = new LavalinkManager(config.nodelink ?? {}, client, { id: botId, username: client.user?.username ?? "bot" }); this.lavalink.on("ready", () => { logger.lavalink("[Lavalink] Session ready"); + if (this._hasBooted) { + this.players?.resumeAllOnNodeReconnect?.(); + } + }); + this.lavalink.on("nodeReconnect", () => { + if (this._hasBooted) { + this.players?.resumeAllOnNodeReconnect?.(); + } }); await this.lavalink.init(); this.playerContext.lavalink = this.lavalink; } this.gatewayHandler.onReady(); + this._hasBooted = true; this.fluxerlist?.startAutoStats?.(client); diff --git a/src/music/LavalinkManager.mjs b/src/music/LavalinkManager.mjs index f4ca57d..150eafc 100644 --- a/src/music/LavalinkManager.mjs +++ b/src/music/LavalinkManager.mjs @@ -416,6 +416,7 @@ export class LavalinkManager extends EventEmitter { "[Lavalink] Node ready: " + node.id + " | session: " + this._sessionId ); this.emit("ready", this._sessionId); + this.emit("nodeConnect", node); } catch (e) { logger.warn( "[Lavalink] nodeConnect handler error:", @@ -425,6 +426,10 @@ export class LavalinkManager extends EventEmitter { }; this.lavalink.on("nodeConnect", onNodeConnect); + this.lavalink.on("nodeReconnect", (node) => { + onNodeConnect(node); + this.emit("nodeReconnect", node); + }); setTimeout(() => { if (!this._nodeConnected) { diff --git a/src/music/PlayerManager.mjs b/src/music/PlayerManager.mjs index df03b7c..6034241 100644 --- a/src/music/PlayerManager.mjs +++ b/src/music/PlayerManager.mjs @@ -117,7 +117,7 @@ export class PlayerManager { } /** Find a player by both guild and channel. @param {string} guildId @param {string} channelId @returns {Player|null} */ - getPlayerByGuildAndChannel(guildId, channelId) { + getPlayerByGuildAndChannel(guildId, channelId) { const cId = cleanId(channelId); const players = this.getGuildPlayers(guildId); for (const [mapChannelId, player] of players) { @@ -126,6 +126,21 @@ export class PlayerManager { return null; } + /** + * Auto-resume all active players after a Lavalink/NodeLink node reconnection. + * @async + */ + async resumeAllOnNodeReconnect() { + const activePlayers = [...new Set(this.playerMap.values())].filter(p => p && !p._destroyed && !p.leaving); + if (activePlayers.length === 0) return; + logger.lavalink(`[PlayerManager] Auto-resuming ${activePlayers.length} player(s) after node reconnection...`); + for (const player of activePlayers) { + player.resumePlaybackAfterNodeReconnect?.().catch(e => + logger.warn(`[PlayerManager] Resume failed for guild ${player._guildId}:`, e?.message) + ); + } + } + /** * Check whether a player counts as "busy" — i.e. the bot is actively * serving that channel: a track is loaded (playing or paused), the queue diff --git a/src/music/player/PlaybackMixin.mjs b/src/music/player/PlaybackMixin.mjs index 4df6bff..c94b64d 100644 --- a/src/music/player/PlaybackMixin.mjs +++ b/src/music/player/PlaybackMixin.mjs @@ -643,12 +643,27 @@ const PlaybackMixin = { * @this {import('./Player.mjs').Player} * @returns {Promise<{text: string, source: string, synced: boolean, lines: Array}|null>} */ - async lyrics() { - const current = this.queue.getCurrent(); - if (!current) return null; - - const query = this._buildLyricsQuery(current); - if (!query.title) return null; + async lyrics(customQuery = null) { + let query; + if (customQuery) { + const parts = String(customQuery).split(/\s*[-–—]\s*/); + let artist = null; + let title = customQuery.trim(); + if (parts.length >= 2) { + artist = parts[0].trim(); + title = parts.slice(1).join(" - ").trim(); + } + query = { + title: Utils.cleanTitle(title), + artist: artist ? Utils.cleanTitle(artist) : null, + candidates: [customQuery.trim(), `${artist || ""} ${title}`.trim()].filter(Boolean) + }; + } else { + const current = this.queue.getCurrent(); + if (!current) return null; + query = this._buildLyricsQuery(current); + if (!query.title) return null; + } try { const result = await this._fetchVerifiedLyrics(query); @@ -725,8 +740,9 @@ const PlaybackMixin = { * @returns {Promise<{text: string, source: string, synced: boolean, lines: Array}|null>} */ async _fetchVerifiedLyrics(query) { - const durationMs = this._getTrackDurationMs(this.queue.getCurrent()); - const durationSec = Math.round(durationMs / 1000); + const current = this.queue.getCurrent(); + const durationMs = current ? this._getTrackDurationMs(current) : 0; + const durationSec = durationMs > 0 ? Math.round(durationMs / 1000) : null; const headers = { "User-Agent": "FluxerBot/1.0 (music bot lyrics lookup)" }; const urls = []; @@ -753,7 +769,7 @@ const PlaybackMixin = { title: query.title, artist: query.artist, durationSec, - }); + }) || candidates[0]; if (!best) return null; if (best.instrumental) { diff --git a/src/music/player/Player.mjs b/src/music/player/Player.mjs index 367f2c5..376e85d 100644 --- a/src/music/player/Player.mjs +++ b/src/music/player/Player.mjs @@ -786,6 +786,41 @@ class Player extends EventEmitter { return ":arrow_forward: Resumed"; } + /** + * Compute the current track playback position in milliseconds. + * @returns {number} Elapsed playback position in ms. + */ + computePosition() { + if (!this.startedPlaying) return 0; + if (this._paused && this._pausedAt) { + return Math.max(0, this._pausedAt - this.startedPlaying); + } + return Math.max(0, Date.now() - this.startedPlaying); + } + + /** + * Seamlessly resume playback after a NodeLink/Lavalink node reconnects. + * Re-requests the stream at the last computed position so listeners experience + * minimal interruption. + * @returns {Promise} + */ + async resumePlaybackAfterNodeReconnect() { + if (this._destroyed || this.leaving || !this._voiceConn) return false; + const current = this.queue?.getCurrent(); + if (!current || !this._audioBridge?.playing) return false; + + const posMs = this.computePosition(); + logger.player(`[Player:${this._guildId}] Node reconnected — resuming "${current.title}" at ${Math.round(posMs / 1000)}s`); + + try { + await this._playTrackViaBridge(current, { seekSeconds: posMs / 1000 }); + return true; + } catch (err) { + logger.warn(`[Player:${this._guildId}] Failed to auto-resume on node reconnect:`, err?.message); + return false; + } + } + /** * Skip the current track and advance to the next. Emits "trackSkip" with * the skipped track so autoplay (when enabled) can replenish the queue. @@ -971,6 +1006,25 @@ class Player extends EventEmitter { return msg; } + /** + * Remove a slice or range of tracks from the queue (0-based indices, inclusive). + * @param {number} from - Starting 0-based index. + * @param {number} to - Ending 0-based index. + * @returns {string} Result message. + */ + removeRange(from, to) { + if (this.isEmpty()) return "The queue is empty."; + const oldSize = this.queue.size(); + const result = this.queue.removeRange(from, to); + if (typeof result === "string") return result; + if (oldSize !== this.queue.size()) this.emit("update", "queue"); + + if (this.isEmpty() && !this.queue.getCurrent()) { + this._startInactivityTimer(); + } + return `:wastebasket: Successfully removed **${result.count}** track${result.count === 1 ? "" : "s"} from the queue.`; + } + /** @private Stop the audio bridge if currently playing. */ _bridgeStop() { if (this._audioBridge?.playing) { diff --git a/src/music/player/Queue.mjs b/src/music/player/Queue.mjs index 44e6a70..184e1be 100644 --- a/src/music/player/Queue.mjs +++ b/src/music/player/Queue.mjs @@ -76,6 +76,23 @@ export class Queue extends EventEmitter { return `Successfully removed **${title}** from the queue.`; } + /** + * Remove a range of tracks from the queue (0-based indices, inclusive). + * @param {number} from - Starting 0-based index. + * @param {number} to - Ending 0-based index. + * @returns {{ count: number, removed: Array }|string} + */ + removeRange(from, to) { + if (this.isEmpty()) return "The queue is empty."; + const start = Math.max(0, Math.min(from, to)); + const end = Math.min(this.data.length - 1, Math.max(from, to)); + if (start >= this.data.length) return "Index out of bounds"; + const deleteCount = (end - start) + 1; + const removed = this.data.splice(start, deleteCount); + this.emit("queue", { type: "removeRange", data: { start, end, count: removed.length, old: this.data.slice(), removed, new: this.data } }); + return { count: removed.length, removed }; + } + /** * Move a track from one position to another (0-based indices). * @param {number} from - Source index.