This commit is contained in:
NoLogicAlan committed 2026-09-15 03:19:34 +03:00
1 parent f1c87d410d
commit 748eafaf43
8 files changed
+54 -21

No files matched your search

+12 -15
View File
@@ -10,7 +10,6 @@ import { Utils } from "../../src/utils/Utils.mjs";
import { logger } from "../../src/core/Logger.mjs"; import { logger } from "../../src/core/Logger.mjs";
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs"; import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs";
import { notLinked, extractPeriod } from "./shared.mjs"; import { notLinked, extractPeriod } from "./shared.mjs";
import { getGuildLinkedUsers } from "./whoknows.mjs";
/** /**
* Action names dispatched to this module. * Action names dispatched to this module.
@@ -67,6 +66,7 @@ function buildTrackList(username, title, tracks, tr, showPlaycount = false, pref
* @param {function(string, object=): string} tr - Translator bound to the invoking message. * @param {function(string, object=): string} tr - Translator bound to the invoking message.
* @param {object} [opts] - Extra options. * @param {object} [opts] - Extra options.
* @param {string|null} [opts.requesterId] - Invoking user's ID for the "you" marker. * @param {string|null} [opts.requesterId] - Invoking user's ID for the "you" marker.
* @param {string|null} [opts.extraLine] - Extra description line (e.g. the requester's rank) appended below the list.
* @returns {EmbedBuilder} The constructed embed. * @returns {EmbedBuilder} The constructed embed.
*/ */
function buildLeaderboardEmbed(lb, pageIdx, prefix, tr, opts = {}) { function buildLeaderboardEmbed(lb, pageIdx, prefix, tr, opts = {}) {
@@ -84,7 +84,7 @@ function buildLeaderboardEmbed(lb, pageIdx, prefix, tr, opts = {}) {
return `${medal} **${rank}.** ${who}${lfName} — **${count}** ${tr("responses.lastfm.leaderboardScrobbles")}${marker}`; return `${medal} **${rank}.** ${who}${lfName} — **${count}** ${tr("responses.lastfm.leaderboardScrobbles")}${marker}`;
}); });
const desc = lines.join("\n").slice(0, 4096); const desc = (lines.join("\n") + (opts.extraLine ? `\n\n${opts.extraLine}` : "")).slice(0, 4096);
const title = lb.scope === "server" const title = lb.scope === "server"
? tr("responses.lastfm.leaderboardTitleServer") ? tr("responses.lastfm.leaderboardTitleServer")
: tr("responses.lastfm.leaderboardTitleGlobal"); : tr("responses.lastfm.leaderboardTitleGlobal");
@@ -162,18 +162,9 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar
case "leaderboard": case "leaderboard":
case "lb": { case "lb": {
/* Server scope when the guild's members are resolvable (ranks only
people actually in this server), global fallback for DMs. */
const guild = msg.message?.guild ?? msg.message?.member?.guild ?? null;
const guildIds = guild ? await getGuildLinkedUsers(guild).catch(() => []) : [];
const useServer = guildIds.length > 0;
const fetchLb = (page, perPage = 10) => useServer
? lastfm.getServerLeaderboard(guildIds, page, perPage)
: lastfm.getLeaderboard(page, perPage);
let lb; let lb;
try { try {
lb = await fetchLb(0); lb = await lastfm.getLeaderboard(0, 10);
} catch (err) { } catch (err) {
return msg.reply({ return msg.reply({
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
@@ -188,8 +179,14 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar
}); });
} }
let myRank = null;
try { myRank = await lastfm.getUserRank?.(userId) ?? null; } catch (_) { myRank = null; }
const rankLine = () => (myRank && !lb.entries.some(e => String(e.userId) === String(userId))
? tr("responses.lastfm.leaderboardYourRank", { rank: myRank.rank, count: Utils.formatNumber(myRank.scrobbleCount) })
: null);
if (lb.totalPages <= 1) { if (lb.totalPages <= 1) {
const embed = buildLeaderboardEmbed(lb, 0, prefix, tr, { requesterId: userId }); const embed = buildLeaderboardEmbed(lb, 0, prefix, tr, { requesterId: userId, extraLine: rankLine() });
return msg.reply({ embeds: [embed] }); return msg.reply({ embeds: [embed] });
} }
@@ -199,7 +196,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar
const footerText = expired const footerText = expired
? tr("responses.lastfm.leaderboardControlsExpired") ? tr("responses.lastfm.leaderboardControlsExpired")
: tr("responses.lastfm.leaderboardPageFooter", { current: pageIdx + 1, total: lb.totalPages }); : tr("responses.lastfm.leaderboardPageFooter", { current: pageIdx + 1, total: lb.totalPages });
const embed = buildLeaderboardEmbed(lb, pageIdx, prefix, tr, { requesterId: userId }); const embed = buildLeaderboardEmbed(lb, pageIdx, prefix, tr, { requesterId: userId, extraLine: rankLine() });
embed.setFooter({ text: footerText }); embed.setFooter({ text: footerText });
return { embeds: [embed] }; return { embeds: [embed] };
}; };
@@ -249,7 +246,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar
} }
try { try {
lb = await fetchLb(currentPage); lb = await lastfm.getLeaderboard(currentPage, 10);
} catch(e) { logger.warn("[LastFm] Error:", e?.message); } } catch(e) { logger.warn("[LastFm] Error:", e?.message); }
await replyMsg.edit(buildPage(currentPage)).catch(() => {}); await replyMsg.edit(buildPage(currentPage)).catch(() => {});
+30
View File
@@ -357,6 +357,36 @@ const ServerStatsMixin = {
return { entries, totalUsers, page, perPage, totalPages }; return { entries, totalUsers, page, perPage, totalPages };
}, },
/**
* Global rank (1-based) of one user on the all-time scrobble leaderboard.
* Returns null when the user is not linked or has no scrobbles recorded
* yet (they are not ranked). Used so anyone can check whether they are
* top 1, 2, 3 ... even when their row is not on the visible page.
* @async
* @param {string} userId - Platform user ID to look up.
* @returns {Promise<{rank: number, scrobbleCount: number}|null>} Rank info or null.
*/
async getUserRank(userId) {
if (!this.enabled || !userId) return null;
const pool = await this._getPool();
const f = this._botIdFilter();
const [mine] = await pool.execute(
`SELECT scrobble_count FROM lastfm_users WHERE user_id = ?${f.where}`,
[String(userId), ...f.params]
);
const count = Number(mine[0]?.scrobble_count ?? 0);
if (!(count > 0)) return null;
const [ahead] = await pool.execute(
`SELECT COUNT(*) AS n FROM lastfm_users WHERE scrobble_count > ?${f.where}`,
[count, ...f.params]
);
return { rank: Number(ahead[0]?.n ?? 0) + 1, scrobbleCount: count };
},
/** /**
* Get the scrobble leaderboard scoped to a set of platform user IDs * Get the scrobble leaderboard scoped to a set of platform user IDs
* (typically the members of one guild), with pagination. Refreshes only * (typically the members of one guild), with pagination. Refreshes only
+2 -1
View File
@@ -734,7 +734,8 @@
"crownsFooter": "يمتلك {{count}} تاجاً", "crownsFooter": "يمتلك {{count}} تاجاً",
"noArtistTags": "🏷️ لا توجد وسوم للفنان **{{artist}}**.", "noArtistTags": "🏷️ لا توجد وسوم للفنان **{{artist}}**.",
"artistTagsTitle": "🏷️ وسوم أعلى لـ {{artist}}", "artistTagsTitle": "🏷️ وسوم أعلى لـ {{artist}}",
"listeners": "مستمع" "listeners": "مستمع",
"leaderboardYourRank": "📍 ترتيبك: **#{{rank}}** ({{count}} سكرابل)"
}, },
"messages": { "messages": {
"missingCriticalPermsTitle": "صلاحيات مفقودة — البوت لا يستطيع العمل بشكل صحيح", "missingCriticalPermsTitle": "صلاحيات مفقودة — البوت لا يستطيع العمل بشكل صحيح",
+2 -1
View File
@@ -734,7 +734,8 @@
"crownsFooter": "{{count}} تاج هەڵگیراوە", "crownsFooter": "{{count}} تاج هەڵگیراوە",
"noArtistTags": "🏷️ هیچ تاگێک بۆ هونەرمەندی **{{artist}}** نەدۆزرایەوە.", "noArtistTags": "🏷️ هیچ تاگێک بۆ هونەرمەندی **{{artist}}** نەدۆزرایەوە.",
"artistTagsTitle": "🏷️ تاگە سەرەکییەکان بۆ {{artist}}", "artistTagsTitle": "🏷️ تاگە سەرەکییەکان بۆ {{artist}}",
"listeners": "گوێگر" "listeners": "گوێگر",
"leaderboardYourRank": "📍 پلەی تۆ: **#{{rank}}** ({{count}} scrobble)"
}, },
"messages": { "messages": {
"missingCriticalPermsTitle": "مۆڵەتە کەمەکان — بۆت ناتوانێت بە دروستی کار بکات", "missingCriticalPermsTitle": "مۆڵەتە کەمەکان — بۆت ناتوانێت بە دروستی کار بکات",
+2 -1
View File
@@ -734,7 +734,8 @@
"crownsFooter": "{{count}} Krone(n) im Besitz", "crownsFooter": "{{count}} Krone(n) im Besitz",
"noArtistTags": "🏷️ Keine Tags für Künstler **{{artist}}** gefunden.", "noArtistTags": "🏷️ Keine Tags für Künstler **{{artist}}** gefunden.",
"artistTagsTitle": "🏷️ Top-Tags für {{artist}}", "artistTagsTitle": "🏷️ Top-Tags für {{artist}}",
"listeners": "Hörer" "listeners": "Hörer",
"leaderboardYourRank": "📍 Dein Rang: **#{{rank}}** ({{count}} Scrobbles)"
}, },
"messages": { "messages": {
"missingCriticalPermsTitle": "Fehlende Berechtigungen — Bot kann nicht ordnungsgemäß arbeiten", "missingCriticalPermsTitle": "Fehlende Berechtigungen — Bot kann nicht ordnungsgemäß arbeiten",
+2 -1
View File
@@ -409,7 +409,8 @@
"whoknowsAlbumTitle": "👤 Who knows {{album}}?", "whoknowsAlbumTitle": "👤 Who knows {{album}}?",
"noArtistTags": "🏷️ No tags found for artist **{{artist}}**.", "noArtistTags": "🏷️ No tags found for artist **{{artist}}**.",
"artistTagsTitle": "🏷️ Top Tags for {{artist}}", "artistTagsTitle": "🏷️ Top Tags for {{artist}}",
"listeners": "listeners" "listeners": "listeners",
"leaderboardYourRank": "📍 Your rank: **#{{rank}}** ({{count}} scrobbles)"
}, },
"list": { "list": {
"empty": "📭 The queue is empty. Use `{{prefix}}play` to add songs!", "empty": "📭 The queue is empty. Use `{{prefix}}play` to add songs!",
+2 -1
View File
@@ -734,7 +734,8 @@
"crownsFooter": "{{count}} coroa{{plural}} mantida{{plural}}", "crownsFooter": "{{count}} coroa{{plural}} mantida{{plural}}",
"noArtistTags": "🏷️ Nenhuma tag encontrada para o artista **{{artist}}**.", "noArtistTags": "🏷️ Nenhuma tag encontrada para o artista **{{artist}}**.",
"artistTagsTitle": "🏷️ Tags Populares para {{artist}}", "artistTagsTitle": "🏷️ Tags Populares para {{artist}}",
"listeners": "ouvintes" "listeners": "ouvintes",
"leaderboardYourRank": "📍 Sua posição: **#{{rank}}** ({{count}} scrobbles)"
}, },
"messages": { "messages": {
"missingCriticalPermsTitle": "Permissões Ausentes — Bot Não Pode Funcionar Corretamente", "missingCriticalPermsTitle": "Permissões Ausentes — Bot Não Pode Funcionar Corretamente",
+2 -1
View File
@@ -405,7 +405,8 @@
"crownsFooter": "{{count}} taç elde tutuluyor", "crownsFooter": "{{count}} taç elde tutuluyor",
"noArtistTags": "🏷️ Sanatçı **{{artist}}** için etiket bulunamadı.", "noArtistTags": "🏷️ Sanatçı **{{artist}}** için etiket bulunamadı.",
"artistTagsTitle": "🏷️ {{artist}} için En Çok Dinlenen Etiketler", "artistTagsTitle": "🏷️ {{artist}} için En Çok Dinlenen Etiketler",
"listeners": "dinleyici" "listeners": "dinleyici",
"leaderboardYourRank": "📍 Sıralan: **#{{rank}}** ({{count}} scrobble)"
}, },
"list": { "list": {
"empty": "📭 Kuyruk boş. Şarkı eklemek için `{{prefix}}play` kullanın!", "empty": "📭 Kuyruk boş. Şarkı eklemek için `{{prefix}}play` kullanın!",