From 894d8b99ac56fc5b1276824fe0be577228391ca0 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Sun, 10 May 2026 00:09:09 +0300 Subject: [PATCH] adding lastfm to play --- README.md | 4 +- commands/lastfm.mjs | 167 +++++++++++++++++++++++++++++++++++++++++- commands/play.mjs | 17 ++++- src/LastFmManager.mjs | 47 ++++++++++++ 4 files changed, 226 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index e645945..eec6d0d 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ Below is the complete list of Remix's commands. The default prefix is `%`. | Command | Description | Usage | Aliases | | :--- | :--- | :--- | :--- | -| `play` | Play a song from a URL, search query, or playlist | `%play Never Gonna Give You Up` | `p` | +| `play` | Play a song from a URL, search query, or playlist | `%play Never Gonna Give You Up` / `%play lastfm:loved` | `p` | | `playnext` | Add a song/playlist to the *top* of the queue | `%playnext query: text` | `pn` | | `pause` | Pause the current playback | `%pause` | | | `resume` | Resume the paused playback | `%resume` | | @@ -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) | `%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 account, toggle scrobbling, view profile | `%lastfm link` | `lf`, `lfm` | +| `lastfm` | Link Last.fm, toggle scrobbling, view profile, play tracks | `%lastfm link` / `%lastfm play loved` | `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` | | diff --git a/commands/lastfm.mjs b/commands/lastfm.mjs index 073a3ab..c106882 100644 --- a/commands/lastfm.mjs +++ b/commands/lastfm.mjs @@ -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, scrobble", "options.lastfm.action") - .addChoices("link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", "scrobble") + .setDescription("The action to perform: link, unlink, np, profile, loved, top, recent, play, scrobble", "options.lastfm.action") + .addChoices("link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", "play", "scrobble") .setRequired(false) ) .addTextOption(o => @@ -40,6 +40,138 @@ function notLinked(prefix) { }; } +/** + * Resolve a Last.fm category (loved/top/recent) into playable tracks. + * Shared between `%lastfm play ` and `%play lastfm:`. + * + * @param {object} ctx - The command `this` context (has .lastfm, .getPlayer, .handler, .t) + * @param {object} msg - The message object + * @param {string} userId - Discord user ID + * @param {string} category - "loved", "top", or "recent" + * @param {object} [options] + * @param {string} [options.period] - Period for top tracks + * @param {number} [options.limit] - Max tracks + * @returns {Promise} + */ +export async function playLastFmCategory(ctx, msg, userId, category, options = {}) { + const lastfm = ctx.lastfm; + const prefix = ctx.handler?.getPrefix?.(msg.message?.guildId) ?? "%"; + + if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(msg)); + + // Validate category + if (!["loved", "top", "recent"].includes(category)) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + `โŒ Unknown category \`${category}\`. Use \`loved\`, \`top\`, or \`recent\`.` + )] + }); + } + + // Check if user is linked + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(prefix)); + + // Get a player (user must be in a voice channel) + const p = await ctx.getPlayer(msg, true, true, true); + if (!p) return; + + // Fetch tracks from Last.fm + const categoryEmoji = { loved: "โค๏ธ", top: "๐Ÿ“Š", recent: "๐Ÿ•" }[category]; + const categoryLabel = { loved: "Loved", top: "Top", recent: "Recent" }[category]; + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + `${categoryEmoji} Fetching your ${categoryLabel} tracks from Last.fm...` + )] + }); + } catch { statusMsg = null; } + + let result; + try { + result = await lastfm.getTracksForPlay(userId, category, options); + } catch (err) { + const errMsg = err.message === "NOT_LINKED" + ? notLinked(prefix) + : { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`โŒ Failed to fetch Last.fm tracks: ${err.message}`)] }; + if (statusMsg) statusMsg.edit(errMsg).catch(() => msg.reply(errMsg)); + else msg.reply(errMsg); + return; + } + + if (!result.tracks.length) { + const noTracks = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + `${categoryEmoji} No ${categoryLabel.toLowerCase()} tracks found for **${result.username}**.` + )] }; + if (statusMsg) statusMsg.edit(noTracks).catch(() => msg.reply(noTracks)); + else msg.reply(noTracks); + return; + } + + // Play each track sequentially โ€” first one via play(), rest added to queue + let added = 0; + let failed = 0; + + if (statusMsg) { + statusMsg.edit({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + `${categoryEmoji} Loading **${result.tracks.length}** ${categoryLabel.toLowerCase()} tracks from **${result.username}**...` + )] + }).catch(() => {}); + } + + // Play the first track immediately + const firstTrack = result.tracks[0]; + try { + const events = p.play(firstTrack.query, false, "ytm"); + await new Promise((resolve) => { + events.on("message", () => resolve()); + events.on("error", () => { failed++; resolve(); }); + // Timeout safety + setTimeout(resolve, 15_000); + }); + added++; + } catch { + failed++; + } + + // Queue the rest โ€” use workerJob directly for speed (no need to wait for play messages) + const restTracks = result.tracks.slice(1); + for (const track of restTracks) { + try { + const data = await p.workerJob("generalQuery", { query: track.query, provider: "ytm" }); + if (data && data.type !== "error") { + if (data.type === "list") { + p.addManyToQueue(data.data, false); + added += data.data.length; + } else if (data.type === "video") { + p.addToQueue(data.data, false); + added++; + } else { + failed++; + } + } else { + failed++; + } + } catch { + failed++; + } + } + + const summary = []; + if (added > 0) summary.push(`โœ… Added **${added}** track${added !== 1 ? "s" : ""} to the queue`); + if (failed > 0) summary.push(`โš ๏ธ ${failed} track${failed !== 1 ? "s" : ""} couldn't be found`); + + const doneEmbed = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + `${categoryEmoji} **${categoryLabel} Tracks โ€” ${result.username}**\n${summary.join(" ยท ")}` + )] }; + + if (statusMsg) statusMsg.edit(doneEmbed).catch(() => msg.reply(doneEmbed)); + else msg.reply(doneEmbed); +} + // โ”€โ”€ Run โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ export async function run(msg, data) { @@ -238,6 +370,30 @@ export async function run(msg, data) { return msg.reply({ embeds: [embed] }); } + // โ”€โ”€ Play (loved/top/recent tracks as queue) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + case "play": { + // Parse category from the token option or from message text + let category = data.get("token")?.value?.toLowerCase(); + if (!category) { + const rawContent = msg.message?.content ?? ""; + const args = rawContent.split(/\s+/); + const playIdx = args.indexOf("play"); + if (playIdx >= 0 && args[playIdx + 1]) { + category = args[playIdx + 1].toLowerCase(); + } + } + + if (!category || !["loved", "top", "recent"].includes(category)) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + `โŒ Usage: \`${prefix}lastfm play \`\nExample: \`${prefix}lastfm play loved\`` + )] + }); + } + + return playLastFmCategory(this, msg, userId, category); + } + // โ”€โ”€ Loved tracks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ case "loved": { const user = await lastfm.getUser(userId); @@ -322,8 +478,11 @@ export async function run(msg, data) { `\`${prefix}lastfm loved\` โ€” View your loved tracks`, `\`${prefix}lastfm top\` โ€” View your top tracks`, `\`${prefix}lastfm recent\` โ€” View your recent tracks`, + `\`${prefix}lastfm play loved\` โ€” Play your loved tracks`, + `\`${prefix}lastfm play top\` โ€” Play your top tracks`, + `\`${prefix}lastfm play recent\` โ€” Play your recent tracks`, ``, - `๐Ÿ’ก You can also play your tracks: \`${prefix}play lastfm loved\``, + `๐Ÿ’ก Or use inline: \`${prefix}play lastfm:loved\``, ].join("\n"))] }); } @@ -347,5 +506,5 @@ function buildTrackList(username, title, tracks, showPlaycount = false) { .setColor(getGlobalColor()) .setTitle(`${title} โ€” ${username}`) .setDescription(desc) - .setFooter({ text: `๐Ÿ’ก Use ${"%"}play lastfm loved to play these!` }); + .setFooter({ text: `๐Ÿ’ก Use %lastfm play loved to play these!` }); } diff --git a/commands/play.mjs b/commands/play.mjs index 915b290..429a86e 100644 --- a/commands/play.mjs +++ b/commands/play.mjs @@ -2,6 +2,10 @@ import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; import { PROVIDER_CHOICES } from "../src/constants/providers.mjs"; +import { playLastFmCategory } from "./lastfm.mjs"; + +// Last.fm provider keywords that trigger special play logic +const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent"]; function parseInlineProvider(raw) { const match = raw.match(/^([a-z]+):\s*(.+)$/i); @@ -29,6 +33,7 @@ export const command = new CommandBuilder() "$prefixplay dz: get lucky", "$prefixplay -p yt take over league of legends", "$prefixplay https://open.spotify.com/track/...", + "$prefixplay lastfm:loved", "$prefixp take over league of legends" ) .addTextOption(option => @@ -46,14 +51,20 @@ export const command = new CommandBuilder() .addAlias("p"); export async function run(message, data) { - const p = await this.getPlayer(message, true, true, true); - if (!p) return; - const rawQuery = data.get("query").value; const flagProvider = data.get("provider")?.value; const { provider: inlineProvider, query } = parseInlineProvider(rawQuery); const provider = inlineProvider ?? flagProvider ?? "ytm"; + // โ”€โ”€ Last.fm special provider: %play lastfm:loved / lastfm:top / lastfm:recent โ”€โ”€ + if ((provider === "lastfm" || provider === "lf") && LASTFM_PLAY_CATEGORIES.includes(query.toLowerCase())) { + const userId = message.message?.author?.id ?? message.author?.id; + return playLastFmCategory(this, message, userId, query.toLowerCase()); + } + + const p = await this.getPlayer(message, true, true, true); + if (!p) return; + const searchEmbed = new EmbedBuilder() .setColor(getGlobalColor()) .setDescription(this.t(message, "responses.play.searching")) diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs index c7d647d..51d0554 100644 --- a/src/LastFmManager.mjs +++ b/src/LastFmManager.mjs @@ -407,6 +407,53 @@ export class LastFmManager { return data.user; } + // โ”€โ”€ Play helper (for %lastfm play and %play lastfm:loved etc.) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + /** + * Fetch tracks from Last.fm by category and return search queries + * that can be resolved by the player's worker (YouTube Music search). + * + * @param {string} userId + * @param {"loved"|"top"|"recent"} category + * @param {object} [options] + * @param {string} [options.period="overall"] - Period for top tracks (overall|7day|1month|3month|6month|12month) + * @param {number} [options.limit=20] - Max tracks to return + * @returns {Promise<{ username: string, tracks: Array<{ query: string, artist: string, name: string, url: string }> }>} + */ + async getTracksForPlay(userId, category, options = {}) { + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + const limit = options.limit ?? 20; + let tracks; + + switch (category) { + case "loved": + tracks = await this.getLovedTracks(userId, limit); + break; + case "top": + tracks = await this.getTopTracks(userId, options.period ?? "overall", limit); + break; + case "recent": + tracks = await this.getRecentTracks(userId, limit); + // Filter out "now playing" entries (they have no finished timestamp) + tracks = tracks.filter(t => !t.now); + break; + default: + throw new Error(`Unknown Last.fm category: ${category}. Use loved, top, or recent.`); + } + + return { + username: user.username, + tracks: tracks.map(t => ({ + query: `${t.artist} ${t.name}`, // searchable query for YouTube Music + artist: t.artist, + name: t.name, + url: t.url ?? "", + })), + }; + } + // โ”€โ”€ Internal helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ _assertEnabled() {