Add seek validation, autoplay system, progress bar & codebase cleanup

- Add seek duration validation — seeks beyond track length are rejected
  with clear error showing max allowed position
- Add autoplay system with Last.fm similar tracks + YouTube search
  fallback — automatically queues similar tracks when queue ends
- Add live progress bar to now playing with elapsed/total time display
- Add robust ffmpeg cleanup to prevent race conditions during
  seek/skip/filter operations
- Add proper queue advancement after seek so bot stays in voice
- Add queueEnd event emission on skip/skipTo for autoplay trigger
- Add _lastPlayedTrack preservation for autoplay recommendations
This commit is contained in:
NoLogicAlan committed 2026-05-21 02:04:05 +03:00
1 parent bc1fe82919
commit 0f2ee99f1e
23 files changed
+665 -170

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("autoplay")
.setDescription("Toggle autoplay — automatically play similar tracks when the queue ends.", "commands.autoplay")
.setCategory("music")
.addAliases("ap");
export async function run(msg, data) {
const prefix = this.handler?.getPrefix?.(msg.message?.guildId) ?? "%";
const p = await this.getPlayer(msg, true, true, false);
if (!p) return;
p._autoplay = !p._autoplay;
if (p._autoplay) {
if (!p._autoplayHandler) {
p._autoplayHandler = async () => {
if (!p._autoplay) return;
if (p.queue?.getCurrent() || !p.queue?.isEmpty()) return;
const lastTrack = p._lastPlayedTrack;
if (!lastTrack) return;
const artist = lastTrack.lastfm?.artist ?? lastTrack.requestedArtist ?? lastTrack.artist ?? lastTrack.artists?.[0]?.name;
const name = lastTrack.lastfm?.name ?? lastTrack.requestedTitle ?? lastTrack.title ?? lastTrack.name;
try {
p._stopInactivityTimer();
let query = null;
const lf = this.lastfm;
if (lf?.enabled && artist && name) {
try {
const similar = await lf.getSimilarTracks(artist, name, 5);
if (similar.length) {
const pick = similar[Math.floor(Math.random() * Math.min(3, similar.length))];
query = `${pick.name} ${pick.artist}`.trim();
}
} catch (_) {
}
}
if (!query) {
if (artist && name) {
query = `${artist} music`;
} else if (name) {
query = `${name} similar`;
} else {
if (!p._is247Enabled()) {
p._startInactivityTimer();
}
return;
}
}
const resolved = await p.workerJob("generalQuery", {
query,
provider: "yt",
});
let track = null;
if (resolved?.type === "video" && resolved.data) {
track = resolved.data;
} else if (resolved?.type === "list" && resolved.data?.length) {
const idx = Math.floor(Math.random() * Math.min(5, resolved.data.length));
track = resolved.data[idx];
}
if (track) {
p.addToQueue(track, false);
if (!p.queue.getCurrent()) {
p.playNext().catch(() => {});
}
} else {
if (!p._is247Enabled()) {
p._startInactivityTimer();
}
}
} catch (err) {
if (!p.queue?.getCurrent() && p.queue?.isEmpty() && !p._is247Enabled()) {
p._startInactivityTimer();
}
}
};
p.on("queueEnd", p._autoplayHandler);
}
const lfStatus = this.lastfm?.enabled ? " with Last.fm recommendations" : " using YouTube search";
return msg.reply({
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(`🔁 Autoplay **enabled**${lfStatus} — similar tracks will be added automatically when the queue ends.`)]
});
} else {
if (p._autoplayHandler) {
p.removeListener("queueEnd", p._autoplayHandler);
p._autoplayHandler = null;
}
return msg.reply({
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(`➡️ Autoplay **disabled** — the bot will stop when the queue ends.`)]
});
}
}
-16
View File
@@ -368,23 +368,7 @@ export async function run(msg) {
const filter = FILTERS.find(f => f.emoji === emoji);
if (!filter) return;
const track = player.queue.getCurrent();
const previousActiveKeys = [...activeKeys];
if (!track && false) {
await menuMsg.edit({
embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, null)]
}).catch(() => {});
const errEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(this.t(msg, "responses.filter.nothingPlaying"))
;
await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {});
await Utils.sleep(1000);
await menuMsg.edit({
embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, null)]
}).catch(() => {});
return;
}
if (filter.key === "off") {
activeKeys = [];
+98 -5
View File
@@ -14,7 +14,7 @@ export const command = new CommandBuilder()
.addChoiceOption(o =>
o.setName("action")
.setDescription("The action to perform: link, unlink, np, profile, loved, top, recent, playlists, play, scrobble, leaderboard", "options.lastfm.action")
.addChoices("link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", "playlists", "play", "scrobble", "leaderboard", "lb")
.addChoices("link", "confirm", "unlink", "np", "profile", "loved", "top", "recent", "playlists", "play", "scrobble", "leaderboard", "lb", "love", "unlove", "artists")
.setRequired(false)
)
.addTextOption(o =>
@@ -23,7 +23,6 @@ export const command = new CommandBuilder()
.setRequired(false)
);
function notConfigured(msg) {
return {
embeds: [new EmbedBuilder()
@@ -255,7 +254,6 @@ function parsePlayArgs(msg, data) {
return { category: "" };
}
export async function run(msg, data) {
const lastfm = this.lastfm;
if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(msg));
@@ -689,6 +687,100 @@ export async function run(msg, data) {
return msg.reply({ embeds: [buildTrackList(user.username, "🕐 Recent Tracks", tracks, false, prefix)] });
}
case "artists": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
let artists;
try {
artists = await lastfm.getTopArtists(userId, "overall", 15);
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to fetch top artists: ${err.message}`)]
});
}
if (!artists.length) {
return msg.reply({
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🎤 No top artists found for **${user.username}**.`)]
});
}
const lines = artists.map((a, i) => {
const num = String(i + 1).padStart(2, " ");
let name = a.name;
if (name.length > 40) name = name.slice(0, 37) + "...";
const link = a.url ? `[${name}](${a.url})` : name;
return `\`${num}.\` ${link} — **${a.playcount}** plays`;
});
const desc = lines.join("\n").slice(0, 4096);
return msg.reply({
embeds: [new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle(`🎤 Top Artists — ${user.username}`)
.setDescription(desc)
.setFooter({ text: `💡 Use ${prefix}lastfm play top to play your top tracks!` })]
});
}
case "love": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
const pLove = await this.getPlayer(msg, false, false, false);
if (!pLove) return;
const track = pLove.queue?.getCurrent();
if (!track) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Nothing is playing right now. Play a song first to love it!`)]
});
}
const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? "Unknown";
const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown";
try {
await lastfm.loveTrack(userId, artist, name);
return msg.reply({
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`❤️ Loved **${name}** by **${artist}** on Last.fm!`)]
});
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to love track: ${err.message}`)]
});
}
}
case "unlove": {
const user = await lastfm.getUser(userId);
if (!user) return msg.reply(notLinked(prefix));
const pUnlove = await this.getPlayer(msg, false, false, false);
if (!pUnlove) return;
const track = pUnlove.queue?.getCurrent();
if (!track) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Nothing is playing right now. Play a song first to unlove it!`)]
});
}
const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? "Unknown";
const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown";
try {
await lastfm.unloveTrack(userId, artist, name);
return msg.reply({
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`💔 Unloved **${name}** by **${artist}** on Last.fm.`)]
});
} catch (err) {
return msg.reply({
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to unlove track: ${err.message}`)]
});
}
}
default:
return msg.reply({
embeds: [new EmbedBuilder()
@@ -703,9 +795,12 @@ export async function run(msg, data) {
`\`${prefix}lastfm profile\` — View your Last.fm profile`,
`\`${prefix}lastfm loved\` — View your loved tracks`,
`\`${prefix}lastfm top\` — View your top tracks`,
`\`${prefix}lastfm artists\` — View your top artists`,
`\`${prefix}lastfm recent\` — View your recent tracks`,
`\`${prefix}lastfm playlists\` — View your Last.fm playlists`,
`\`${prefix}lastfm leaderboard\` — Scrobble leaderboard`,
`\`${prefix}lastfm love\` — Love the current track`,
`\`${prefix}lastfm unlove\` — Unlove the current track`,
``,
`🎶 **Play from Last.fm:**`,
`\`${prefix}lastfm play loved\` — Play your loved tracks`,
@@ -732,7 +827,6 @@ export async function run(msg, data) {
}
}
function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") {
const lines = tracks.map((t, i) => {
const num = String(i + 1).padStart(2, " ");
@@ -752,7 +846,6 @@ function buildTrackList(username, title, tracks, showPlaycount = false, prefix =
.setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` });
}
function buildLeaderboardEmbed(lb, pageIdx, prefix) {
const MEDALS = ["🥇", "🥈", "🥉"];
const startRank = pageIdx * lb.perPage;
+28
View File
@@ -0,0 +1,28 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
export const command = new CommandBuilder()
.setName("move")
.setDescription("Move a track from one position to another in the queue.", "commands.move")
.setCategory("music")
.addAliases("mv", "m")
.addNumberOption(o =>
o.setName("from")
.setDescription("The current position of the track in the queue. You can view the indices with the 'list' command.", "options.move.from")
.setRequired(true)
)
.addNumberOption(o =>
o.setName("to")
.setDescription("The target position to move the track to in the queue.", "options.move.to")
.setRequired(true)
);
export async function run(message, data) {
const p = await this.getPlayer(message, false, false, false);
if (!p) return;
const from = data.get("from")?.value;
const to = data.get("to")?.value;
if (from == null || from < 1) return message.replyEmbed("Source position must be 1 or greater.");
if (to == null || to < 1) return message.replyEmbed("Target position must be 1 or greater.");
const res = p.move(from, to);
message.replyEmbed(res);
}
+91
View File
@@ -0,0 +1,91 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("seek")
.setDescription("Seek to a specific position in the current track.", "commands.seek")
.setCategory("music")
.addTextOption(o =>
o.setName("position")
.setDescription("Position to seek to (e.g. 1:30, 90, or 1:30:00 for hours)")
.setRequired(true)
);
export async function run(msg, data) {
const positionInput = data.get("position")?.value;
const p = await this.getPlayer(msg, true, true, false);
if (!p) return;
if (!p.queue?.getCurrent()) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ There's nothing playing at the moment!")] });
}
if (p._paused) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Can't seek while paused. Resume first.")] });
}
let seekMs = parseSeekPosition(positionInput);
if (seekMs === null || seekMs < 0) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Invalid position format. Use \`mm:ss\`, \`hh:mm:ss\`, or seconds (e.g. \`1:30\`, \`90\`, \`0:30\`).`)] });
}
const trackDuration = p._getTrackDurationMs(p.queue.getCurrent());
if (trackDuration > 0 && seekMs >= trackDuration) {
const maxStr = formatDuration(trackDuration);
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Position exceeds track duration (**${maxStr}**). Use a value between \`0:00\` and \`${maxStr}\`.`)] });
}
try {
const result = await p.seekToPosition(seekMs);
if (result) {
const seekStr = formatDuration(seekMs);
const totalStr = trackDuration > 0 ? formatDuration(trackDuration) : "∞";
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`⏩ Seeked to **${seekStr}** / ${totalStr}`)] });
} else {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription("❌ Seeking is not supported by the current audio node.")] });
}
} catch (err) {
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Failed to seek: ${err.message}`)] });
}
}
function parseSeekPosition(str) {
if (!str || typeof str !== "string") return null;
str = str.trim();
if (/^\d+$/.test(str)) {
return parseInt(str, 10) * 1000;
}
const parts = str.split(":").map(Number);
if (parts.some(isNaN)) return null;
if (parts.length === 2) {
const [minutes, seconds] = parts;
if (seconds >= 60) return null;
return (minutes * 60 + seconds) * 1000;
}
if (parts.length === 3) {
const [hours, minutes, seconds] = parts;
if (minutes >= 60 || seconds >= 60) return null;
return (hours * 3600 + minutes * 60 + seconds) * 1000;
}
return null;
}
function formatDuration(ms) {
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) {
return `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
}
return `${minutes}:${String(seconds).padStart(2, "0")}`;
}
-7
View File
@@ -29,7 +29,6 @@ function richEmbed(fields, opts = {}) {
return { embeds: [raw] };
}
const SHORTCUTS = {
prefix: "prefix",
pfx: "prefix",
@@ -51,7 +50,6 @@ const VOLUME_MIN = 1;
const VOLUME_MAX = 200;
const MAX_247_CHANNELS = 10;
/** Extract clean numeric channel ID from any format */
function cleanId(raw) {
return String(raw).replace(/\D/g, "");
@@ -99,7 +97,6 @@ function getGuildName(message) {
return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server";
}
/**
* Get the 24/7 mode for a specific channel.
* Reads from the per-channel map (stay_247_modes) first,
@@ -521,7 +518,6 @@ async function handle247(ctx, message, value) {
}
}
/**
* Validate and save a setting value.
* @returns {string|null} Error message string, or null on success.
@@ -582,7 +578,6 @@ async function applySet(ctx, message, set, key, rawValue) {
return null;
}
async function handleShortcut(ctx, message, settingKey, valueTokens) {
const set = ctx.getSettings(message);
@@ -605,7 +600,6 @@ async function handleShortcut(ctx, message, settingKey, valueTokens) {
}
}
export const command = function() {
if (this.locale) {
VALID_LOCALES = this.locale.availableLocales();
@@ -702,7 +696,6 @@ export const command = function() {
);
};
export async function run(message, data) {
const set = this.getSettings(message);
const cmd = data.commandId || "getSettings";
-4
View File
@@ -9,7 +9,6 @@ export const command = new CommandBuilder()
.addAliases("info")
.setCategory("util");
const CACHE_TTL_MS = 5 * 60 * 1000;
let cachedUserCount = null;
@@ -96,7 +95,6 @@ function getLivePlayerCount(playerMap) {
return live;
}
let cachedGuildCount = null;
let guildCacheExpiresAt = 0;
@@ -131,7 +129,6 @@ async function getGuildCount(client) {
}
}
function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, linkedUsers, ping, uptime, comHash, comLink, reason, footer, loading, lastfmEnabled }) {
const num = (v) => Utils.formatNumber(v);
const ld = (v) => loading ? "..." : v;
@@ -169,7 +166,6 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount,
return builder;
}
export async function run(message) {
const lastfm = this.lastfm;
const lastfmEnabled = lastfm?.enabled ?? false;
-2
View File
@@ -34,7 +34,6 @@ export const command = new CommandBuilder()
.setRequired(false)
);
function notConfigured(prefix) {
return {
embeds: [new EmbedBuilder()
@@ -95,7 +94,6 @@ function buildVotersEmbed(voters, total, page, limit, type, resourceId, expired
return { embeds: [embed] };
}
export async function run(msg, data) {
const fluxerlist = this.fluxerlist;
const prefix = this.handler?.getPrefix?.(msg.message?.guildId) ?? "%";