feat(playlists): support YouTube, Spotify, SoundCloud, and Apple Music imports with 250-track capacity

This commit is contained in:
NoLogicAlan committed 2026-11-23 03:22:39 +03:00
1 parent 98a69d471a
commit 495970ffe9
10 files changed
+335 -33

No files matched your search

+226 -7
View File
@@ -1,6 +1,6 @@
/**
* @module commands/playlist
* @description Save the active queue or manage personal custom playlists across servers.
* @description Save the active queue or import playlists from YouTube, Spotify, SoundCloud, Apple Music and more.
*/
import { CommandBuilder } from "../src/commands/index.mjs";
@@ -15,10 +15,107 @@ const COLOR_PRIMARY = 0xe9196c;
const COLOR_SUCCESS = 0x2ecc71;
const COLOR_ERROR = 0xe74c3c;
/**
* Format raw source identifiers into friendly labels.
* @param {string} raw
* @returns {string}
*/
function formatSourceName(raw) {
const s = String(raw || "").toLowerCase();
if (s.includes("spotify")) return "Spotify";
if (s.includes("youtube") || s.includes("yt")) return "YouTube";
if (s.includes("soundcloud")) return "SoundCloud";
if (s.includes("apple") || s.includes("applemusic")) return "Apple Music";
if (s.includes("deezer")) return "Deezer";
if (s.includes("tidal")) return "Tidal";
if (s.includes("bandcamp")) return "Bandcamp";
return "External Source";
}
/**
* Resolve tracks from an external URL (YouTube, Spotify, SoundCloud, Apple Music, Deezer, etc.) via Lavalink.
* @param {object} bot - The bot instance.
* @param {string} url - The URL to resolve.
* @returns {Promise<{name: string|null, tracks: Array<object>, source: string}>}
*/
async function resolveExternalPlaylist(bot, url) {
if (!bot.lavalink) return { name: null, tracks: [], source: "unknown" };
await bot.lavalink.waitForNode({ timeoutMs: 10_000 }).catch(() => {});
const cleanUrl = url.trim();
/* Canonicalize YouTube playlist queries if needed */
let searchQuery = cleanUrl;
const ytId = Utils.extractYouTubeId(cleanUrl);
const canonicalYt = ytId ? Utils.normalizeYouTubeUrl(cleanUrl) : null;
if (ytId && canonicalYt) {
try {
const listId = new URL(cleanUrl).searchParams.get("list");
if (listId) searchQuery = canonicalYt + "&list=" + listId;
} catch (_) {}
}
let result = null;
try {
result = await bot.lavalink.search(searchQuery);
} catch (err) {
logger.warn("[playlist] External resolve failed:", err?.message);
return { name: null, tracks: [], source: "unknown" };
}
const rawTracks = result?.tracks || [];
if (rawTracks.length === 0) {
return { name: null, tracks: [], source: "unknown" };
}
const playlistName = result?.playlistInfo?.name ?? result?.info?.name ?? null;
const allRawTracks = [...rawTracks];
/* Support LavaSrc / NodeLink pagination for large external playlists */
let nextPageToken = result?.pluginInfo?.nextPageToken ?? result?.playlistInfo?.nextPageToken;
let page = 1;
const maxPages = 6;
while (nextPageToken && page < maxPages && allRawTracks.length < MAX_TRACKS_PER_PLAYLIST) {
try {
page++;
const nextResult = await bot.lavalink.search(searchQuery, {
page,
pageToken: nextPageToken,
});
const nextTracks = nextResult?.tracks || [];
if (nextTracks.length === 0) break;
allRawTracks.push(...nextTracks);
nextPageToken = nextResult?.pluginInfo?.nextPageToken ?? nextResult?.playlistInfo?.nextPageToken;
} catch (_) {
break;
}
}
const tracks = allRawTracks.slice(0, MAX_TRACKS_PER_PLAYLIST).map(t => {
const info = t.info ?? t ?? {};
let ms = info.length ?? t.length ?? info.durationMs ?? 0;
let trackUri = info.uri ?? ("https://www.youtube.com/watch?v=" + (info.identifier || ""));
if (typeof trackUri === "string" && trackUri.includes("music.youtube.com")) {
trackUri = trackUri.replace("music.youtube.com", "www.youtube.com");
}
return {
title: Utils.cleanTitle(info.title ?? "Unknown"),
author: info.author ?? "Unknown",
uri: trackUri,
durationMs: ms,
sourceName: info.sourceName ?? "unknown",
thumbnail: info.artworkUrl ?? null,
};
}).filter(t => t.uri.length > 0);
const detectedSource = tracks[0]?.sourceName || "external";
return { name: playlistName, tracks, source: detectedSource };
}
/** @type {CommandBuilder} */
export const command = new CommandBuilder()
.setName("playlist")
.setDescription("Save the current queue or manage your personal custom playlists.", "commands.playlist")
.setDescription("Save the current queue or import playlists from YouTube, Spotify, SoundCloud, Apple Music and more.", "commands.playlist")
.addAliases("pl", "playlists")
.setCategory("music")
.addTextOption((o) =>
@@ -56,7 +153,7 @@ export async function run(msg, data) {
let sub = data?.action || "";
if (!sub) {
if (["save", "create", "new"].includes(firstToken)) sub = "save";
if (["save", "create", "new", "import"].includes(firstToken)) sub = "save";
else if (["play", "p", "load"].includes(firstToken)) sub = "play";
else if (["list", "all"].includes(firstToken)) sub = "list";
else if (["show", "view", "info"].includes(firstToken)) sub = "show";
@@ -72,10 +169,80 @@ export async function run(msg, data) {
}
/* -------------------------------------------------------------------------
SUBCOMMAND: SAVE
SUBCOMMAND: SAVE / IMPORT
------------------------------------------------------------------------- */
if (sub === "save" || sub === "create" || sub === "new") {
let name = rawParts.length > 1 ? rawParts[1] : null;
if (sub === "save" || sub === "create" || sub === "new" || sub === "import") {
let name = null;
let url = null;
/* Scan arguments to distinguish custom playlist name and optional source URL */
for (let i = 1; i < rawParts.length; i++) {
const part = rawParts[i];
if (Utils.isValidUrl(part)) {
url = part;
} else if (!name) {
name = part;
}
}
/* Case A: URL provided — import tracks from YouTube, Spotify, SoundCloud, Apple Music, etc. */
if (url) {
const sourceLabel = formatSourceName(url);
const loadingEmbed = new EmbedBuilder()
.setColor(embedColor)
.setDescription(this.t(msg, "responses.playlist.resolving", { source: sourceLabel }));
let statusMsg = null;
try {
statusMsg = await msg.reply({ embeds: [loadingEmbed] });
} catch (_) {}
const resolved = await resolveExternalPlaylist(this, url);
if (resolved.tracks.length === 0) {
const errorEmbed = new EmbedBuilder()
.setColor(COLOR_ERROR)
.setDescription(this.t(msg, "responses.playlist.noTracksFromSource"));
if (statusMsg) return statusMsg.edit({ embeds: [errorEmbed] });
return msg.reply({ embeds: [errorEmbed] });
}
/* Fallback to external playlist name if no custom name was given */
if (!name) {
name = resolved.name ? resolved.name.replace(/[^a-zA-Z0-9_\-\s]/g, "").slice(0, 32).trim() : null;
}
if (!name) name = `${sourceLabel.toLowerCase()}-import`;
const res = await pm.savePlaylist(userId, name, resolved.tracks);
if (!res.success) {
let errKey = "responses.playlist.saveFailed";
if (res.error === "LIMIT_REACHED") errKey = "responses.playlist.limitReached";
else if (res.error === "INVALID_NAME") errKey = "responses.playlist.invalidName";
const failEmbed = new EmbedBuilder()
.setColor(COLOR_ERROR)
.setDescription(this.t(msg, errKey, { max: MAX_PLAYLISTS_PER_USER }));
if (statusMsg) return statusMsg.edit({ embeds: [failEmbed] });
return msg.reply({ embeds: [failEmbed] });
}
const displaySource = formatSourceName(resolved.source);
const successEmbed = new EmbedBuilder()
.setColor(COLOR_SUCCESS)
.setDescription(this.t(msg, "responses.playlist.savedFromSource", {
name: res.name,
count: res.count,
source: displaySource,
prefix,
}));
if (statusMsg) return statusMsg.edit({ embeds: [successEmbed] });
return msg.reply({ embeds: [successEmbed] });
}
/* Case B: No URL — save tracks from the active queue */
if (!name && rawParts.length > 1) {
name = rawParts[1];
}
if (!name) {
const embed = new EmbedBuilder()
@@ -319,7 +486,18 @@ export async function run(msg, data) {
SUBCOMMAND: ADD
------------------------------------------------------------------------- */
if (sub === "add") {
let name = rawParts.length > 1 ? rawParts[1] : null;
let name = null;
let url = null;
/* Scan arguments for playlist name and optional URL */
for (let i = 1; i < rawParts.length; i++) {
const part = rawParts[i];
if (Utils.isValidUrl(part)) {
url = part;
} else if (!name) {
name = part;
}
}
if (!name) {
const embed = new EmbedBuilder()
@@ -328,6 +506,47 @@ export async function run(msg, data) {
return msg.reply({ embeds: [embed] });
}
/* Case A: Adding from URL (Spotify, YouTube, SoundCloud, Apple Music) */
if (url) {
const resolved = await resolveExternalPlaylist(this, url);
if (resolved.tracks.length === 0) {
const embed = new EmbedBuilder()
.setColor(COLOR_ERROR)
.setDescription(this.t(msg, "responses.playlist.noTracksFromSource"));
return msg.reply({ embeds: [embed] });
}
const res = await pm.addTracksToPlaylist(userId, name, resolved.tracks);
if (!res.success) {
if (res.error === "NOT_FOUND") {
const embed = new EmbedBuilder()
.setColor(COLOR_ERROR)
.setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix }));
return msg.reply({ embeds: [embed] });
}
if (res.error === "PLAYLIST_FULL") {
const embed = new EmbedBuilder()
.setColor(COLOR_ERROR)
.setDescription(this.t(msg, "responses.playlist.playlistFull", { max: MAX_TRACKS_PER_PLAYLIST }));
return msg.reply({ embeds: [embed] });
}
const embed = new EmbedBuilder()
.setColor(COLOR_ERROR)
.setDescription(this.t(msg, "responses.playlist.addFailed"));
return msg.reply({ embeds: [embed] });
}
const embed = new EmbedBuilder()
.setColor(COLOR_SUCCESS)
.setDescription(this.t(msg, "responses.playlist.tracksAdded", {
name: res.name,
addedCount: res.addedCount,
count: res.count,
}));
return msg.reply({ embeds: [embed] });
}
/* Case B: Adding currently playing track */
const p = await this.getPlayer(msg, false, false, false);
const current = p?.queue?.getCurrent();