diff --git a/commands/lastfm/account.mjs b/commands/lastfm/account.mjs index 639d930..afa7ffe 100644 --- a/commands/lastfm/account.mjs +++ b/commands/lastfm/account.mjs @@ -16,12 +16,12 @@ import { notLinked } from "./shared.mjs"; * @type {Set} */ export const ACCOUNT_ACTIONS = new Set([ - "link",, - "confirm",, - "unlink",, - "scrobble",, - "np",, - "profile",, + "link", + "confirm", + "unlink", + "scrobble", + "np", + "profile", "playlists" ]); diff --git a/commands/lastfm/discovery.mjs b/commands/lastfm/discovery.mjs index 8c19fbf..950b8c6 100644 --- a/commands/lastfm/discovery.mjs +++ b/commands/lastfm/discovery.mjs @@ -15,17 +15,17 @@ import { notLinked, extractCurrentTrack } from "./shared.mjs"; * @type {Set} */ export const DISCOVERY_ACTIONS = new Set([ - "friends",, - "fr",, - "weekly",, - "wc",, - "trending",, - "tr",, - "geo",, - "g",, - "artisttracks",, - "atr",, - "search",, + "friends", + "fr", + "weekly", + "wc", + "trending", + "tr", + "geo", + "g", + "artisttracks", + "atr", + "search", "s" ]); @@ -119,7 +119,7 @@ export async function runDiscoveryActions(msg, data, lastfm, prefix, userId, tar const num = String(i + 1).padStart(2, " "); const link = item.url ? `[${item.name}](${item.url})` : item.name; const artistStr = item.artist ? ` by **${item.artist}**` : ""; - return `\`${num}.\` ${link}${artistStr} — **${Utils.formatNumber(item.playcount)}** plays`; + return `\`${num}.\` ${link}${artistStr} — **${Utils.formatNumber(item.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`; }); const desc = lines.join("\n").slice(0, 4096); @@ -163,7 +163,7 @@ export async function runDiscoveryActions(msg, data, lastfm, prefix, userId, tar const num = String(i + 1).padStart(2, " "); const link = item.url ? `[${item.name}](${item.url})` : item.name; const artistStr = item.artist ? ` by **${item.artist}**` : ""; - const extra = item.listeners ? ` — ${Utils.formatNumber(item.listeners)} listeners` : item.playcount ? ` — ${Utils.formatNumber(item.playcount)} plays` : ""; + const extra = item.listeners ? ` — ${Utils.formatNumber(item.listeners)} ${this.t(msg, "responses.lastfm.listeners")}` : item.playcount ? ` — ${Utils.formatNumber(item.playcount)} ${this.t(msg, "responses.lastfm.plays")}` : ""; return `\`${num}.\` ${link}${artistStr}${extra}`; }); diff --git a/commands/lastfm/info.mjs b/commands/lastfm/info.mjs index 6ee80e6..70dd2b7 100644 --- a/commands/lastfm/info.mjs +++ b/commands/lastfm/info.mjs @@ -16,16 +16,16 @@ import { notLinked, extractCurrentTrack, extractPeriod } from "./shared.mjs"; * @type {Set} */ export const INFO_ACTIONS = new Set([ - "artistinfo",, - "ai",, - "albuminfo",, - "ali",, - "trackinfo",, - "ti",, - "topalbums",, - "toptags",, - "tags",, - "cover",, + "artistinfo", + "ai", + "albuminfo", + "ali", + "trackinfo", + "ti", + "topalbums", + "toptags", + "tags", + "cover", "art" ]); @@ -387,7 +387,7 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs let albumTitle = a.name; if (albumTitle.length > 30) albumTitle = albumTitle.slice(0, 27) + "..."; const link = a.url ? `[${albumTitle}](${a.url})` : albumTitle; - return `\`${num}.\` ${link} — **${a.artist}** (**${a.playcount}** plays)`; + return `\`${num}.\` ${link} — **${a.artist}** (**${a.playcount}** ${this.t(msg, "responses.lastfm.plays")})`; }); const desc = lines.join("\n").slice(0, 4096); diff --git a/commands/lastfm/listening.mjs b/commands/lastfm/listening.mjs index d4a2433..0a310be 100644 --- a/commands/lastfm/listening.mjs +++ b/commands/lastfm/listening.mjs @@ -10,19 +10,20 @@ import { Utils } from "../../src/utils/Utils.mjs"; import { logger } from "../../src/core/Logger.mjs"; import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs"; import { notLinked, extractPeriod } from "./shared.mjs"; +import { getGuildLinkedUsers } from "./whoknows.mjs"; /** * Action names dispatched to this module. * @type {Set} */ export const LISTENING_ACTIONS = new Set([ - "loved",, - "top",, - "leaderboard",, - "lb",, - "recent",, - "artists",, - "love",, + "loved", + "top", + "leaderboard", + "lb", + "recent", + "artists", + "love", "unlove" ]); @@ -33,17 +34,18 @@ export const LISTENING_ACTIONS = new Set([ * @param {string} username - The Last.fm username. * @param {string} title - The list title. * @param {object[]} tracks - Array of track objects with name, artist, url, and optional playcount. + * @param {function(string, object=): string} tr - Translator bound to the invoking message. * @param {boolean} [showPlaycount=false] - Whether to show play counts. * @param {string} [prefix="%"] - The command prefix for the footer hint. * @returns {EmbedBuilder} The constructed embed. */ -function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") { +function buildTrackList(username, title, tracks, tr, showPlaycount = false, prefix = "%") { const lines = tracks.map((t, i) => { const num = String(i + 1).padStart(2, " "); let name = t.name; if (name.length > 40) name = name.slice(0, 37) + "..."; const link = t.url ? `[${name}](${t.url})` : name; - const extra = showPlaycount && t.playcount ? ` (${t.playcount} plays)` : ""; + const extra = showPlaycount && t.playcount ? ` (${t.playcount} ${tr("responses.lastfm.plays")})` : ""; return `\`${num}.\` ${link} — **${t.artist}**${extra}`; }); @@ -51,38 +53,47 @@ function buildTrackList(username, title, tracks, showPlaycount = false, prefix = return new EmbedBuilder() .setColor(getGlobalColor()) - .setTitle(`${title} — ${username}`) + .setTitle(title) /* locale titles (lovedTitle/topTitle/recentTitle) already embed {{username}} */ .setDescription(desc) - .setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` }); + .setFooter({ text: tr("responses.lastfm.trackListFooter", { prefix }) }); } /** * Build a scrobble leaderboard embed for a given page. * @private - * @param {object} lb - Leaderboard data with entries and perPage. + * @param {object} lb - Leaderboard data with entries, perPage and scope ("server"|"global"). * @param {number} pageIdx - The page index (0-based). * @param {string} prefix - The command prefix for the footer hint. + * @param {function(string, object=): string} tr - Translator bound to the invoking message. + * @param {object} [opts] - Extra options. + * @param {string|null} [opts.requesterId] - Invoking user's ID for the "you" marker. * @returns {EmbedBuilder} The constructed embed. */ -function buildLeaderboardEmbed(lb, pageIdx, prefix) { +function buildLeaderboardEmbed(lb, pageIdx, prefix, tr, opts = {}) { const MEDALS = ["🥇", "🥈", "🥉"]; const startRank = pageIdx * lb.perPage; + const requesterId = opts.requesterId ? String(opts.requesterId) : null; const lines = lb.entries.map((entry, i) => { const rank = startRank + i + 1; - const medal = rank <= 3 ? MEDALS[rank - 1] : ` `; - const name = entry.username || entry.userId; + const medal = rank <= 3 ? MEDALS[rank - 1] : "` `"; + const who = entry.userId ? `<@${entry.userId}>` : (entry.username || "?"); + const lfName = entry.username ? ` — *${entry.username}*` : ""; + const marker = requesterId && String(entry.userId) === requesterId ? ` **${tr("responses.lastfm.leaderboardYou")}**` : ""; const count = Utils.formatNumber(entry.scrobbleCount); - return `${medal} ${rank}. **${name}** — ${count} scrobbles`; + return `${medal} **${rank}.** ${who}${lfName} — **${count}** ${tr("responses.lastfm.leaderboardScrobbles")}${marker}`; }); const desc = lines.join("\n").slice(0, 4096); + const title = lb.scope === "server" + ? tr("responses.lastfm.leaderboardTitleServer") + : tr("responses.lastfm.leaderboardTitleGlobal"); return new EmbedBuilder() .setColor(getGlobalColor()) - .setTitle("🎵 Scrobble Leaderboard") + .setTitle(title) .setDescription(desc) - .setFooter({ text: `💡 View & sync your count: ${prefix}lastfm profile` }); + .setFooter({ text: tr("responses.lastfm.leaderboardFooterSync", { prefix }) }); } /** @@ -97,6 +108,10 @@ function buildLeaderboardEmbed(lb, pageIdx, prefix) { * @returns {Promise<*>} Whatever the original switch returned for this action. */ export async function runListeningActions(msg, data, lastfm, prefix, userId, targetUserId, action) { + /* Translator bound to this message: every embed builder below renders in + the guild's locale instead of hardcoded English. */ + const tr = (key, repl = {}) => this.t(msg, key, repl); + switch (action) { case "loved": { const user = await lastfm.getUser(userId); @@ -117,7 +132,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar }); } - return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.lovedTitle", { username: user.username }), tracks, false, prefix)] }); + return msg.reply({ embeds: [buildTrackList(user.username, tr("responses.lastfm.lovedTitle", { username: user.username }), tracks, tr, false, prefix)] }); } case "top": { @@ -142,14 +157,23 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar } const periodLabel = period !== "overall" ? ` (${period})` : ""; - return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.topTitle", { username: user.username }) + periodLabel, tracks, true, prefix)] }); + return msg.reply({ embeds: [buildTrackList(user.username, tr("responses.lastfm.topTitle", { username: user.username }) + periodLabel, tracks, tr, true, prefix)] }); } case "leaderboard": 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; try { - lb = await lastfm.getLeaderboard(0, 10); + lb = await fetchLb(0); } catch (err) { return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] @@ -165,7 +189,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar } if (lb.totalPages <= 1) { - const embed = buildLeaderboardEmbed(lb, 0, prefix); + const embed = buildLeaderboardEmbed(lb, 0, prefix, tr, { requesterId: userId }); return msg.reply({ embeds: [embed] }); } @@ -173,9 +197,9 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar const buildPage = (pageIdx, expired = false) => { const footerText = expired - ? this.t(msg, "responses.lastfm.leaderboardControlsExpired") - : this.t(msg, "responses.lastfm.leaderboardPageFooter", { current: pageIdx + 1, total: lb.totalPages }); - const embed = buildLeaderboardEmbed(lb, pageIdx, prefix); + ? tr("responses.lastfm.leaderboardControlsExpired") + : tr("responses.lastfm.leaderboardPageFooter", { current: pageIdx + 1, total: lb.totalPages }); + const embed = buildLeaderboardEmbed(lb, pageIdx, prefix, tr, { requesterId: userId }); embed.setFooter({ text: footerText }); return { embeds: [embed] }; }; @@ -225,7 +249,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar } try { - lb = await lastfm.getLeaderboard(currentPage, 10); + lb = await fetchLb(currentPage); } catch(e) { logger.warn("[LastFm] Error:", e?.message); } await replyMsg.edit(buildPage(currentPage)).catch(() => {}); @@ -254,7 +278,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar }); } - return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.recentTitle", { username: user.username }), tracks, false, prefix)] }); + return msg.reply({ embeds: [buildTrackList(user.username, tr("responses.lastfm.recentTitle", { username: user.username }), tracks, tr, false, prefix)] }); } case "artists": { @@ -284,7 +308,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar let name = a.name; if (name.length > 40) name = name.slice(0, 37) + "..."; const link = a.url ? `[${name}](${a.url})` : name; - return `\`${num}.\` ${link} — **${a.playcount}** plays`; + return `\`${num}.\` ${link} — **${a.playcount}** ${tr("responses.lastfm.plays")}`; }); const desc = lines.join("\n").slice(0, 4096); @@ -292,9 +316,9 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar return msg.reply({ embeds: [new EmbedBuilder() .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.artistsTitle", { username: user.username }) + periodLabel) + .setTitle(tr("responses.lastfm.artistsTitle", { username: user.username }) + periodLabel) .setDescription(desc) - .setFooter({ text: this.t(msg, "responses.lastfm.artistsFooter", { prefix }) })] + .setFooter({ text: tr("responses.lastfm.artistsFooter", { prefix }) })] }); } diff --git a/commands/lastfm/tags.mjs b/commands/lastfm/tags.mjs index b5e3076..e532ad9 100644 --- a/commands/lastfm/tags.mjs +++ b/commands/lastfm/tags.mjs @@ -16,14 +16,14 @@ import { extractCurrentTrack } from "./shared.mjs"; * @type {Set} */ export const TAG_ACTIONS = new Set([ - "tag",, - "artisttags",, - "at",, - "albumtags",, - "alt",, - "tracktags",, - "tt",, - "tagalbums",, + "tag", + "artisttags", + "at", + "albumtags", + "alt", + "tracktags", + "tt", + "tagalbums", "ta" ]); @@ -85,7 +85,7 @@ export async function runTagActions(msg, data, lastfm, prefix, userId, targetUse if (topArtists.length) { const artistStr = topArtists.map((a, i) => { const link = a.url ? `[${a.name}](${a.url})` : a.name; - return `${i + 1}. ${link} (**${Utils.formatNumber(a.playcount)}** plays)`; + return `${i + 1}. ${link} (**${Utils.formatNumber(a.playcount)}** ${this.t(msg, "responses.lastfm.plays")})`; }).join("\n"); fields.push({ name: "Top Artists", value: artistStr.slice(0, 1024), inline: false }); } @@ -316,7 +316,7 @@ export async function runTagActions(msg, data, lastfm, prefix, userId, targetUse const lines = albums.map((a, i) => { const num = String(i + 1).padStart(2, " "); const link = a.url ? `[${a.name}](${a.url})` : a.name; - return `\`${num}.\` ${link} by **${a.artist}**${a.playcount > 0 ? ` (${Utils.formatNumber(a.playcount)} plays)` : ""}`; + return `\`${num}.\` ${link} by **${a.artist}**${a.playcount > 0 ? ` (${Utils.formatNumber(a.playcount)} ${this.t(msg, "responses.lastfm.plays")})` : ""}`; }); const desc = lines.join("\n").slice(0, 4096); diff --git a/commands/lastfm/whoknows.mjs b/commands/lastfm/whoknows.mjs index 4e86fde..4163995 100644 --- a/commands/lastfm/whoknows.mjs +++ b/commands/lastfm/whoknows.mjs @@ -16,31 +16,31 @@ import { notLinked, extractCurrentTrack } from "./shared.mjs"; * @type {Set} */ export const WHOKNOWS_ACTIONS = new Set([ - "whoknows",, - "wk",, - "compare",, - "fmc",, - "refreshmembers",, - "rm",, - "affinity",, - "af",, - "crowns",, - "cr",, - "whoknowstrack",, - "wkt",, - "whoknowsalbum",, + "whoknows", + "wk", + "compare", + "fmc", + "refreshmembers", + "rm", + "affinity", + "af", + "crowns", + "cr", + "whoknowstrack", + "wkt", + "whoknowsalbum", "wka" ]); /** * Get all non-bot user IDs in a guild. - * @private + * @export * @async * @param {object} guild - The guild object. * @returns {Promise} Array of user ID strings. */ -async function getGuildLinkedUsers(guild) { +export async function getGuildLinkedUsers(guild) { const memberIds = []; try { const members = guild?.members; @@ -127,7 +127,7 @@ export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targ const lines = listeners.map((l, i) => { const medal = i < 3 ? MEDALS[i] : ` `; - return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`; + return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`; }); const desc = lines.join("\n").slice(0, 4096); @@ -197,7 +197,7 @@ export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targ const commonStr = comparison.commonArtists.slice(0, 15).map((a, i) => { const num = String(i + 1).padStart(2, " "); const link = a.url ? `[${a.name}](${a.url})` : a.name; - return `\`${num}.\` ${link} (**${a.playcount}** plays)`; + return `\`${num}.\` ${link} (**${a.playcount}** ${this.t(msg, "responses.lastfm.plays")})`; }).join("\n"); embed.addFields({ name: `Common Artists (${comparison.commonArtists.length})`, value: commonStr.slice(0, 1024), inline: false }); } @@ -332,7 +332,7 @@ export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targ const lines = filteredCrowns.slice(0, 20).map(c => { const link = c.artistUrl ? `[${c.artist}](${c.artistUrl})` : c.artist; const nextStr = c.nextBest ? ` (next: **${c.nextBest.username}** with ${Utils.formatNumber(c.nextBest.playcount)})` : ""; - return `👑 ${link} — **${Utils.formatNumber(c.userPlaycount)}** plays${nextStr}`; + return `👑 ${link} — **${Utils.formatNumber(c.userPlaycount)}** ${this.t(msg, "responses.lastfm.plays")}${nextStr}`; }); const desc = lines.join("\n").slice(0, 4096); @@ -423,7 +423,7 @@ export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targ const lines = listeners.map((l, i) => { const medal = i < 3 ? MEDALS[i] : ` `; - return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`; + return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`; }); const desc = lines.join("\n").slice(0, 4096); @@ -504,7 +504,7 @@ export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targ const lines = listeners.map((l, i) => { const medal = i < 3 ? MEDALS[i] : ` `; - return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`; + return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`; }); const desc = lines.join("\n").slice(0, 4096); diff --git a/src/music/PlayerLifecycleMixin.mjs b/src/music/PlayerLifecycleMixin.mjs index 971a51d..b3a7b69 100644 --- a/src/music/PlayerLifecycleMixin.mjs +++ b/src/music/PlayerLifecycleMixin.mjs @@ -145,6 +145,14 @@ const PlayerLifecycleMixin = { const guildId = getMessageGuildId(msg); const cleanGuildId = cleanId(guildId); + + /* DMs have no voice channels — prompting for a channel selection would + be pointless (and hang until timeout). Tell the user directly. */ + if (!cleanGuildId) { + await msg.reply(this._t(msg, "responses._common.serverOnlyForMusic")).catch(() => {}); + return false; + } + const allChannels = cleanGuildId ? [...(this.commands.client?.channels?.values?.() ?? [])] .filter(c => { diff --git a/src/services/lastfm/ServerStatsMixin.mjs b/src/services/lastfm/ServerStatsMixin.mjs index d6788f2..705a293 100644 --- a/src/services/lastfm/ServerStatsMixin.mjs +++ b/src/services/lastfm/ServerStatsMixin.mjs @@ -321,6 +321,15 @@ const ServerStatsMixin = { async getLeaderboard(page = 0, perPage = 10) { if (!this.enabled) return { entries: [], totalUsers: 0, page: 0, perPage: 10, totalPages: 0 }; + /* Sync scrobble counts from Last.fm before ranking. The local counter + only advances on bot-made scrobbles, so listening done outside the + bot (phone/desktop clients) would never show up. getTotalScrobbles() + syncs every linked user, is deduped while in-flight, cached for 10 + minutes, and resolves (never throws) even if the API is down. */ + try { + await this.getTotalScrobbles(); + } catch (_) { /* stale counts are better than no leaderboard */ } + const pool = await this._getPool(); const f = this._botIdFilter(); @@ -348,6 +357,75 @@ const ServerStatsMixin = { return { entries, totalUsers, page, perPage, totalPages }; }, + /** + * Get the scrobble leaderboard scoped to a set of platform user IDs + * (typically the members of one guild), with pagination. Refreshes only + * these users' counts from Last.fm first (5-minute TTL, deduped while + * in-flight) so pagination turns don't hammer the API. + * @async + * @param {Array} userIds - Platform user IDs to include. + * @param {number} [page=0] - Zero-based page index. + * @param {number} [perPage=10] - Number of entries per page. + * @returns {Promise<{entries: Array<{userId: string, username: string, scrobbleCount: number}>, totalUsers: number, page: number, perPage: number, totalPages: number, scope: string}>} Leaderboard data. + */ + async getServerLeaderboard(userIds, page = 0, perPage = 10) { + const empty = { entries: [], totalUsers: 0, page: 0, perPage, totalPages: 0, scope: "server" }; + if (!this.enabled) return empty; + + const ids = [...new Set((Array.isArray(userIds) ? userIds : []) + .map(id => String(id)) + .filter(id => /^\d{5,25}$/.test(id)))]; + if (!ids.length) return empty; + + /* Refresh just these users' counts from Last.fm before ranking. + The local counter only advances on bot-made scrobbles, so listening + done outside the bot would never show up. TTL-gated + deduped. */ + try { + if (!this._lbServerSyncAt || Date.now() - this._lbServerSyncAt > 5 * 60 * 1000) { + if (!this._lbServerSyncInflight) { + this._lbServerSyncInflight = (async () => { + const concurrency = 3; + for (let i = 0; i < ids.length; i += concurrency) { + await Promise.allSettled( + ids.slice(i, i + concurrency).map(uid => this.syncUserScrobbleCount(uid)) + ); + } + this._lbServerSyncAt = Date.now(); + })().finally(() => { this._lbServerSyncInflight = null; }); + } + await this._lbServerSyncInflight; + } + } catch (_) { /* stale counts are better than no leaderboard */ } + + const pool = await this._getPool(); + const f = this._botIdFilter(); + const placeholders = ids.map(() => "?").join(","); + const scopeSql = ` AND user_id IN (${placeholders})`; + + const [countRows] = await pool.execute( + `SELECT COUNT(*) AS total FROM lastfm_users WHERE scrobble_count > 0${scopeSql}${f.where}`, + [...ids, ...f.params] + ); + const totalUsers = Number(countRows[0]?.total ?? 0); + const totalPages = Math.max(1, Math.ceil(totalUsers / perPage)); + + page = Math.max(0, Math.min(page, totalPages - 1)); + const offset = page * perPage; + + const [rows] = await pool.execute( + `SELECT user_id, username, scrobble_count FROM lastfm_users WHERE scrobble_count > 0${scopeSql}${f.where} ORDER BY scrobble_count DESC LIMIT ? OFFSET ?`, + [...ids, ...f.params, String(perPage), String(offset)] + ); + + const entries = rows.map(r => ({ + userId: r.user_id, + username: r.username || r.user_id, + scrobbleCount: Number(r.scrobble_count), + })); + + return { entries, totalUsers, page, perPage, totalPages, scope: "server" }; + }, + /** * Compute affinity (common artists) between multiple users. * @async diff --git a/src/ui/MessageHandler.mjs b/src/ui/MessageHandler.mjs index f278dde..c16cd0f 100644 --- a/src/ui/MessageHandler.mjs +++ b/src/ui/MessageHandler.mjs @@ -179,6 +179,8 @@ export class MessageHandler { * @returns {Promise} */ async assertPermissions(permissions, message) { + if (!message.guildId && !message.guild?.id) return true; + const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId); if (guild && !guild.members?.me) { try { await guild.members.fetchMe(); } catch (e) { logger.warn("[MessageHandler] fetchMe failed:", e?.message); } diff --git a/storage/locales/bot/ar-SA.json b/storage/locales/bot/ar-SA.json index ce4cbbe..d7ce6d5 100644 --- a/storage/locales/bot/ar-SA.json +++ b/storage/locales/bot/ar-SA.json @@ -690,6 +690,13 @@ "whoknowsAlbumTitle": "👤 من يعرف {{album}}؟", "leaderboardEmpty": "🎵 لا توجد سكرابلات مسجلة بعد. اربط حساب Last.fm الخاص بك باستخدام `{{prefix}}lastfm link` وابدأ الاستماع!", "leaderboardControlsExpired": "⌛ انتهت صلاحية عناصر التحكم", + "leaderboardTitleServer": "🎵 لوحة متصدري السكرابل للسيرفر", + "leaderboardTitleGlobal": "🎵 لوحة متصدري السكرابل (عالمية)", + "leaderboardScrobbles": "سكرابل", + "leaderboardYou": "← أنت", + "leaderboardFooterSync": "💡 تتم مزامنة الأعداد مباشرة من Last.fm (ذاكرة مؤقتة ~10 دقائق) · `{{prefix}}lastfm profile` لمزامنة أعدادك يدويًا", + "trackListFooter": "💡 استخدم `{{prefix}}lastfm play loved` لتشغيل هذه المسارات!", + "plays": "تشغيل", "leaderboardPageFooter": "صفحة {{current}}/{{total}} • استخدم ◀️▶️ للتنقل", "artistsFooter": "💡 استخدم `{{prefix}}lastfm play top` لتشغيل أكثر مساراتك استماعاً!", "noArtistSpecified": "❌ لم يتم تحديد فنان. شغّل أغنية أو حدد اسم فنان.", @@ -726,7 +733,8 @@ "crownsTitle": "👑 ألقاب الفنانين — {{username}}", "crownsFooter": "يمتلك {{count}} تاجاً", "noArtistTags": "🏷️ لا توجد وسوم للفنان **{{artist}}**.", - "artistTagsTitle": "🏷️ وسوم أعلى لـ {{artist}}" + "artistTagsTitle": "🏷️ وسوم أعلى لـ {{artist}}", + "listeners": "مستمع" }, "messages": { "missingCriticalPermsTitle": "صلاحيات مفقودة — البوت لا يستطيع العمل بشكل صحيح", diff --git a/storage/locales/bot/ckb.json b/storage/locales/bot/ckb.json index 6844510..ec16d7f 100644 --- a/storage/locales/bot/ckb.json +++ b/storage/locales/bot/ckb.json @@ -690,6 +690,13 @@ "whoknowsAlbumTitle": "👤 کێ دەزانێت {{album}}؟", "leaderboardEmpty": "🎵 هێشتا هیچ scrobble تۆمار نەکراوە. هەژماری Last.fm خۆت بە `{{prefix}}lastfm link` ببەستە و گوێگرتن دەستپێبکە!", "leaderboardControlsExpired": "⌛ کۆنتڕۆڵەکان بەسەرچوون", + "leaderboardTitleServer": "🎵 خشتەی سکرۆبڵی سێرڤەر", + "leaderboardTitleGlobal": "🎵 خشتەی سکرۆبڵ (گشتی)", + "leaderboardScrobbles": "scrobble", + "leaderboardYou": "← تۆ", + "leaderboardFooterSync": "💡 ژمارەکان ڕاستەوخۆ لە Last.fm ەوە هاوکات دەکرێن (کاش ~10 خولەک) · بۆ نوێکردنەوەی ژمارەکانت `{{prefix}}lastfm profile`", + "trackListFooter": "💡 بۆ لێدانی ئەم تراکانە `{{prefix}}lastfm play loved` بەکاربهێنە!", + "plays": "جار لێدراوە", "leaderboardPageFooter": "لاپەڕە {{current}}/{{total}} • بۆ ناوبردن ◀️▶️ بەکاربهێنە", "artistsFooter": "💡 بۆ لێدانی زۆرترین گوێگرتنی تراکەکانت `{{prefix}}lastfm play top` بەکاربهێنە!", "noArtistSpecified": "❌ هونەرمەند دیاری نەکراوە. گۆرانییەک لێبدە یان ناوی هونەرمەند بدە.", @@ -726,7 +733,8 @@ "crownsTitle": "👑 تاجەکانی هونەرمەند — {{username}}", "crownsFooter": "{{count}} تاج هەڵگیراوە", "noArtistTags": "🏷️ هیچ تاگێک بۆ هونەرمەندی **{{artist}}** نەدۆزرایەوە.", - "artistTagsTitle": "🏷️ تاگە سەرەکییەکان بۆ {{artist}}" + "artistTagsTitle": "🏷️ تاگە سەرەکییەکان بۆ {{artist}}", + "listeners": "گوێگر" }, "messages": { "missingCriticalPermsTitle": "مۆڵەتە کەمەکان — بۆت ناتوانێت بە دروستی کار بکات", diff --git a/storage/locales/bot/de-DE.json b/storage/locales/bot/de-DE.json index 4225659..1a05f59 100644 --- a/storage/locales/bot/de-DE.json +++ b/storage/locales/bot/de-DE.json @@ -690,6 +690,13 @@ "whoknowsAlbumTitle": "👤 Wer kennt {{album}}?", "leaderboardEmpty": "🎵 Noch keine Scrobbles aufgezeichnet. Verknüpfe dein Last.fm-Konto mit `{{prefix}}lastfm link` und leg los!", "leaderboardControlsExpired": "⌛ Steuerung abgelaufen", + "leaderboardTitleServer": "🎵 Server-Scrobble-Bestenliste", + "leaderboardTitleGlobal": "🎵 Scrobble-Bestenliste (global)", + "leaderboardScrobbles": "Scrobbles", + "leaderboardYou": "← du", + "leaderboardFooterSync": "💡 Zahlen werden live von Last.fm synchronisiert (Cache ~10 Min.) · `{{prefix}}lastfm profile` zum Aktualisieren deiner Zahlen", + "trackListFooter": "💡 Nutze `{{prefix}}lastfm play loved`, um diese Titel zu spielen!", + "plays": "Wiedergaben", "leaderboardPageFooter": "Seite {{current}}/{{total}} • Nutze ◀️▶️ zum Navigieren", "artistsFooter": "💡 Nutze `{{prefix}}lastfm play top`, um deine Top-Titel zu spielen!", "noArtistSpecified": "❌ Kein Künstler angegeben. Spiele einen Song oder gib einen Künstlernamen an.", @@ -726,7 +733,8 @@ "crownsTitle": "👑 Künstler-Kronen — {{username}}", "crownsFooter": "{{count}} Krone(n) im Besitz", "noArtistTags": "🏷️ Keine Tags für Künstler **{{artist}}** gefunden.", - "artistTagsTitle": "🏷️ Top-Tags für {{artist}}" + "artistTagsTitle": "🏷️ Top-Tags für {{artist}}", + "listeners": "Hörer" }, "messages": { "missingCriticalPermsTitle": "Fehlende Berechtigungen — Bot kann nicht ordnungsgemäß arbeiten", diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index d53da90..23a6e35 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -199,6 +199,7 @@ "responses": { "_common": { "nothingPlaying": "❌ There's nothing playing at the moment!", + "serverOnlyForMusic": "🎵 Music needs a **voice channel in a server** — I can't join voice in DMs. Run the command in a server instead!", "noVoiceChannel": "⚠️ I can't find you in a voice channel. Please join one first, or if you're already in one, make sure I have **View Channel** and **Connect** permissions.", "noVoiceStrict": "⚠️ I can't find you in a voice channel. Please join one, or if you're already in one, make sure I have **View Channel** and **Connect** permissions.", "alreadyInChannel": "⚠️ I'm already playing in {{channels}}. Join that channel or use `{{prefix}}play` to start music in your channel.", @@ -357,6 +358,13 @@ "whoknowsFooter": "{{count}} listener{{plural}} · {{totalPlays}} total plays", "leaderboardEmpty": "🎵 No scrobbles recorded yet. Link your Last.fm account with `{{prefix}}lastfm link` and start listening!", "leaderboardControlsExpired": "Controls expired", + "leaderboardTitleServer": "🎵 Server Scrobble Leaderboard", + "leaderboardTitleGlobal": "🎵 Scrobble Leaderboard (global)", + "leaderboardScrobbles": "scrobbles", + "leaderboardYou": "← you", + "leaderboardFooterSync": "💡 Counts synced live from Last.fm (cached ~10 min) · `{{prefix}}lastfm profile` to force-sync yours", + "trackListFooter": "💡 Use `{{prefix}}lastfm play loved` to play these!", + "plays": "plays", "leaderboardPageFooter": "Page {{current}}/{{total}} • Use ◀️▶️ to navigate", "artistsFooter": "💡 Use {{prefix}}lastfm play top to play your top tracks!", "noArtistSpecified": "❌ No artist specified. Play a song or provide an artist name via the token option.", @@ -400,7 +408,8 @@ "whoknowsAlbumNobody": "👤 Nobody in this server has listened to **{{album}}** on Last.fm.", "whoknowsAlbumTitle": "👤 Who knows {{album}}?", "noArtistTags": "🏷️ No tags found for artist **{{artist}}**.", - "artistTagsTitle": "🏷️ Top Tags for {{artist}}" + "artistTagsTitle": "🏷️ Top Tags for {{artist}}", + "listeners": "listeners" }, "list": { "empty": "📭 The queue is empty. Use `{{prefix}}play` to add songs!", diff --git a/storage/locales/bot/pt-BR.json b/storage/locales/bot/pt-BR.json index 825203b..27d3495 100644 --- a/storage/locales/bot/pt-BR.json +++ b/storage/locales/bot/pt-BR.json @@ -690,6 +690,13 @@ "whoknowsAlbumTitle": "👤 Quem conhece {{album}}?", "leaderboardEmpty": "🎵 Nenhum scrobble registrado ainda. Vincule sua conta do Last.fm com `{{prefix}}lastfm link` e comece a ouvir!", "leaderboardControlsExpired": "⌛ Controles expirados", + "leaderboardTitleServer": "🎵 Ranking de Scrobbles do Servidor", + "leaderboardTitleGlobal": "🎵 Ranking de Scrobbles (global)", + "leaderboardScrobbles": "scrobbles", + "leaderboardYou": "← você", + "leaderboardFooterSync": "💡 Contagens sincronizadas ao vivo do Last.fm (cache de ~10 min) · `{{prefix}}lastfm profile` para sincronizar as suas", + "trackListFooter": "💡 Use `{{prefix}}lastfm play loved` para tocar estas faixas!", + "plays": "reproduções", "leaderboardPageFooter": "Página {{current}}/{{total}} • Use ◀️▶️ para navegar", "artistsFooter": "💡 Use `{{prefix}}lastfm play top` para tocar suas faixas mais ouvidas!", "noArtistSpecified": "❌ Nenhum artista especificado. Toque uma música ou forneça um nome de artista.", @@ -726,7 +733,8 @@ "crownsTitle": "👑 Coroas de Artista — {{username}}", "crownsFooter": "{{count}} coroa{{plural}} mantida{{plural}}", "noArtistTags": "🏷️ Nenhuma tag encontrada para o artista **{{artist}}**.", - "artistTagsTitle": "🏷️ Tags Populares para {{artist}}" + "artistTagsTitle": "🏷️ Tags Populares para {{artist}}", + "listeners": "ouvintes" }, "messages": { "missingCriticalPermsTitle": "Permissões Ausentes — Bot Não Pode Funcionar Corretamente", diff --git a/storage/locales/bot/tr.json b/storage/locales/bot/tr.json index 689eb4c..7eb3ebe 100644 --- a/storage/locales/bot/tr.json +++ b/storage/locales/bot/tr.json @@ -361,6 +361,13 @@ "whoknowsAlbumTitle": "👤 Kim bilir {{album}}?", "leaderboardEmpty": "🎵 Henüz scrobble kaydedilmedi. Last.fm hesabınızı `{{prefix}}lastfm link` ile bağlayın ve dinlemeye başlayın!", "leaderboardControlsExpired": "⌛ Kontrollerin süresi doldu", + "leaderboardTitleServer": "🎵 Sunucu Scrobble Sıralaması", + "leaderboardTitleGlobal": "🎵 Scrobble Sıralaması (genel)", + "leaderboardScrobbles": "scrobble", + "leaderboardYou": "← sen", + "leaderboardFooterSync": "💡 Sayılar Last.fm'den canlı senkronize edilir (~10 dk önbellek) · Kendi saylarını güncellemek için `{{prefix}}lastfm profile`", + "trackListFooter": "💡 Bunları çalmak için `{{prefix}}lastfm play loved` kullan!", + "plays": "çalma", "leaderboardPageFooter": "Sayfa {{current}}/{{total}} • Gezinmek için ◀️▶️ kullanın", "artistsFooter": "💡 En çok dinlediğin parçaları çalmak için `{{prefix}}lastfm play top` kullan!", "noArtistSpecified": "❌ Sanatçı belirtilmedi. Bir şarkı çalın veya sanatçı adı girin.", @@ -397,7 +404,8 @@ "crownsTitle": "👑 Sanatçı Taçları — {{username}}", "crownsFooter": "{{count}} taç elde tutuluyor", "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" }, "list": { "empty": "📭 Kuyruk boş. Şarkı eklemek için `{{prefix}}play` kullanın!",