feat: add Last.fm integration with auto-scrobbling

- Add LastFmManager with full Last.fm API auth flow (get token →
  user authorises → get session key stored in MySQL)
- Add %lastfm command (aliases: lf, lfm) with subcommands:
  link, confirm, unlink, np, profile, loved, top, recent, scrobble
- Auto-scrobble in PlayerManager: sends now-playing notification to
  all human voice-channel members on track start, then defers a
  scrobble after the configured threshold (default 50% of duration
  or 4 min, whichever comes first)
- Add lastfm config block to config_example.json (apiKey,
  apiSecret, scrobbleThreshold, scrobbleMinMs)
- Add all Last.fm locale strings to storage/locales/bot/en.json

fix: show channel as Discord mention in inactivity leave message

- RecoveryManager: changed plain activeChannelId to
  <#activeChannelId> so it renders as a clickable channel link
This commit is contained in:
NoLogicAlan committed 2026-05-09 23:47:50 +03:00
1 parent 09fa5d160c
commit 8ac0dde343
8 files changed
+960 -3

No files matched your search

+7 -2
View File
@@ -49,7 +49,7 @@
## About The Project ## About The Project
Remix is a free and open-source music bot for [Fluxer](https://fluxer.app), built with [`@fluxerjs/core`](https://github.com/fluxerjs/core) and powered by [`moonlink.js`](https://github.com/ShadowLp174/moonlink.js) for seamless, high-quality audio streaming. It uses [`revoice.js`](https://github.com/ShadowLp174/revoice.js) for LiveKit voice connections and audio playback, and [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) for native voice channel integration alongside the Moonlink Lavalink proxy. Remix is a free and open-source music bot for [Fluxer](https://fluxer.app), built with [`@fluxerjs/core`](https://github.com/fluxerjs/core) and powered by [`moonlink.js`](https://github.com/ShadowLp174/moonlink.js) for seamless, high-quality audio streaming. It uses [`revoice.js`](https://www.npmjs.com/package/revoice.js) for LiveKit voice connections and audio playback, and [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) for native voice channel integration alongside the Moonlink Lavalink proxy.
We believe music features shouldn't be locked behind paywalls — **all commands on Remix are 100% free and always will be.** We believe music features shouldn't be locked behind paywalls — **all commands on Remix are 100% free and always will be.**
@@ -64,6 +64,7 @@ We believe music features shouldn't be locked behind paywalls — **all commands
- **Interactive emoji player** — reaction-based control panel with play, pause, skip, volume, shuffle, and more - **Interactive emoji player** — reaction-based control panel with play, pause, skip, volume, shuffle, and more
- **Lyrics** — fetch synced lyrics via NodeLink - **Lyrics** — fetch synced lyrics via NodeLink
- **Radio stations** — built-in support for custom radio streams with keyword-based search - **Radio stations** — built-in support for custom radio streams with keyword-based search
- **Last.fm integration** — auto-scrobble songs, play loved/top/recent tracks, and view your Last.fm profile
- **Server settings** — per-guild configuration for prefix, volume, locale, 24/7 channels, and more - **Server settings** — per-guild configuration for prefix, volume, locale, 24/7 channels, and more
- **Web dashboard** — optional browser-based control panel with Redis-backed sessions and Fluxer OAuth2 login - **Web dashboard** — optional browser-based control panel with Redis-backed sessions and Fluxer OAuth2 login
- **Multi-language support** — available in English, Arabic, German, Kurdish (Sorani), and Brazilian Portuguese - **Multi-language support** — available in English, Arabic, German, Kurdish (Sorani), and Brazilian Portuguese
@@ -122,6 +123,7 @@ Below is the complete list of Remix's commands. The default prefix is `%`.
| `stats` | Display bot stats (uptime, ping, player count) | `%stats` | `info` | | `stats` | Display bot stats (uptime, ping, player count) | `%stats` | `info` |
| `invite` | Get the bot invite link | `%invite` | `addbot`, `remix` | | `invite` | Get the bot invite link | `%invite` | `addbot`, `remix` |
| `support` | Get an invite to the support server | `%support` | `server` | | `support` | Get an invite to the support server | `%support` | `server` |
| `lastfm` | Link Last.fm account, toggle scrobbling, view profile | `%lastfm link` | `lf`, `lfm` |
| `reload` | Reload commands or modules at runtime (owner) | `%reload` | | | `reload` | Reload commands or modules at runtime (owner) | `%reload` | |
| `servers` | List servers the bot is in (owner) | `%servers` | | | `servers` | List servers the bot is in (owner) | `%servers` | |
| `eval` | Evaluate JavaScript (owner only) | `%eval 1+1` | | | `eval` | Evaluate JavaScript (owner only) | `%eval 1+1` | |
@@ -261,6 +263,7 @@ Key configuration options in `config.json`:
| `nodelink` | object | — | NodeLink connection (`host`, `port`, `password`, `requestTimeout`) | | `nodelink` | object | — | NodeLink connection (`host`, `port`, `password`, `requestTimeout`) |
| `spotify` | object | — | Spotify API credentials (`clientId`, `clientSecret`) | | `spotify` | object | — | Spotify API credentials (`clientId`, `clientSecret`) |
| `geniusToken` | string | — | *(Deprecated, unused)* Previously for lyrics; lyrics are now fetched via NodeLink | | `geniusToken` | string | — | *(Deprecated, unused)* Previously for lyrics; lyrics are now fetched via NodeLink |
| `lastfm` | object | — | Last.fm integration (`apiKey`, `apiSecret`, `scrobbleThreshold`, `scrobbleMinMs`) |
| `dashboard` | object | — | Dashboard config: `enabled`, `redis`, `fluxer` (OAuth2) | | `dashboard` | object | — | Dashboard config: `enabled`, `redis`, `fluxer` (OAuth2) |
| `dashboardUrl` | string | — | URL the dashboard is accessible from | | `dashboardUrl` | string | — | URL the dashboard is accessible from |
| `sessionSecret` | string | — | Secret for Express.js session middleware | | `sessionSecret` | string | — | Secret for Express.js session middleware |
@@ -292,6 +295,7 @@ fluxer/
│ ├── radio.mjs # Radio station management │ ├── radio.mjs # Radio station management
│ ├── debug.mjs # Voice connection debugger (owner only, paginated) │ ├── debug.mjs # Voice connection debugger (owner only, paginated)
│ ├── stats.mjs # Bot stats with live player count │ ├── stats.mjs # Bot stats with live player count
│ ├── lastfm.mjs # Last.fm account linking, scrobbling, and profile
│ └── ... # All other commands │ └── ... # All other commands
├── src/ ├── src/
│ ├── CommandHandler.mjs # Command loader, prefix manager, registry │ ├── CommandHandler.mjs # Command loader, prefix manager, registry
@@ -302,6 +306,7 @@ fluxer/
│ ├── Settings.mjs # RemoteSettingsManager + ServerSettings export │ ├── Settings.mjs # RemoteSettingsManager + ServerSettings export
│ ├── GatewayHandler.mjs # Raw WS events, voice-state tracking, presence rotation │ ├── GatewayHandler.mjs # Raw WS events, voice-state tracking, presence rotation
│ ├── RecoveryManager.mjs # Session persistence, crash recovery, 24/7 auto-join │ ├── RecoveryManager.mjs # Session persistence, crash recovery, 24/7 auto-join
│ ├── LastFmManager.mjs # Last.fm API client — auth, scrobbling, user data
│ ├── Utils.mjs # Shared utilities │ ├── Utils.mjs # Shared utilities
│ ├── worker.mjs # Background task worker │ ├── worker.mjs # Background task worker
│ ├── probe.mjs # FFprobe wrapper for audio stream info │ ├── probe.mjs # FFprobe wrapper for audio stream info
@@ -375,7 +380,7 @@ To add a new language, place a JSON file in `storage/locales/bot/` following the
**Powered by:** **Powered by:**
- [`@fluxerjs/core`](https://github.com/fluxerjs/core) — Fluxer API client - [`@fluxerjs/core`](https://github.com/fluxerjs/core) — Fluxer API client
- [`revoice.js`](https://github.com/ShadowLp174/revoice.js) — LiveKit voice connection and MediaPlayer - [`revoice.js`](https://www.npmjs.com/package/revoice.js) — LiveKit voice connection and MediaPlayer
- [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) — Native voice channel integration - [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) — Native voice channel integration
- [`moonlink.js`](https://github.com/ShadowLp174/moonlink.js) — Lavalink proxy - [`moonlink.js`](https://github.com/ShadowLp174/moonlink.js) — Lavalink proxy
- [`NodeLink`](https://github.com/PerformanC/NodeLink) — Audio node manager - [`NodeLink`](https://github.com/PerformanC/NodeLink) — Audio node manager
+351
View File
@@ -0,0 +1,351 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
import { Utils } from "../src/Utils.mjs";
const EMOJI_REMOVE_TIMEOUT = 60_000;
export const command = new CommandBuilder()
.setName("lastfm")
.setDescription("Link your Last.fm account, toggle scrobbling, or view your profile.", "commands.lastfm")
.setCategory("util")
.addAliases("lf", "lfm")
.addChoiceOption(o =>
o.setName("action")
.setDescription("The action to perform: link, unlink, np, profile, loved, top, recent, scrobble", "options.lastfm.action")
.addChoices("link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", "scrobble")
.setRequired(false)
)
.addTextOption(o =>
o.setName("token")
.setDescription("The auth token from Last.fm (used with 'confirm' action)")
.setRequired(false)
);
// ── Helpers ────────────────────────────────────────────────────────────────────
function notConfigured(msg) {
return {
embeds: [new EmbedBuilder()
.setColor("#ff0000")
.setDescription("❌ Last.fm integration is not configured on this bot. Ask the bot owner to add a Last.fm API key to the config.")]
};
}
function notLinked(prefix) {
return {
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(`❌ You don't have a Last.fm account linked. Use \`${prefix}lastfm link\` to get started.`)]
};
}
// ── Run ────────────────────────────────────────────────────────────────────────
export async function run(msg, data) {
const lastfm = this.lastfm;
if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(msg));
const prefix = this.handler?.getPrefix?.(msg.message?.guildId) ?? "%";
const action = data.get("action")?.value ?? "profile";
const userId = msg.message?.author?.id ?? msg.author?.id;
switch (action) {
// ── Link ────────────────────────────────────────────────────────────────
case "link": {
// Check if already linked
const existing = await lastfm.getUser(userId);
if (existing) {
return msg.reply({
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(`✅ You already have **${existing.username}** linked! Use \`${prefix}lastfm unlink\` to disconnect, or \`${prefix}lastfm scrobble\` to toggle scrobbling.`)]
});
}
// Step 1: Get auth token
let token;
try {
token = await lastfm.getAuthToken();
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to get auth token: ${err.message}`)]
});
}
const authUrl = lastfm.getAuthUrl(token);
// Send auth URL via DM so it's private
let sent = false;
try {
const dm = await msg.author.createDM();
await dm.send({
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle("🎵 Link your Last.fm account")
.setDescription([
`Click the link below to authorize Remix on Last.fm:`,
``,
`**[Authorize on Last.fm](${authUrl})**`,
``,
`After you click "Yes, allow access", come back and run:`,
`\`${prefix}lastfm confirm ${token}\``,
``,
`_This link expires in 60 minutes._`,
].join("\n"))
]
});
sent = true;
} catch {
// DM failed — send in channel with a warning
}
const replyEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(
sent
? `📧 Check your DMs for the Last.fm authorization link! After approving, run \`${prefix}lastfm confirm <token>\` here.`
: `⚠️ I couldn't DM you. [Click here to authorize on Last.fm](${authUrl}), then run \`${prefix}lastfm confirm <token>\`.`
);
return msg.reply({ embeds: [replyEmbed] });
}
// ── Confirm (completes the auth flow) ──────────────────────────────────
// This is handled as a sub-action via text matching since we can't
// predict the token as a choice. We check if action wasn't matched
// and treat it as a token confirmation.
case "confirm": {
// Get token from the option, or fall back to parsing the message
let tokenValue = data.get("token")?.value;
if (!tokenValue) {
const rawContent = msg.message?.content ?? "";
const args = rawContent.split(/\s+/);
const confirmIdx = args.indexOf("confirm");
tokenValue = confirmIdx >= 0 ? args[confirmIdx + 1] : null;
}
if (!tokenValue) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Usage: \`${prefix}lastfm confirm <token>\` — provide the token from the auth DM.`)]
});
}
let session;
try {
session = await lastfm.getSession(tokenValue);
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to get session: ${err.message}\nMake sure you approved the token on Last.fm first.`)]
});
}
await lastfm.saveUser(userId, session.key, session.name);
return msg.reply({
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(`✅ Last.fm account **[${session.name}](https://last.fm/user/${session.name})** linked! Scrobbling is enabled by default.`)]
});
}
// ── Unlink ─────────────────────────────────────────────────────────────
case "unlink": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
await lastfm.removeUser(userId);
return msg.reply({
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`✅ Last.fm account **${user.username}** has been unlinked.`)]
});
}
// ── Toggle scrobbling ──────────────────────────────────────────────────
case "scrobble": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
const newState = !user.scrobbleEnabled;
await lastfm.setScrobble(userId, newState);
return msg.reply({
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(newState
? `✅ Scrobbling **enabled** — songs you listen to will be scrobbled to **${user.username}**.`
: `⏸️ Scrobbling **disabled** — songs won't be scrobbled. Your account is still linked.`
)]
});
}
// ── Now playing info ───────────────────────────────────────────────────
case "np": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
let recentData;
try {
recentData = await lastfm.getRecentTracks(userId, 1);
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to fetch recent tracks: ${err.message}`)]
});
}
if (!recentData.length) {
return msg.reply({
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🎵 No recent tracks found for **${user.username}**.`)]
});
}
const track = recentData[0];
const statusEmoji = track.now ? "🎵 Now Playing" : "🕐 Last Played";
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setAuthor({ name: `${statusEmoji} on Last.fm`, icon_url: track.image || undefined })
.setDescription(`**${track.name}** by **${track.artist}**\n[Open on Last.fm](${track.url})`)
.setFooter({ text: `Last.fm: ${user.username}` });
return msg.reply({ embeds: [embed] });
}
// ── Profile ────────────────────────────────────────────────────────────
case "profile": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
let info;
try {
info = await lastfm.getUserInfo(userId);
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to fetch profile: ${err.message}`)]
});
}
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setAuthor({ name: `Last.fm Profile: ${info.name}`, icon_url: info.image?.[2]?.["#text"] || undefined, url: info.url })
.setDescription([
`🎵 **${Utils.formatNumber(info.playcount ?? 0)}** scrobbles`,
`👤 Registered: ${info.registered?.unixtime ? new Date(+info.registered.unixtime * 1000).toLocaleDateString() : "unknown"}`,
`🔄 Scrobbling: ${user.scrobbleEnabled ? "✅ Enabled" : "⏸️ Disabled"}`,
``,
`🔗 [Open profile](${info.url})`,
].join("\n"))
.setFooter({ text: `Use ${prefix}lastfm scrobble to toggle scrobbling` });
return msg.reply({ embeds: [embed] });
}
// ── Loved tracks ──────────────────────────────────────────────────────
case "loved": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
let tracks;
try {
tracks = await lastfm.getLovedTracks(userId, 15);
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to fetch loved tracks: ${err.message}`)]
});
}
if (!tracks.length) {
return msg.reply({
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`❤️ No loved tracks found for **${user.username}**.`)]
});
}
return msg.reply({ embeds: [buildTrackList(user.username, "❤️ Loved Tracks", tracks)] });
}
// ── Top tracks ─────────────────────────────────────────────────────────
case "top": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
let tracks;
try {
tracks = await lastfm.getTopTracks(userId, "overall", 15);
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to fetch top tracks: ${err.message}`)]
});
}
if (!tracks.length) {
return msg.reply({
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`📊 No top tracks found for **${user.username}**.`)]
});
}
return msg.reply({ embeds: [buildTrackList(user.username, "📊 Top Tracks", tracks, true)] });
}
// ── Recent tracks ──────────────────────────────────────────────────────
case "recent": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
let tracks;
try {
tracks = await lastfm.getRecentTracks(userId, 15);
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to fetch recent tracks: ${err.message}`)]
});
}
if (!tracks.length) {
return msg.reply({
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🕐 No recent tracks found for **${user.username}**.`)]
});
}
return msg.reply({ embeds: [buildTrackList(user.username, "🕐 Recent Tracks", tracks)] });
}
default:
return msg.reply({
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription([
`🎵 **Last.fm Commands:**`,
``,
`\`${prefix}lastfm link\` — Link your Last.fm account`,
`\`${prefix}lastfm unlink\` — Disconnect your account`,
`\`${prefix}lastfm scrobble\` — Toggle auto-scrobbling`,
`\`${prefix}lastfm np\` — Show your Last.fm now playing`,
`\`${prefix}lastfm profile\` — View your Last.fm profile`,
`\`${prefix}lastfm loved\` — View your loved tracks`,
`\`${prefix}lastfm top\` — View your top tracks`,
`\`${prefix}lastfm recent\` — View your recent tracks`,
``,
`💡 You can also play your tracks: \`${prefix}play lastfm loved\``,
].join("\n"))]
});
}
}
// ── Track list embed builder ──────────────────────────────────────────────────
function buildTrackList(username, title, tracks, showPlaycount = false) {
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)` : "";
return `\`${num}.\` ${link} — **${t.artist}**${extra}`;
});
const desc = lines.join("\n").slice(0, 4096);
return new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle(`${title} — ${username}`)
.setDescription(desc)
.setFooter({ text: `💡 Use ${"%"}play lastfm loved to play these!` });
}
+8
View File
@@ -76,6 +76,14 @@
}, },
"sessionSecret": "secret for the expressjs session middleware; https://www.npmjs.com/package/express-session#user-content-secret", "sessionSecret": "secret for the expressjs session middleware; https://www.npmjs.com/package/express-session#user-content-secret",
"geniusToken": "Genius access token (Used for lyrics); optional", "geniusToken": "Genius access token (Used for lyrics); optional",
"lastfm": {
"Comment": "Last.fm integration: auto-scrobble songs, play loved/top/recent tracks. Register at https://www.last.fm/api/account/create",
"apiKey": "your_lastfm_api_key",
"apiSecret": "your_lastfm_api_secret",
"scrobbleThreshold": 0.5,
"scrobbleMinMs": 240000,
"Comment2": "scrobbleThreshold: fraction of track duration before scrobbling (0.5 = 50%). scrobbleMinMs: minimum ms played before scrobble (default 4 min). Both must be met."
},
"owners": ["user id for owner-only commands", "another user id"], "owners": ["user id for owner-only commands", "another user id"],
"playerAFKTimeout": 60000, "playerAFKTimeout": 60000,
"Comment": "The above specifies the time in ms after which a player goes inactive; Optional.", "Comment": "The above specifies the time in ms after which a player goes inactive; Optional.",
+6
View File
@@ -14,6 +14,7 @@ import { Dashboard } from "./src/dashboard/Dashboard.mjs";
import { Locale } from "./src/constants/Locale.mjs"; import { Locale } from "./src/constants/Locale.mjs";
import { RecoveryManager } from "./src/RecoveryManager.mjs"; import { RecoveryManager } from "./src/RecoveryManager.mjs";
import { GatewayHandler } from "./src/GatewayHandler.mjs"; import { GatewayHandler } from "./src/GatewayHandler.mjs";
import { LastFmManager } from "./src/LastFmManager.mjs";
export class Remix { export class Remix {
constructor() { constructor() {
@@ -146,6 +147,10 @@ export class Remix {
// are active before the first Ready event fires. // are active before the first Ready event fires.
this.gatewayHandler.setupEventHandlers(); this.gatewayHandler.setupEventHandlers();
// ── Last.fm Manager ─────────────────────────────────────────────────────
// Handles Last.fm API auth, scrobbling, and user data.
this.lastfm = new LastFmManager(config.lastfm, config.mysql);
// ── Settings ready callback ────────────────────────────────────────────── // ── Settings ready callback ──────────────────────────────────────────────
settings.on("ready", () => { settings.on("ready", () => {
initLogger(config); initLogger(config);
@@ -258,6 +263,7 @@ export class Remix {
timers: this.T, timers: this.T,
}); });
this.players.observedVoiceUsers = this.observedVoiceUsers; this.players.observedVoiceUsers = this.observedVoiceUsers;
this.players._lastfm = this.lastfm;
// ── Periodic alone-check ─────────────────────────────────────────────────── // ── Periodic alone-check ───────────────────────────────────────────────────
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval; const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
+453
View File
@@ -0,0 +1,453 @@
/**
* LastFmManager.mjs — Last.fm API client for scrobbling, auth, and user data.
*
* Features:
* - Auth flow (desktop API: get token → user authorizes → get session)
* - Now-playing notification (track.scrobble with timestamp=0)
* - Full scrobble after threshold (50% of track or 4 min, whichever is less)
* - Fetch loved / top / recent tracks for %play lastfm loved/top/recent
* - Per-user session key storage in MySQL table `lastfm_users`
*
* Last.fm API docs: https://www.last.fm/api
*/
import crypto from "node:crypto";
import { logger } from "./constants/Logger.mjs";
const BASE_URL = "https://ws.audioscrobbler.com/2.0/";
// ── Helpers ────────────────────────────────────────────────────────────────────
/**
* Build the API signature required by Last.fm for authenticated calls.
* See: https://www.last.fm/api/authspec#_8-signing-calls
*/
function buildSignature(params, apiSecret) {
// 1. Sort all parameter keys alphabetically
const sorted = Object.keys(params).sort();
// 2. Concatenate key+value pairs
const str = sorted.map(k => k + params[k]).join("");
// 3. Append secret
return crypto.createHash("md5").update(str + apiSecret).digest("hex");
}
/**
* Make a signed Last.fm API call.
* @param {object} params - API parameters (method, api_key, etc.)
* @param {string} apiSecret
* @param {boolean} [post=false] - Use POST instead of GET
* @returns {Promise<object>} Parsed JSON response
*/
async function apiCall(params, apiSecret, post = false) {
const allParams = { ...params, format: "json" };
allParams.api_sig = buildSignature(allParams, apiSecret);
const url = post ? BASE_URL : `${BASE_URL}?${new URLSearchParams(allParams)}`;
const opts = post
? {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(allParams).toString(),
}
: {};
const res = await fetch(url, opts);
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`Last.fm HTTP ${res.status}: ${text.slice(0, 200)}`);
}
const data = await res.json();
if (data.error) {
throw new Error(`Last.fm ${data.error}: ${data.message}`);
}
return data;
}
// ── LastFmManager ──────────────────────────────────────────────────────────────
export class LastFmManager {
/**
* @param {object} config - The `lastfm` section from config.json
* @param {object} mysqlConfig - MySQL connection info for creating the users table
*/
constructor(config, mysqlConfig) {
this.apiKey = config?.apiKey ?? "";
this.apiSecret = config?.apiSecret ?? "";
this.enabled = !!(this.apiKey && this.apiSecret);
this.scrobbleThreshold = config?.scrobbleThreshold ?? 0.5; // fraction of track duration
this.scrobbleMinMs = config?.scrobbleMinMs ?? 240_000; // 4 min fallback
// MySQL pool (lazy-created on first query)
this._mysqlConfig = mysqlConfig;
this._pool = null;
// In-memory user cache: Map<userId, { sessionKey, username, scrobbleEnabled }>
this._userCache = new Map();
if (!this.enabled) {
logger.settings("[LastFm] Disabled — apiKey or apiSecret missing in config.");
}
}
// ── MySQL ──────────────────────────────────────────────────────────────────
async _getPool() {
if (this._pool) return this._pool;
// Dynamic import so we don't crash if mysql2 isn't needed
const mysql = await import("mysql2/promise");
this._pool = mysql.createPool({
host: this._mysqlConfig.host,
port: this._mysqlConfig.port ?? 3306,
user: this._mysqlConfig.user,
password: this._mysqlConfig.password,
database: this._mysqlConfig.database,
});
await this._initTable();
return this._pool;
}
async _initTable() {
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
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
`);
}
// ── User persistence ───────────────────────────────────────────────────────
async getUser(userId) {
const cached = this._userCache.get(userId);
if (cached) return cached;
const pool = await this._getPool();
const [rows] = await pool.execute(
"SELECT session_key, username, scrobble FROM lastfm_users WHERE user_id = ?",
[String(userId)]
);
if (!rows.length) return null;
const row = rows[0];
const data = {
sessionKey: row.session_key,
username: row.username,
scrobbleEnabled: !!row.scrobble,
};
this._userCache.set(userId, data);
return data;
}
async saveUser(userId, sessionKey, username) {
const pool = await this._getPool();
await pool.execute(
`INSERT INTO lastfm_users (user_id, session_key, username, scrobble)
VALUES (?, ?, ?, 1)
ON DUPLICATE KEY UPDATE session_key = VALUES(session_key), username = VALUES(username)`,
[String(userId), sessionKey, username ?? ""]
);
const data = { sessionKey, username: username ?? "", scrobbleEnabled: true };
this._userCache.set(userId, data);
return data;
}
async removeUser(userId) {
const pool = await this._getPool();
await pool.execute("DELETE FROM lastfm_users WHERE user_id = ?", [String(userId)]);
this._userCache.delete(userId);
}
async setScrobble(userId, enabled) {
const pool = await this._getPool();
await pool.execute(
"UPDATE lastfm_users SET scrobble = ? WHERE user_id = ?",
[enabled ? 1 : 0, String(userId)]
);
const cached = this._userCache.get(userId);
if (cached) cached.scrobbleEnabled = enabled;
}
// ── Auth flow ──────────────────────────────────────────────────────────────
/**
* Step 1: Get an auth token. The user must visit the Last.fm auth URL to approve it.
* @returns {Promise<string>} The auth token
*/
async getAuthToken() {
this._assertEnabled();
const data = await apiCall(
{ method: "auth.gettoken", api_key: this.apiKey },
this.apiSecret
);
return data.token;
}
/**
* Get the URL the user should visit to authorize the token.
*/
getAuthUrl(token) {
return `https://www.last.fm/api/auth/?api_key=${this.apiKey}&token=${token}`;
}
/**
* Step 2: After the user authorizes the token, exchange it for a session key.
* @returns {Promise<{ key: string, name: string }>}
*/
async getSession(token) {
this._assertEnabled();
const data = await apiCall(
{ method: "auth.getsession", api_key: this.apiKey, token },
this.apiSecret
);
return data.session; // { key, name }
}
// ── Scrobbling ─────────────────────────────────────────────────────────────
/**
* Send a "now playing" notification to Last.fm (does NOT count as a scrobble).
* Called immediately when a track starts.
*/
async updateNowPlaying(userId, track) {
if (!this.enabled) return;
const user = await this.getUser(userId);
if (!user || !user.scrobbleEnabled) return;
try {
await apiCall(
{
method: "track.updatenowplaying",
api_key: this.apiKey,
sk: user.sessionKey,
artist: this._extractArtist(track),
track: this._extractTitle(track),
album: track.album ?? "",
duration: this._extractDurationSec(track),
trackNumber: track.trackNumber ?? "",
},
this.apiSecret,
true // POST
);
} catch (err) {
logger.warn(`[LastFm] updateNowPlaying failed for ${userId}: ${err.message}`);
}
}
/**
* Scrobble a track (counts toward the user's Last.fm play counts).
* Called after the track has played for >= 50% of its duration (or 4 minutes).
*/
async scrobble(userId, track, startedAtMs) {
if (!this.enabled) return;
const user = await this.getUser(userId);
if (!user || !user.scrobbleEnabled) return;
try {
await apiCall(
{
method: "track.scrobble",
api_key: this.apiKey,
sk: user.sessionKey,
"artist[0]": this._extractArtist(track),
"track[0]": this._extractTitle(track),
"album[0]": track.album ?? "",
"timestamp[0]": Math.floor(startedAtMs / 1000),
"duration[0]": this._extractDurationSec(track),
},
this.apiSecret,
true // POST
);
logger.settings(`[LastFm] Scrobbled "${track.title}" for ${userId}`);
} catch (err) {
logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`);
}
}
// ── User data (for play command) ──────────────────────────────────────────
/**
* Get the user's loved tracks.
* @param {string} userId - Discord/Fluxer user ID
* @param {number} [limit=20] - Max tracks to return
* @returns {Promise<Array<{ artist, name, url, image }>>}
*/
async getLovedTracks(userId, limit = 20) {
const user = await this.getUser(userId);
if (!user) throw new Error("NOT_LINKED");
const data = await apiCall(
{
method: "user.getlovedtracks",
api_key: this.apiKey,
user: user.username,
limit,
},
this.apiSecret
);
return (data.lovedtracks?.track ?? []).map(t => ({
artist: t.artist?.name ?? t.artist?.["#text"] ?? "Unknown",
name: t.name,
url: t.url,
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
}));
}
/**
* Get the user's top tracks.
* @param {string} userId
* @param {string} [period="overall"] - overall | 7day | 1month | 3month | 6month | 12month
* @param {number} [limit=20]
*/
async getTopTracks(userId, period = "overall", limit = 20) {
const user = await this.getUser(userId);
if (!user) throw new Error("NOT_LINKED");
const data = await apiCall(
{
method: "user.gettoptracks",
api_key: this.apiKey,
user: user.username,
period,
limit,
},
this.apiSecret
);
return (data.toptracks?.track ?? []).map(t => ({
artist: t.artist?.name ?? "Unknown",
name: t.name,
url: t.url,
playcount: t.playcount ?? 0,
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
}));
}
/**
* Get the user's recent tracks.
* @param {string} userId
* @param {number} [limit=20]
*/
async getRecentTracks(userId, limit = 20) {
const user = await this.getUser(userId);
if (!user) throw new Error("NOT_LINKED");
const data = await apiCall(
{
method: "user.getrecenttracks",
api_key: this.apiKey,
user: user.username,
limit,
},
this.apiSecret
);
return (data.recenttracks?.track ?? []).map(t => ({
artist: t.artist?.["#text"] ?? t.artist?.name ?? "Unknown",
name: t.name,
url: t.url,
now: t["@attr"]?.nowplaying === "true",
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
}));
}
/**
* Get track info (play count, tags, etc.) for the %np embed.
*/
async getTrackInfo(artist, track, userId = null) {
if (!this.enabled) return null;
const params = {
method: "track.getinfo",
api_key: this.apiKey,
artist,
track,
};
// If user is linked, include their username for personal playcount
if (userId) {
const user = await this.getUser(userId);
if (user) params.username = user.username;
}
try {
const data = await apiCall(params, this.apiSecret);
return data.track;
} catch {
return null;
}
}
/**
* Get the user's Last.fm profile info.
*/
async getUserInfo(userId) {
const user = await this.getUser(userId);
if (!user) throw new Error("NOT_LINKED");
const data = await apiCall(
{
method: "user.getinfo",
api_key: this.apiKey,
user: user.username,
},
this.apiSecret
);
return data.user;
}
// ── Internal helpers ───────────────────────────────────────────────────────
_assertEnabled() {
if (!this.enabled) throw new Error("Last.fm integration is not configured (missing apiKey/apiSecret).");
}
_extractArtist(track) {
return track.artists?.[0]?.name
?? track.author?.name
?? track.artist
?? "Unknown Artist";
}
_extractTitle(track) {
return track.title ?? track.name ?? "Unknown Track";
}
_extractDurationSec(track) {
if (!track.duration) return "";
// Duration can be: { seconds: N }, "PT3M0S", or milliseconds number
if (typeof track.duration === "object" && track.duration.seconds) return track.duration.seconds;
if (typeof track.duration === "number") return Math.round(track.duration / 1000);
if (typeof track.duration === "string") {
const m = track.duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
if (m) return ((+m[1] || 0) * 3600) + ((+m[2] || 0) * 60) + (+m[3] || 0);
}
return "";
}
/**
* Should this track be scrobbled based on play duration?
* Last.fm rule: scrobble if played for >= 50% of track duration OR >= 4 minutes,
* and the track must be >= 30 seconds long.
*/
shouldScrobble(track, playedMs) {
const durationMs = typeof track.duration === "object" && track.duration.seconds
? track.duration.seconds * 1000
: typeof track.duration === "number"
? track.duration
: null;
if (!durationMs || durationMs < 30_000) return false; // too short
const thresholdMs = Math.min(durationMs * this.scrobbleThreshold, this.scrobbleMinMs);
return playedMs >= thresholdMs;
}
}
+102
View File
@@ -115,6 +115,7 @@ export class PlayerManager {
this.locale = config.locale ?? null; this.locale = config.locale ?? null;
this.spawnPlayer = config.spawnPlayer ?? null; // RecoveryManager.spawnPlayer — for 24/7 rejoin on autoleave this.spawnPlayer = config.spawnPlayer ?? null; // RecoveryManager.spawnPlayer — for 24/7 rejoin on autoleave
this.timers = config.timers ?? {}; this.timers = config.timers ?? {};
this._lastfm = null; // Set later by Remix class after init
} }
/** /**
@@ -218,6 +219,11 @@ export class PlayerManager {
emit("streamStartPlay", Date.now()); emit("streamStartPlay", Date.now());
// Also broadcast on global channel for full state update // Also broadcast on global channel for full state update
this.dashboard.playerUpdate({ type: "startplay" }, player); this.dashboard.playerUpdate({ type: "startplay" }, player);
// ── Last.fm: now-playing notification + deferred scrobble ────────────
if (this._lastfm?.enabled && song) {
this._handleLastFmStartPlay(player, song);
}
}); });
player.on("stopplay", () => { player.on("stopplay", () => {
@@ -829,4 +835,100 @@ export class PlayerManager {
})(); })();
} }
// ═══════════════════════════════════════════════════════════════════════════
// Last.fm Scrobbling
// ═══════════════════════════════════════════════════════════════════════════
/**
* Handle the "startplay" event for Last.fm: send now-playing notification
* to all linked users in the voice channel, and schedule a deferred scrobble
* after the track has played for long enough (50% duration or 4 min).
*
* @param {Player} player
* @param {Object} song - Track object
*/
_handleLastFmStartPlay(player, song) {
const lastfm = this._lastfm;
if (!lastfm?.enabled) return;
const guildId = cleanId(player._guildId);
if (!guildId) return;
// Find all human users in the voice channel
const channelId = getPlayerChannelId(player);
const humanUserIds = [];
// Check observedVoiceUsers first
if (this.observedVoiceUsers) {
for (const [uid, info] of this.observedVoiceUsers) {
if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) {
humanUserIds.push(uid);
}
}
}
// Also check guild voice states as fallback
const guild = player.client?.guilds?.get(guildId);
if (guild) {
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
if (voiceStates) {
const entries = Array.isArray(voiceStates)
? voiceStates
: typeof voiceStates.values === "function"
? [...voiceStates.values()]
: Object.values(voiceStates ?? {});
for (const state of entries) {
const uid = state?.userId ?? state?.user_id;
const chId = cleanId(state?.channelId ?? state?.channel_id);
if (uid && chId === channelId) {
// Skip bots
const member = guild.members?.get?.(uid);
if (member?.user?.bot) continue;
if (!humanUserIds.includes(uid)) humanUserIds.push(uid);
}
}
}
}
const startedAtMs = player.startedPlaying;
// Send now-playing for each linked user
for (const userId of humanUserIds) {
lastfm.updateNowPlaying(userId, song).catch(() => {});
}
// Schedule deferred scrobble after threshold
const durationMs = (() => {
const d = song.duration;
if (!d) return null;
if (typeof d === "object" && d.seconds) return d.seconds * 1000;
if (typeof d === "number") return d;
return null;
})();
if (durationMs && durationMs >= 30_000) {
const thresholdMs = Math.min(
durationMs * lastfm.scrobbleThreshold,
lastfm.scrobbleMinMs
);
// Don't schedule if threshold is too far out (cap at 10 min)
if (thresholdMs <= 600_000) {
setTimeout(() => {
// Only scrobble if the same song is still playing
const current = player.queue?.getCurrent();
if (!current || player._destroyed || player.leaving) return;
if (current.title !== song.title && current.url !== song.url) return;
if (player._paused) return; // don't scrobble if paused
const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs);
if (lastfm.shouldScrobble(song, playedMs)) {
for (const userId of humanUserIds) {
lastfm.scrobble(userId, song, startedAtMs).catch(() => {});
}
}
}, thresholdMs);
}
}
}
} }
+1 -1
View File
@@ -395,7 +395,7 @@ export class RecoveryManager {
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
.setColor(getGlobalColor()) .setColor(getGlobalColor())
.setDescription( .setDescription(
`Left channel ${activeChannelId} because of inactivity.\n` + `Left channel <#${activeChannelId}> because of inactivity.\n` +
`If you want me to stay in voice, use \`${prefix}247 on\` or \`${prefix}247 auto\`\n` + `If you want me to stay in voice, use \`${prefix}247 on\` or \`${prefix}247 auto\`\n` +
`💡 Use \`${prefix}247\` to view and manage all saved channels.` `💡 Use \`${prefix}247\` to view and manage all saved channels.`
) )
+32
View File
@@ -33,6 +33,7 @@
"invite": "Get the invite link for Remix and the support server.", "invite": "Get the invite link for Remix and the support server.",
"join": "Make the bot join your voice channel, or specify one.", "join": "Make the bot join your voice channel, or specify one.",
"leave": "Make the bot leave your current voice channel.", "leave": "Make the bot leave your current voice channel.",
"lastfm": "Link your Last.fm account, toggle scrobbling, or view your profile.",
"list": "List the songs in the queue of your current voice channel.", "list": "List the songs in the queue of your current voice channel.",
"loop": "Toggle the looping of your queue/song.", "loop": "Toggle the looping of your queue/song.",
"lyrics": "Display synced lyrics from NodeLink.", "lyrics": "Display synced lyrics from NodeLink.",
@@ -61,6 +62,10 @@
"debug": { "debug": {
"target": "The target that should be examined." "target": "The target that should be examined."
}, },
"lastfm": {
"action": "The action to perform: link, confirm, unlink, np, profile, loved, top, recent, scrobble",
"token": "The auth token from Last.fm (used with 'confirm' action)"
},
"eval": { "eval": {
"expression": "The JavaScript expression to evaluate" "expression": "The JavaScript expression to evaluate"
}, },
@@ -249,6 +254,33 @@
"leftRejoin247": "✅ Successfully Left — rejoining <#{{channel}}> in 5 seconds.\nTo disable 24/7 mode permanently, use `%247 off`.", "leftRejoin247": "✅ Successfully Left — rejoining <#{{channel}}> in 5 seconds.\nTo disable 24/7 mode permanently, use `%247 off`.",
"left247On": "✅ Successfully Left.\n24/7 mode is **on** — bot won't rejoin automatically. Use `%play` to bring it back, or `%247 off` to fully disable.\nUse `%247` to view all saved channels." "left247On": "✅ Successfully Left.\n24/7 mode is **on** — bot won't rejoin automatically. Use `%play` to bring it back, or `%247 off` to fully disable.\nUse `%247` to view all saved channels."
}, },
"lastfm": {
"notConfigured": "❌ Last.fm integration is not configured on this bot. Ask the bot owner to add a Last.fm API key to the config.",
"notLinked": "❌ You don't have a Last.fm account linked. Use `{{prefix}}lastfm link` to get started.",
"linked": "✅ Last.fm account **[{{username}}](https://last.fm/user/{{username}})** linked! Scrobbling is enabled by default.",
"alreadyLinked": "✅ You already have **{{username}}** linked! Use `{{prefix}}lastfm unlink` to disconnect, or `{{prefix}lastfm scrobble` to toggle scrobbling.",
"unlinked": "✅ Last.fm account **{{username}}** has been unlinked.",
"scrobbleEnabled": "✅ Scrobbling **enabled** — songs you listen to will be scrobbled to **{{username}}**.",
"scrobbleDisabled": "⏸️ Scrobbling **disabled** — songs won't be scrobbled. Your account is still linked.",
"authDM": "📧 Check your DMs for the Last.fm authorization link! After approving, run `{{prefix}}lastfm confirm <token>` here.",
"authDMFailed": "⚠️ I couldn't DM you. [Click here to authorize on Last.fm]({{url}}), then run `{{prefix}}lastfm confirm <token>`.",
"confirmUsage": "❌ Usage: `{{prefix}}lastfm confirm <token>` — provide the token from the auth DM.",
"confirmFailed": "❌ Failed to get session: {{error}}\nMake sure you approved the token on Last.fm first.",
"tokenFailed": "❌ Failed to get auth token: {{error}}",
"noLoved": "❤️ No loved tracks found for **{{username}}**.",
"noTop": "📊 No top tracks found for **{{username}}**.",
"noRecent": "🕐 No recent tracks found for **{{username}}**.",
"lovedTitle": "❤️ Loved Tracks — {{username}}",
"topTitle": "📊 Top Tracks — {{username}}",
"recentTitle": "🕐 Recent Tracks — {{username}}",
"nowPlaying": "🎵 Now Playing on Last.fm",
"lastPlayed": "🕐 Last Played on Last.fm",
"profileTitle": "Last.fm Profile: {{username}}",
"profileScrobbles": "🎵 **{{playcount}}** scrobbles",
"profileRegistered": "👤 Registered: {{date}}",
"profileLink": "🔗 [Open profile]({{url}})",
"fetchFailed": "❌ Failed to fetch data from Last.fm: {{error}}"
},
"list": { "list": {
"empty": "📭 The queue is empty. Use `{{prefix}}play` to add songs!", "empty": "📭 The queue is empty. Use `{{prefix}}play` to add songs!",
"emptyInline": "_Queue is empty._", "emptyInline": "_Queue is empty._",