mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
feat: add scrobble leaderboard and global Last.fm stats
- Add %lastfm leaderboard (alias: lb) command with paginated embed showing top users ranked by scrobble count with 🥇🥈🥉 medals; emoji reactions ◀️▶️❌ for navigation, auto-expires after timeout - Add getLeaderboard() to LastFmManager: paginated query on scrobble_count DESC from lastfm_users, returns entries/totalPages - Add syncUserScrobbleCount(): syncs local counter from Last.fm user.getinfo playcount; called on every %lastfm profile view - Add _incrementScrobbleCount(): fire-and-forget increment of both per-user scrobble_count and global stored_scrobbles after each successful scrobble - Add scrobble_count BIGINT column to lastfm_users with auto-migrate ALTER TABLE for existing installs (error silently ignored if column already exists) - Add lastfm_stats table (single-row) tracking stored_scrobbles and linked_users globally; row is seeded with INSERT IGNORE on init - Add getStoredScrobbles() and getLinkedUsersCount() with lazy in-memory caching for the stats row - Add linked_users increment on first-time account link - Show scrobble count and linked users in %stats embed when Last.fm is enabled (fetched in parallel, non-blocking on initial reply) - Add locale keys responses.stats.scrobbles and responses.stats.linkedUsers to en, ar-SA, ckb, de-DE, pt-BR
This commit is contained in:
1 parent
3e84002b79
commit
e11c29ed25
3 files changed
+209
-10
No files matched your search
@@ -123,7 +123,7 @@ Below is the complete list of Remix's commands. The default prefix is `%`.
|
||||
| `stats` | Display bot stats (uptime, ping, player count, stored scrobbles) | `%stats` | `info` |
|
||||
| `invite` | Get the bot invite link | `%invite` | `addbot`, `remix` |
|
||||
| `support` | Get an invite to the support server | `%support` | `server` |
|
||||
| `lastfm` | Link Last.fm, toggle scrobbling, view profile, play tracks | `%lastfm link` / `%lastfm play loved` | `lf`, `lfm` |
|
||||
| `lastfm` | Link Last.fm, toggle scrobbling, view profile, play tracks, leaderboard | `%lastfm link` / `%lastfm play loved` / `%lastfm lb` | `lf`, `lfm` |
|
||||
| `reload` | Reload commands or modules at runtime (owner) | `%reload` | |
|
||||
| `servers` | List servers the bot is in (owner) | `%servers` | |
|
||||
| `eval` | Evaluate JavaScript (owner only) | `%eval 1+1` | |
|
||||
|
||||
+127
-2
@@ -12,8 +12,8 @@ export const command = new CommandBuilder()
|
||||
.addAliases("lf", "lfm")
|
||||
.addChoiceOption(o =>
|
||||
o.setName("action")
|
||||
.setDescription("The action to perform: link, unlink, np, profile, loved, top, recent, playlists, play, scrobble", "options.lastfm.action")
|
||||
.addChoices("link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", "playlists", "play", "scrobble")
|
||||
.setDescription("The action to perform: link, unlink, np, profile, loved, top, recent, playlists, play, scrobble, leaderboard", "options.lastfm.action")
|
||||
.addChoices("link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", "playlists", "play", "scrobble", "leaderboard", "lb")
|
||||
.setRequired(false)
|
||||
)
|
||||
.addTextOption(o =>
|
||||
@@ -401,6 +401,9 @@ export async function run(msg, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// Sync scrobble count in background (keeps leaderboard fresh)
|
||||
lastfm.syncUserScrobbleCount(userId).catch(() => {});
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setAuthor({ name: `Last.fm Profile: ${info.name}`, icon_url: info.image?.[2]?.["#text"] || undefined, url: info.url })
|
||||
@@ -527,6 +530,104 @@ export async function run(msg, data) {
|
||||
return msg.reply({ embeds: [buildTrackList(user.username, "📊 Top Tracks", tracks, true)] });
|
||||
}
|
||||
|
||||
// ── Leaderboard ─────────────────────────────────────────────────────
|
||||
case "leaderboard":
|
||||
case "lb": {
|
||||
let lb;
|
||||
try {
|
||||
lb = await lastfm.getLeaderboard(0, 10);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to fetch leaderboard: ${err.message}`)]
|
||||
});
|
||||
}
|
||||
|
||||
if (!lb.entries.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||
`🎵 No scrobbles recorded yet. Link your Last.fm account with \`${prefix}lastfm link\` and start listening!`
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
// Single page — no pagination needed
|
||||
if (lb.totalPages <= 1) {
|
||||
const embed = buildLeaderboardEmbed(lb, 0, prefix);
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
// Multi-page with emoji navigation
|
||||
let currentPage = 0;
|
||||
|
||||
const buildPage = (pageIdx, expired = false) => {
|
||||
// Fetch for this page index (we pre-load only page 0;
|
||||
// subsequent pages are fetched on navigation)
|
||||
const footerText = expired
|
||||
? "Controls expired"
|
||||
: `Page ${pageIdx + 1}/${lb.totalPages} • Use ◀️▶️ to navigate`;
|
||||
const embed = buildLeaderboardEmbed(lb, pageIdx, prefix);
|
||||
embed.setFooter({ text: footerText });
|
||||
return { embeds: [embed] };
|
||||
};
|
||||
|
||||
const replyMsg = await msg.reply(buildPage(0));
|
||||
if (!replyMsg?.message) return;
|
||||
|
||||
const navEmojis = ["◀️", "▶️", "❌"];
|
||||
for (const emoji of navEmojis) {
|
||||
await replyMsg.message.react(emoji).catch(() => {});
|
||||
}
|
||||
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await replyMsg.message.removeAllReactions();
|
||||
} catch {
|
||||
for (const emoji of navEmojis) {
|
||||
try { await replyMsg.message.removeReaction(emoji); } catch {}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let emojiTimeout;
|
||||
const resetTimer = () => {
|
||||
clearTimeout(emojiTimeout);
|
||||
emojiTimeout = setTimeout(async () => {
|
||||
unobserve?.();
|
||||
await clearReactions();
|
||||
await replyMsg.edit(buildPage(currentPage, true)).catch(() => {});
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
const unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
||||
if (e.emoji_id === "❌") {
|
||||
clearTimeout(emojiTimeout);
|
||||
unobserve?.();
|
||||
await replyMsg.message.delete().catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
resetTimer();
|
||||
|
||||
if (e.emoji_id === "◀️") {
|
||||
currentPage = currentPage > 0 ? currentPage - 1 : lb.totalPages - 1;
|
||||
} else if (e.emoji_id === "▶️") {
|
||||
currentPage = currentPage < lb.totalPages - 1 ? currentPage + 1 : 0;
|
||||
}
|
||||
|
||||
// Fetch the page data from DB
|
||||
try {
|
||||
lb = await lastfm.getLeaderboard(currentPage, 10);
|
||||
} catch {
|
||||
/* keep previous data */
|
||||
}
|
||||
|
||||
await replyMsg.edit(buildPage(currentPage)).catch(() => {});
|
||||
});
|
||||
|
||||
resetTimer();
|
||||
break;
|
||||
}
|
||||
|
||||
// ── Recent tracks ──────────────────────────────────────────────────────
|
||||
case "recent": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
@@ -566,6 +667,7 @@ export async function run(msg, data) {
|
||||
`\`${prefix}lastfm top\` — View your top tracks`,
|
||||
`\`${prefix}lastfm recent\` — View your recent tracks`,
|
||||
`\`${prefix}lastfm playlists\` — View your Last.fm playlists`,
|
||||
`\`${prefix}lastfm leaderboard\` — Scrobble leaderboard`,
|
||||
``,
|
||||
`🎶 **Play from Last.fm:**`,
|
||||
`\`${prefix}lastfm play loved\` — Play your loved tracks`,
|
||||
@@ -600,3 +702,26 @@ function buildTrackList(username, title, tracks, showPlaycount = false) {
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: `💡 Use %lastfm play loved to play these!` });
|
||||
}
|
||||
|
||||
// ── Leaderboard embed builder ─────────────────────────────────────────────────
|
||||
|
||||
function buildLeaderboardEmbed(lb, pageIdx, prefix) {
|
||||
const MEDALS = ["🥇", "🥈", "🥉"];
|
||||
const startRank = pageIdx * lb.perPage;
|
||||
|
||||
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 count = Utils.formatNumber(entry.scrobbleCount);
|
||||
return `${medal} ${rank}. **${name}** — ${count} scrobbles`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle("🎵 Scrobble Leaderboard")
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: `💡 View & sync your count: ${prefix}lastfm profile` });
|
||||
}
|
||||
+81
-7
@@ -119,14 +119,22 @@ export class LastFmManager {
|
||||
const pool = this._pool;
|
||||
await pool.execute(`
|
||||
CREATE TABLE IF NOT EXISTS \`lastfm_users\` (
|
||||
\`user_id\` VARCHAR(30) NOT NULL PRIMARY KEY,
|
||||
\`session_key\` VARCHAR(64) NOT NULL,
|
||||
\`username\` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
\`scrobble\` TINYINT(1) NOT NULL DEFAULT 1,
|
||||
\`linked_at\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
\`user_id\` VARCHAR(30) NOT NULL PRIMARY KEY,
|
||||
\`session_key\` VARCHAR(64) NOT NULL,
|
||||
\`username\` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
\`scrobble\` TINYINT(1) NOT NULL DEFAULT 1,
|
||||
\`scrobble_count\` BIGINT NOT NULL DEFAULT 0,
|
||||
\`linked_at\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
`);
|
||||
|
||||
// Auto-migrate: add scrobble_count column if it doesn't exist (existing tables)
|
||||
try {
|
||||
await pool.execute("ALTER TABLE \`lastfm_users\` ADD COLUMN \`scrobble_count\` BIGINT NOT NULL DEFAULT 0 AFTER \`scrobble\`");
|
||||
} catch {
|
||||
// Column already exists — ignore
|
||||
}
|
||||
|
||||
// Stats table — single row tracking global scrobble counts
|
||||
await pool.execute(`
|
||||
CREATE TABLE IF NOT EXISTS \`lastfm_stats\` (
|
||||
@@ -298,7 +306,7 @@ export class LastFmManager {
|
||||
logger.settings(`[LastFm] Scrobbled "${track.title}" for ${userId}`);
|
||||
|
||||
// Increment stored scrobbles counter (non-blocking)
|
||||
this._incrementScrobbleCount();
|
||||
this._incrementScrobbleCount(userId);
|
||||
} catch (err) {
|
||||
logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`);
|
||||
}
|
||||
@@ -743,6 +751,65 @@ export class LastFmManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the scrobble leaderboard — top users by scrobble_count.
|
||||
* @param {number} [page=0] - 0-based page index
|
||||
* @param {number} [perPage=10] - Users per page
|
||||
* @returns {Promise<{ entries: Array<{ userId, username, scrobbleCount }>, totalUsers: number, page, perPage, totalPages: number }>}
|
||||
*/
|
||||
async getLeaderboard(page = 0, perPage = 10) {
|
||||
if (!this.enabled) return { entries: [], totalUsers: 0, page: 0, perPage: 10, totalPages: 0 };
|
||||
|
||||
const pool = await this._getPool();
|
||||
|
||||
// Get total count
|
||||
const [countRows] = await pool.execute(
|
||||
"SELECT COUNT(*) AS total FROM lastfm_users WHERE scrobble_count > 0"
|
||||
);
|
||||
const totalUsers = Number(countRows[0]?.total ?? 0);
|
||||
const totalPages = Math.max(1, Math.ceil(totalUsers / perPage));
|
||||
|
||||
// Clamp page
|
||||
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 ORDER BY scrobble_count DESC LIMIT ? OFFSET ?",
|
||||
[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 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a user's scrobble_count from their Last.fm profile (user.getinfo).
|
||||
* This syncs the local counter with Last.fm's actual count.
|
||||
* Called lazily when the leaderboard is viewed or the user checks their profile.
|
||||
* @param {string} userId
|
||||
* @returns {Promise<number>} The updated scrobble count
|
||||
*/
|
||||
async syncUserScrobbleCount(userId) {
|
||||
if (!this.enabled) return 0;
|
||||
try {
|
||||
const info = await this.getUserInfo(userId);
|
||||
const playcount = Number(info.playcount ?? 0);
|
||||
const pool = await this._getPool();
|
||||
await pool.execute(
|
||||
"UPDATE lastfm_users SET scrobble_count = ? WHERE user_id = ?",
|
||||
[String(playcount), String(userId)]
|
||||
);
|
||||
return playcount;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Internal helpers ───────────────────────────────────────────────────────
|
||||
|
||||
_assertEnabled() {
|
||||
@@ -751,15 +818,22 @@ export class LastFmManager {
|
||||
|
||||
/**
|
||||
* Increment the stored scrobbles counter (in-memory + MySQL).
|
||||
* Also increments per-user scrobble_count.
|
||||
* Called after a successful scrobble. Non-blocking — fire-and-forget.
|
||||
*/
|
||||
_incrementScrobbleCount() {
|
||||
_incrementScrobbleCount(userId) {
|
||||
this._storedScrobbles++;
|
||||
// Persist to MySQL in the background (don't await)
|
||||
this._getPool().then(pool => {
|
||||
pool.execute(
|
||||
"UPDATE lastfm_stats SET stored_scrobbles = stored_scrobbles + 1 WHERE id = 1"
|
||||
).catch(() => {});
|
||||
if (userId) {
|
||||
pool.execute(
|
||||
"UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?",
|
||||
[String(userId)]
|
||||
).catch(() => {});
|
||||
}
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user