mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
adding lastfm to play
This commit is contained in:
1 parent
71b79e7f38
commit
894d8b99ac
4 files changed
+226
-9
No files matched your search
@@ -92,7 +92,7 @@ Below is the complete list of Remix's commands. The default prefix is `%`.
|
|||||||
|
|
||||||
| Command | Description | Usage | Aliases |
|
| 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` |
|
| `playnext` | Add a song/playlist to the *top* of the queue | `%playnext query: text` | `pn` |
|
||||||
| `pause` | Pause the current playback | `%pause` | |
|
| `pause` | Pause the current playback | `%pause` | |
|
||||||
| `resume` | Resume the paused playback | `%resume` | |
|
| `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` |
|
| `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` |
|
| `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` | |
|
| `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` | |
|
||||||
|
|||||||
+163
-4
@@ -12,8 +12,8 @@ export const command = new CommandBuilder()
|
|||||||
.addAliases("lf", "lfm")
|
.addAliases("lf", "lfm")
|
||||||
.addChoiceOption(o =>
|
.addChoiceOption(o =>
|
||||||
o.setName("action")
|
o.setName("action")
|
||||||
.setDescription("The action to perform: link, unlink, np, profile, loved, top, recent, scrobble", "options.lastfm.action")
|
.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", "scrobble")
|
.addChoices("link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", "play", "scrobble")
|
||||||
.setRequired(false)
|
.setRequired(false)
|
||||||
)
|
)
|
||||||
.addTextOption(o =>
|
.addTextOption(o =>
|
||||||
@@ -40,6 +40,138 @@ function notLinked(prefix) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a Last.fm category (loved/top/recent) into playable tracks.
|
||||||
|
* Shared between `%lastfm play <cat>` and `%play lastfm:<cat>`.
|
||||||
|
*
|
||||||
|
* @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<void>}
|
||||||
|
*/
|
||||||
|
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 ────────────────────────────────────────────────────────────────────────
|
// ── Run ────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
@@ -238,6 +370,30 @@ export async function run(msg, data) {
|
|||||||
return msg.reply({ embeds: [embed] });
|
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 <loved|top|recent>\`\nExample: \`${prefix}lastfm play loved\``
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return playLastFmCategory(this, msg, userId, category);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Loved tracks ──────────────────────────────────────────────────────
|
// ── Loved tracks ──────────────────────────────────────────────────────
|
||||||
case "loved": {
|
case "loved": {
|
||||||
const user = await lastfm.getUser(userId);
|
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 loved\` — View your loved tracks`,
|
||||||
`\`${prefix}lastfm top\` — View your top tracks`,
|
`\`${prefix}lastfm top\` — View your top tracks`,
|
||||||
`\`${prefix}lastfm recent\` — View your recent 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"))]
|
].join("\n"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -347,5 +506,5 @@ function buildTrackList(username, title, tracks, showPlaycount = false) {
|
|||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(`${title} — ${username}`)
|
.setTitle(`${title} — ${username}`)
|
||||||
.setDescription(desc)
|
.setDescription(desc)
|
||||||
.setFooter({ text: `💡 Use ${"%"}play lastfm loved to play these!` });
|
.setFooter({ text: `💡 Use %lastfm play loved to play these!` });
|
||||||
}
|
}
|
||||||
+14
-3
@@ -2,6 +2,10 @@ import { CommandBuilder } from "../src/CommandHandler.mjs";
|
|||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
import { PROVIDER_CHOICES } from "../src/constants/providers.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) {
|
function parseInlineProvider(raw) {
|
||||||
const match = raw.match(/^([a-z]+):\s*(.+)$/i);
|
const match = raw.match(/^([a-z]+):\s*(.+)$/i);
|
||||||
@@ -29,6 +33,7 @@ export const command = new CommandBuilder()
|
|||||||
"$prefixplay dz: get lucky",
|
"$prefixplay dz: get lucky",
|
||||||
"$prefixplay -p yt take over league of legends",
|
"$prefixplay -p yt take over league of legends",
|
||||||
"$prefixplay https://open.spotify.com/track/...",
|
"$prefixplay https://open.spotify.com/track/...",
|
||||||
|
"$prefixplay lastfm:loved",
|
||||||
"$prefixp take over league of legends"
|
"$prefixp take over league of legends"
|
||||||
)
|
)
|
||||||
.addTextOption(option =>
|
.addTextOption(option =>
|
||||||
@@ -46,14 +51,20 @@ export const command = new CommandBuilder()
|
|||||||
.addAlias("p");
|
.addAlias("p");
|
||||||
|
|
||||||
export async function run(message, data) {
|
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 rawQuery = data.get("query").value;
|
||||||
const flagProvider = data.get("provider")?.value;
|
const flagProvider = data.get("provider")?.value;
|
||||||
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
|
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
|
||||||
const provider = inlineProvider ?? flagProvider ?? "ytm";
|
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()
|
const searchEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(this.t(message, "responses.play.searching"))
|
.setDescription(this.t(message, "responses.play.searching"))
|
||||||
|
|||||||
@@ -407,6 +407,53 @@ export class LastFmManager {
|
|||||||
return data.user;
|
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 ───────────────────────────────────────────────────────
|
// ── Internal helpers ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
_assertEnabled() {
|
_assertEnabled() {
|
||||||
|
|||||||
Reference in new issue
Block a user