/** * @module commands/autoplay * @description Toggle autoplay mode — automatically keeps the music going when the queue ends. */ import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; import { logger } from "../src/constants/Logger.mjs"; /** @type {CommandBuilder} @description Command definition for the autoplay command. */ export const command = new CommandBuilder() .setName("autoplay") .setDescription("Toggle autoplay — automatically play similar tracks when the queue ends.", "commands.autoplay") .setCategory("music") .addAliases("ap"); /** Max number of upcoming tracks the pre-filler keeps in the queue. */ const QUEUE_KEEP_AHEAD = 2; /** How many candidate results are considered for random picking. */ const PICK_POOL = 8; /** Tracks considered "recently played" and excluded from re-picking. */ const HISTORY_SIZE = 30; /** Sanity bounds for candidate durations (ms) — skip hour-long mixes and jingles. */ const MIN_DURATION_MS = 45_000; const MAX_DURATION_MS = 15 * 60_000; /** * Extract a YouTube video ID from a track's videoId field or URL. * @param {object} t - Internal track object. * @returns {string|null} Video ID, or null if unavailable. */ function extractVideoId(t) { if (!t) return null; if (t.videoId && /^[A-Za-z0-9_-]{6,20}$/.test(t.videoId)) return t.videoId; const url = typeof t.url === "string" ? t.url : ""; const m = url.match(/[?&]v=([A-Za-z0-9_-]{6,20})/) ?? url.match(/youtu\.be\/([A-Za-z0-9_-]{6,20})/); return m ? m[1] : null; } /** * Record a track in the player's autoplay history so it is not picked again soon. * @param {object} p - The player instance. * @param {object} track - The internal track object. * @returns {void} */ function rememberTrack(p, track) { const vid = extractVideoId(track); const title = String(track?.title ?? "").toLowerCase().trim(); p._autoplayHistory = (p._autoplayHistory ?? []).filter(h => h.vid !== vid || !vid); if (vid) p._autoplayHistory.push({ vid, title }); if (p._autoplayHistory.length > HISTORY_SIZE) { p._autoplayHistory.splice(0, p._autoplayHistory.length - HISTORY_SIZE); } } /** * Check whether a candidate track is acceptable: not recently played, sane duration. * @param {object} p - The player instance. * @param {object} t - Candidate internal track object. * @returns {boolean} True if the candidate is playable and not a recent repeat. */ function isCandidateOk(p, t) { if (!t) return false; const ms = Number(t._durationMs ?? t.duration?.seconds * 1000 ?? 0); if (ms && (ms < MIN_DURATION_MS || ms > MAX_DURATION_MS)) return false; const vid = extractVideoId(t); if (vid && (p._autoplayHistory ?? []).some(h => h.vid === vid)) return false; const title = String(t?.title ?? "").toLowerCase().trim(); if (title && (p._autoplayHistory ?? []).some(h => h.title && h.title === title)) return false; return true; } /** * Resolve a query via the player's Lavalink search and return a random acceptable * candidate from the top results. * @param {object} p - The player instance. * @param {string} query - The search query or URL. * @param {string} provider - Provider shorthand key ("yt", "ytm", ...). * @returns {Promise} An acceptable track, or null. */ async function pickFromQuery(p, query, provider = "ytm") { const resolved = await p.generalQuery({ query, provider }); const list = resolved?.type === "list" ? (resolved.data ?? []) : resolved?.type === "video" && resolved.data ? [resolved.data] : []; const ok = list.filter(t => isCandidateOk(p, t)); if (!ok.length) return null; return ok[Math.floor(Math.random() * Math.min(PICK_POOL, ok.length))]; } /** * Pick the next autoplay track using the strategy chain. * @param {object} p - The player instance. * @param {object} ctx - The bot context (needs .lastfm). * @param {object|null} lastTrack - The last played internal track. * @returns {Promise} The chosen track, or null if all strategies failed. */ async function pickAutoplayTrack(p, ctx, lastTrack) { const artist = lastTrack?.lastfm?.artist ?? lastTrack?.requestedArtist ?? lastTrack?.artist ?? lastTrack?.artists?.[0]?.name ?? null; const name = lastTrack?.lastfm?.name ?? lastTrack?.requestedTitle ?? lastTrack?.title ?? lastTrack?.name ?? null; const videoId = extractVideoId(lastTrack); if (videoId) { try { const mixUrl = `https://www.youtube.com/watch?v=${videoId}&list=RD${videoId}`; const track = await pickFromQuery(p, mixUrl, "yt"); if (track) return track; } catch (e) { logger.warn("[Autoplay] Mix strategy failed:", e?.message); } } const lf = ctx?.lastfm; if (lf?.enabled && artist && name) { try { const similar = await lf.getSimilarTracks(artist, name, 10); for (let i = 0; i < Math.min(4, similar.length); i++) { const pick = similar[Math.floor(Math.random() * Math.min(3, similar.length))]; const track = await pickFromQuery(p, `${pick.name} ${pick.artist}`.trim(), "ytm"); if (track) return track; } } catch (e) { logger.warn("[Autoplay] Last.fm strategy failed:", e?.message); } } if (artist) { try { const track = await pickFromQuery(p, `${artist} songs`, "ytm"); if (track) return track; } catch (e) { logger.warn("[Autoplay] Artist strategy failed:", e?.message); } } if (name) { try { const track = await pickFromQuery(p, `${name}`, "ytm"); if (track) return track; } catch (_) {} } return null; } /** * Fill the queue ahead while autoplay is enabled. Debounced and guarded so it * never runs concurrently or fights the queueEnd handler. * @param {object} p - The player instance. * @param {object} ctx - The bot context. * @returns {Promise} */ async function fillQueue(p, ctx) { if (!p._autoplay || p._destroyed || p._autoplayFilling) return; const current = p.queue?.getCurrent(); if (!current) return; // queueEnd handler owns the "nothing playing" case. const upcoming = p.queue?.data?.length ?? 0; if (upcoming >= QUEUE_KEEP_AHEAD) return; p._autoplayFilling = true; try { while (p._autoplay && !p._destroyed && (p.queue?.data?.length ?? 0) < QUEUE_KEEP_AHEAD) { const last = p.queue?.data?.at?.(-1) ?? p._lastPlayedTrack ?? current; const track = await pickAutoplayTrack(p, ctx, last); if (!track) break; rememberTrack(p, track); p.addToQueue(track, false); } } catch (e) { logger.warn("[Autoplay] Fill error:", e?.message); } finally { p._autoplayFilling = false; } } /** * Build the queueEnd handler: pick and immediately play a similar track. * @param {object} p - The player instance. * @param {object} ctx - The bot context. * @returns {Function} The handler. */ function buildQueueEndHandler(p, ctx) { return async () => { if (!p._autoplay || p._destroyed) return; if (p.queue?.getCurrent() || !(p.queue?.isEmpty?.() ?? true)) return; const lastTrack = p._lastPlayedTrack; if (!lastTrack) return; try { p._stopInactivityTimer(); rememberTrack(p, lastTrack); const track = await pickAutoplayTrack(p, ctx, lastTrack); if (track) { rememberTrack(p, track); p.addToQueue(track, false); if (!p.queue.getCurrent()) { p.playNext().catch(() => {}); } } else if (!p._is247Enabled()) { p._startInactivityTimer(); } } catch (err) { logger.warn("[Autoplay] Handler error:", err?.message); if (!p.queue?.getCurrent() && p.queue?.isEmpty() && !p._is247Enabled()) { p._startInactivityTimer(); } } }; } /** * Attach autoplay listeners (queueEnd + pre-fill hooks) to a player. * @param {object} p - The player instance. * @param {object} ctx - The bot context. * @returns {void} */ function attachAutoplay(p, ctx) { detachAutoplay(p); p._autoplayHandler = buildQueueEndHandler(p, ctx); p.on("queueEnd", p._autoplayHandler); p._autoplayFillHandler = () => { fillQueue(p, ctx).catch(() => {}); }; p.on("queue", p._autoplayFillHandler); p.on("update", p._autoplayFillHandler); p.on("playback", p._autoplayFillHandler); } /** * Remove all autoplay listeners from a player. * @param {object} p - The player instance. * @returns {void} */ function detachAutoplay(p) { if (p._autoplayHandler) { p.removeListener("queueEnd", p._autoplayHandler); p._autoplayHandler = null; } if (p._autoplayFillHandler) { p.removeListener("queue", p._autoplayFillHandler); p.removeListener("update", p._autoplayFillHandler); p.removeListener("playback", p._autoplayFillHandler); p._autoplayFillHandler = null; } } /** * Run handler for the autoplay command. * Toggles autoplay on the player. * @param {object} msg - The command message wrapper. * @param {object} data - Parsed command data (unused, no options required). * @returns {Promise} */ export async function run(msg, data) { const p = await this.getPlayer(msg, true, true, false); if (!p) return; p._autoplay = !p._autoplay; if (p._autoplay) { p._autoplayHistory = p._autoplayHistory ?? []; attachAutoplay(p, this); fillQueue(p, this).catch(() => {}); return msg.reply({ embeds: [new EmbedBuilder() .setColor(getGlobalColor()) .setDescription(this.t(msg, "responses.autoplay.enabled"))] }); } else { detachAutoplay(p); p._autoplayHistory = []; return msg.reply({ embeds: [new EmbedBuilder() .setColor(getGlobalColor()) .setDescription(this.t(msg, "responses.autoplay.disabled"))] }); } }