mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
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:
1 parent
09fa5d160c
commit
8ac0dde343
8 files changed
+960
-3
No files matched your search
@@ -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!` });
|
||||
}
|
||||
Reference in new issue
Block a user