Compare commits

...
3 Commits
Author SHA1 Message Date
NoLogicAlan 0e3087c7b5 ... 2026-10-12 02:12:33 +03:00
NoLogicAlan 824d989f34 (test)Improve music search ranking and Fluxer dependencies 2026-10-12 02:03:51 +03:00
NoLogicAlan b4bb6c26e5 HOTFIX 2026-10-12 00:26:44 +03:00
6 changed files with 248 additions and 17 deletions

No files matched your search

+2 -1
View File
@@ -166,6 +166,7 @@ export const command = new CommandBuilder()
) )
.addExamples( .addExamples(
"$prefixplay take over league of legends", "$prefixplay take over league of legends",
"$prefixplay pop",
"$prefixplay sp: blinding lights", "$prefixplay sp: blinding lights",
"$prefixplay dz: get lucky", "$prefixplay dz: get lucky",
"$prefixplay -p yt take over league of legends", "$prefixplay -p yt take over league of legends",
@@ -183,7 +184,7 @@ export const command = new CommandBuilder()
) )
.addTextOption(option => .addTextOption(option =>
option.setName("query") option.setName("query")
.setDescription("A search query, URL, or provider-prefixed query like `sp: song name`.", "options.play.query") .setDescription("A search query, music genre (for example `pop`), URL, or provider-prefixed query like `sp: song name`.", "options.play.query")
.setRequired(true) .setRequired(true)
) )
.addChoiceOption(o => .addChoiceOption(o =>
+2 -1
View File
@@ -21,6 +21,7 @@ export const command = new CommandBuilder()
.setCategory("music") .setCategory("music")
.addExamples( .addExamples(
"$prefixsearch never gonna give you up", "$prefixsearch never gonna give you up",
"$prefixsearch pop",
"$prefixsearch sp: blinding lights", "$prefixsearch sp: blinding lights",
"$prefixsearch -p dz get lucky" "$prefixsearch -p dz get lucky"
) )
@@ -33,7 +34,7 @@ export const command = new CommandBuilder()
, true) , true)
.addTextOption(o => .addTextOption(o =>
o.setName("query") o.setName("query")
.setDescription("The query to search for, or a provider-prefixed query like `sp: song name`.", "options.search.query") .setDescription("The song, artist, or music genre to search for; provider prefixes such as `sp: song name` also work.", "options.search.query")
.setRequired(true) .setRequired(true)
); );
+3 -3
View File
@@ -4,7 +4,7 @@
"node": ">=22.13.0" "node": ">=22.13.0"
}, },
"dependencies": { "dependencies": {
"@fluxerjs/core": "^3.2.0", "@fluxerjs/core": "^3.3.0",
"@fluxerjs/sharding": "^3.0.0", "@fluxerjs/sharding": "^3.0.0",
"@fluxerjs/util": "^3.1.0", "@fluxerjs/util": "^3.1.0",
"@fluxerjs/voice": "^3.1.0", "@fluxerjs/voice": "^3.1.0",
@@ -12,9 +12,9 @@
"ffprobe-static": "^3.1.0", "ffprobe-static": "^3.1.0",
"lavalink-client": "^2.11.0", "lavalink-client": "^2.11.0",
"mysql2": "^3.9.0", "mysql2": "^3.9.0",
"opusscript": "^0.0.8", "opusscript": "^0.1.1",
"prism-media": "^1.3.5", "prism-media": "^1.3.5",
"redis": "^5.12.1" "redis": "^6.3.0"
}, },
"scripts": { "scripts": {
"dev": "node --inspect index.mjs --trace-warnings", "dev": "node --inspect index.mjs --trace-warnings",
+7 -5
View File
@@ -497,11 +497,13 @@ const BotVoiceMixin = {
system: true, system: true,
}); });
await player.playNext(); if (current && pos > 0 && dur > 0) player._resumeSeekMs = pos;
if (!player.queue.getCurrent()) {
if (current && pos > 0 && dur > 0) { player.playNext().catch((e) => logger.warn(`[Restore] playNext failed for guild ${guildId}:`, e?.message ?? e));
await new Promise((r) => setTimeout(r, 800)); // let the bridge settle } else if (player._resumeSeekMs > 0) {
try { await player.seekToPosition(pos); } catch (_) {} const seekTo = player._resumeSeekMs;
player._resumeSeekMs = 0;
setTimeout(() => { player.seekToPosition(seekTo).catch(() => {}); }, 800).unref?.();
} }
logger.player(`[Restore] Guild ${guildId}: ${player.queue.data.length} track(s) restored, resuming at ${pos}ms.`); logger.player(`[Restore] Guild ${guildId}: ${player.queue.data.length} track(s) restored, resuming at ${pos}ms.`);
+12 -2
View File
@@ -175,7 +175,12 @@ const PlaybackMixin = {
this._radioReconnects = 0; this._radioReconnects = 0;
if (songData.type !== "radio" || !this._radioAnnounced) { if (songData.type !== "radio" || !this._radioAnnounced) {
this.announceSong(songData); const now = Date.now();
const last = this._lastAnnounce;
const dup = last && !this.queue.songLoop && last.key === (songData.url || songData.title) && now - last.at < 8_000;
if (!dup) this.announceSong(songData);
else logger.player(`[Player:${this._guildId}] Suppressed duplicate now-playing for: ${songData.title}`);
this._lastAnnounce = { key: songData.url || songData.title, at: now };
if (songData.type === "radio") this._radioAnnounced = true; if (songData.type === "radio") this._radioAnnounced = true;
} }
this._skipVotes.clear(); this._skipVotes.clear();
@@ -183,7 +188,12 @@ const PlaybackMixin = {
try { try {
const playUri = songData.url; const playUri = songData.url;
const seekSec = trackOptMatch?.startMs > 0 ? trackOptMatch.startMs / 1000 : 0; const resumeMs = this._resumeSeekMs > 0 ? this._resumeSeekMs : 0;
this._resumeSeekMs = 0;
const seekSec = resumeMs > 0
? resumeMs / 1000
: (trackOptMatch?.startMs > 0 ? trackOptMatch.startMs / 1000 : 0);
if (resumeMs > 0) this.startedPlaying = Date.now() - resumeMs;
if (!playUri || !Utils.isValidUrl(playUri)) { if (!playUri || !Utils.isValidUrl(playUri)) {
logger.warn(`[Player] No valid URL for track: ${songData.title} (url=${songData.url}), trying search...`); logger.warn(`[Player] No valid URL for track: ${songData.title} (url=${songData.url}), trying search...`);
+222 -5
View File
@@ -14,6 +14,175 @@ import { logger } from "../../core/Logger.mjs";
import { PROVIDERS, PROVIDER_NAMES } from "../providers.mjs"; import { PROVIDERS, PROVIDER_NAMES } from "../providers.mjs";
import { bilibiliEnabled, isBilibiliUrl, resolveBilibiliVideo } from "../bilibili/index.mjs"; import { bilibiliEnabled, isBilibiliUrl, resolveBilibiliVideo } from "../bilibili/index.mjs";
/**
* Broad music genres are ambiguous when used by themselves: searching for
* `pop`, for example, often returns a song literally named "Pop" instead of
* pop music. Keep this deliberately conservative so artist and song names
* continue to be searched exactly as the user entered them.
*/
const GENRE_TERMS = new Set([
"pop", "rock", "rap", "hip hop", "hip-hop", "rnb", "r&b", "jazz", "blues",
"country", "metal", "classical", "edm", "electronic", "dance", "house",
"techno", "trance", "reggae", "latin", "kpop", "k-pop", "indie", "folk",
"punk", "soul", "funk", "disco", "gospel", "ambient", "lofi", "lo-fi",
]);
/**
* Return the provider queries to try, ordered by the most useful intent.
* A one-genre query becomes e.g. `pop music`, which asks providers for the
* topic/genre rather than an exact track title. The untouched input remains
* a fallback for providers whose catalogues do better with the short term.
*
* @param {string} query
* @param {string} source Lavalink search prefix.
* @returns {string[]}
*/
function searchQueryVariants(query, source) {
const original = String(query ?? "").trim().replace(/\s+/g, " ");
if (!original) return [];
if (source === "gtts" || source === "ftts") return [original];
const normalized = original.toLowerCase().replace(/[.!?,]+$/g, "");
if (!GENRE_TERMS.has(normalized)) return [original];
return [`${original} music`, `${original} songs`, original];
}
/** @param {unknown} value @returns {string} */
function normalizeSearchText(value) {
return String(value ?? "")
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9&]+/g, " ")
.trim()
.replace(/\s+/g, " ");
}
/**
* Small bounded edit-distance helper used only for ranking already-returned
* tracks. It never invents a new query or makes an extra network request.
* @param {string} left
* @param {string} right
* @returns {number}
*/
function editDistance(left, right) {
if (left === right) return 0;
if (!left) return right.length;
if (!right) return left.length;
let previous = Array.from({ length: right.length + 1 }, (_, i) => i);
for (let i = 1; i <= left.length; i++) {
const current = [i];
for (let j = 1; j <= right.length; j++) {
current[j] = Math.min(
current[j - 1] + 1,
previous[j] + 1,
previous[j - 1] + (left[i - 1] === right[j - 1] ? 0 : 1),
);
}
previous = current;
}
return previous[right.length];
}
/**
* Return the best spelling similarity of a user term against words in a
* result. A conservative threshold prevents loosely-related tracks from
* jumping ahead merely because they share a couple of letters.
* @param {string} term
* @param {string} haystack
* @returns {number}
*/
function bestTokenSimilarity(term, haystack) {
if (term.length < 4) return 0;
let best = 0;
for (const candidate of haystack.split(" ")) {
if (candidate.length < 4) continue;
const maxLength = Math.max(term.length, candidate.length);
const similarity = 1 - editDistance(term, candidate) / maxLength;
if (similarity > best) best = similarity;
}
return best;
}
/** @param {string} haystack @param {string} term @returns {boolean} */
function hasExactToken(haystack, term) {
return haystack.split(" ").includes(term);
}
/**
* Assign a relevance score without relying on provider-specific ordering.
* Lavalink providers do not all sort results the same way, so title/artist
* matching gives users predictable results across YouTube Music, YouTube,
* SoundCloud, and the optional catalog providers.
*
* @param {object} track
* @param {string} query
* @returns {number}
*/
function scoreSearchTrack(track, query) {
const info = track?.info ?? track ?? {};
const needle = normalizeSearchText(query);
const terms = needle.split(" ").filter(Boolean);
const title = normalizeSearchText(info.title);
const author = normalizeSearchText(info.author);
const album = normalizeSearchText(info.albumName ?? info.album?.name);
const isGenreQuery = GENRE_TERMS.has(needle);
let score = 0;
if (title === needle) score += isGenreQuery ? 8 : 100;
else if (title.includes(needle)) score += isGenreQuery ? 12 : 50;
if (author === needle) score += 55;
else if (author.includes(needle)) score += 25;
for (const term of terms) {
const titleHasTerm = hasExactToken(title, term);
const authorHasTerm = hasExactToken(author, term);
const albumHasTerm = hasExactToken(album, term);
const titlePartial = term.length >= 4 && title.includes(term);
const authorPartial = term.length >= 4 && author.includes(term);
const albumPartial = term.length >= 4 && album.includes(term);
if (titleHasTerm) score += 14;
else if (titlePartial) score += 3;
if (authorHasTerm) score += 10;
else if (authorPartial) score += 2;
if (albumHasTerm) score += 4;
else if (albumPartial) score += 1;
if (!titleHasTerm && !authorHasTerm && !albumHasTerm && !titlePartial && !authorPartial && !albumPartial) {
const similarity = Math.max(
bestTokenSimilarity(term, title),
bestTokenSimilarity(term, author),
bestTokenSimilarity(term, album),
);
if (similarity >= 0.84) score += 8 + Math.round((similarity - 0.84) * 50);
}
}
if (author.includes("topic")) score += isGenreQuery ? 45 : 8;
if (info.isStream) score -= 8;
if (info.isSeekable === false) score -= 3;
for (const qualifier of ["cover", "tribute", "karaoke", "instrumental", "nightcore", "slowed", "reverb", "remix", "mashup"]) {
if (title.includes(qualifier) && !needle.includes(qualifier)) score -= 60;
}
if (title.includes("live") && !needle.includes("live")) score -= 15;
const length = Number(info.length ?? info.durationMs ?? 0);
if (length >= 30_000 && length <= 30 * 60_000) score += 3;
return score;
}
/** @param {object} track @returns {string} */
function searchTrackKey(track) {
const info = track?.info ?? track ?? {};
return String(track?.encoded ?? info.identifier ?? info.uri ?? "") ||
`${normalizeSearchText(info.title)}|${normalizeSearchText(info.author)}`;
}
/** /**
* @type {object} * @type {object}
* @description Search mixin — applied to Player. * @description Search mixin — applied to Player.
@@ -32,9 +201,10 @@ const SearchMixin = {
if (!this._lavalink) return { type: "error", data: "Audio node not ready." }; if (!this._lavalink) return { type: "error", data: "Audio node not ready." };
await this._lavalink.waitForNode({ timeoutMs: 15_000 }); await this._lavalink.waitForNode({ timeoutMs: 15_000 });
const isUrl = typeof query === "string" && Utils.isValidUrl(query); const isUrl = typeof query === "string" && Utils.isValidUrl(query);
const source = this._getSource(provider);
const result = isUrl const result = isUrl
? await this._lavalink.search(query) ? await this._lavalink.search(query)
: await this._lavalink.search(query, { source: this._getSource(provider) }); : await this._searchFreeText(query, source);
const tracks = (result?.tracks ?? []).map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean); const tracks = (result?.tracks ?? []).map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean);
if (!tracks.length) return null; if (!tracks.length) return null;
return tracks.length === 1 ? { type: "video", data: tracks[0] } : { type: "list", data: tracks }; return tracks.length === 1 ? { type: "video", data: tracks[0] } : { type: "list", data: tracks };
@@ -60,7 +230,7 @@ const SearchMixin = {
await this._lavalink.waitForNode({ timeoutMs: 15_000 }); await this._lavalink.waitForNode({ timeoutMs: 15_000 });
const source = this._getSource(provider); const source = this._getSource(provider);
const result = await this._lavalink.search(query, { source }); const result = await this._searchFreeText(query, source);
const lcTracks = result?.tracks ?? []; const lcTracks = result?.tracks ?? [];
const results = lcTracks.slice(0, this.resultLimit).map(t => this._lcTrackToVideo(t)).filter(Boolean); const results = lcTracks.slice(0, this.resultLimit).map(t => this._lcTrackToVideo(t)).filter(Boolean);
@@ -188,6 +358,53 @@ const SearchMixin = {
return PROVIDERS[provider]?.prefix ?? (provider + "search"); return PROVIDERS[provider]?.prefix ?? (provider + "search");
}, },
/**
* Search free text with a topic-aware first pass. This is shared by
* `%play`, `%search`, and internal queries so they all interpret broad
* genre requests consistently.
*
* @private
* @this {import('./Player.mjs').Player}
* @param {string} query
* @param {string} source Lavalink search prefix.
* @returns {Promise<object|null>}
*/
async _searchFreeText(query, source) {
const variants = searchQueryVariants(query, source);
const attempts = await Promise.allSettled(
variants.map(candidate => this._lavalink.search(candidate, { source }))
);
const successful = attempts
.filter(attempt => attempt.status === "fulfilled")
.map(attempt => attempt.value)
.filter(Boolean);
if (successful.length === 0) {
const failed = attempts.find(attempt => attempt.status === "rejected");
if (failed) throw failed.reason;
return null;
}
const unique = new Map();
for (const result of successful) {
for (const track of result?.tracks ?? []) {
const key = searchTrackKey(track);
if (!unique.has(key)) unique.set(key, track);
}
}
const tracks = [...unique.values()]
.map((track, index) => ({ track, index, score: scoreSearchTrack(track, query) }))
.sort((a, b) => b.score - a.score || a.index - b.index)
.map(({ track }) => track);
if (variants.length > 1) {
logger.player(`[Player] Topic-aware search for "${query}": ${tracks.length} unique results ranked from ${variants.length} queries.`);
}
return { ...successful[0], tracks };
},
/** /**
* Search for a track and add it to the queue. Handles URL loading with * Search for a track and add it to the queue. Handles URL loading with
* YouTube normalization + oEmbed title fallback and playlist expansion; * YouTube normalization + oEmbed title fallback and playlist expansion;
@@ -249,7 +466,7 @@ const SearchMixin = {
if (isUrl) { if (isUrl) {
result = await this._lavalink.search(searchQuery); result = await this._lavalink.search(searchQuery);
} else { } else {
result = await this._lavalink.search(searchQuery, { source }); result = await this._searchFreeText(searchQuery, source);
} }
} catch (searchErr) { } catch (searchErr) {
logger.warn("[Player] URL/primary search failed:", searchErr?.message); logger.warn("[Player] URL/primary search failed:", searchErr?.message);
@@ -304,7 +521,7 @@ const SearchMixin = {
events.emit("message", "No results yet — trying **" + fb.label + "**..."); events.emit("message", "No results yet — trying **" + fb.label + "**...");
let fbResult = null; let fbResult = null;
try { try {
fbResult = await this._lavalink.search(searchQuery, { source: fb.source }); fbResult = await this._searchFreeText(searchQuery, fb.source);
} catch (_) { fbResult = null; } } catch (_) { fbResult = null; }
if (fbResult?.tracks?.length > 0) { if (fbResult?.tracks?.length > 0) {
const video = this._lcTrackToVideo(fbResult.tracks[0], trackMeta); const video = this._lcTrackToVideo(fbResult.tracks[0], trackMeta);
@@ -377,7 +594,7 @@ const SearchMixin = {
if (!this._lavalink) return []; if (!this._lavalink) return [];
try { try {
const source = this._getSource(provider); const source = this._getSource(provider);
const result = await this._lavalink.search(query, { source }); const result = await this._searchFreeText(query, source);
return result.tracks || []; return result.tracks || [];
} catch (e) { } catch (e) {
logger.error(`[Player] lavalink search error:`, e?.message); logger.error(`[Player] lavalink search error:`, e?.message);