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

+5
View File
@@ -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) {
+16 -1
View File
@@ -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
+25 -9
View File
@@ -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) {
+54
View File
@@ -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<boolean>}
*/
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) {
+17
View File
@@ -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<object> }|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.