initial push to remix-bot/fluxer

This commit is contained in:
NoLogicAlan committed 2026-04-14 02:23:18 +03:00
commit 2820cc881c
63 files changed
+16005

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("clear")
.setDescription("Remove all songs from the queue.", "commands.clear")
.addAliases("c")
.setCategory("music");
export async function run(msg) {
const p = await this.getPlayer(msg, false, false, false);
if (!p) return;
p.clear();
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription("🗑️ Queue cleared.")
.toJSON();
msg.replyEmbed({ embeds: [embed] });
}
+38
View File
@@ -0,0 +1,38 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("debug")
.setDescription("A debug command for various purposes.")
.setRequirement(r => r.setOwnerOnly(true))
.setCategory("util")
.addChoiceOption(o =>
o.setName("target")
.setDescription("The target that should be examined.")
.addChoices("voice")
.setRequired(true));
export function run(msg, data) {
switch (data.get("target").value) {
case "voice": {
const servers = [...this.players.playerMap.entries()].map(([cid, s]) => {
const channel = this.client.channels.cache.get(cid);
return {
name: channel?.name ?? "unknown",
id: channel?.id ?? cid,
status: s.connection?.state?.status ?? "unknown",
guildname: channel?.guild?.name ?? "unknown",
guildid: channel?.guildId ?? "unknown"
};
});
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle("🔧 Voice Debug")
.setDescription("```json\n" + JSON.stringify(servers, null, 2) + "\n```")
.toJSON();
msg.replyEmbed({ embeds: [embed] });
break;
}
}
}
+214
View File
@@ -0,0 +1,214 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
import { inspect } from "node:util";
// Auto-remove timer: 1 minute
const EMOJI_REMOVE_TIMEOUT = 60000;
/**
* List of keys that should be redacted from objects before displaying in Discord.
*/
const RESTRICTED = [
"token",
"config",
"key",
"clientSecret",
"clientId",
"password",
"secret",
"authorization"
];
function hasSensitive(obj, level = 0) {
if (level >= 3 || typeof obj !== "object" || obj === null) return false;
for (const key in obj) {
if (RESTRICTED.some(r => key.toLowerCase().includes(r))) return true;
if (typeof obj[key] === "object" && hasSensitive(obj[key], level + 1)) return true;
}
return false;
}
function removeSensitive(obj, level = 0) {
if (level >= 3 || typeof obj !== "object" || obj === null) return obj;
const isArray = Array.isArray(obj);
const newObj = isArray ? [...obj] : { ...obj };
let modified = false;
for (const key in newObj) {
const isSensitive = !isArray && RESTRICTED.some(r => key.toLowerCase().includes(r));
if (isSensitive) {
newObj[key] = "[REDACTED]";
modified = true;
} else if (typeof newObj[key] === "object" && newObj[key] !== null) {
const cleaned = removeSensitive(newObj[key], level + 1);
if (cleaned !== newObj[key]) {
newObj[key] = cleaned;
modified = true;
}
}
}
return modified ? newObj : obj;
}
async function clean(value) {
if (value instanceof Promise) value = await value;
if (typeof value === "object" && value !== null) {
if (hasSensitive(value)) {
value = removeSensitive(value);
}
}
let output;
try {
output = typeof value === "string" ? value : inspect(value, { depth: 1, compact: false });
} catch (err) {
output = `[Inspection Error]: ${err.message}`;
}
return output
.replace(/`/g, "`\u200b")
.replace(/@/g, "@\u200b") || "undefined"; // Fallback if output is empty
}
/**
* Executes the code and returns the raw data instead of a formatted string,
* so we can paginate it inside Embeds later.
*/
async function runEval(expression, context) {
const start = Date.now();
let result, isError = false, type = "undefined";
try {
result = await eval(`(async function() { ${expression} })`).call(context);
type = result === null ? "null" : typeof result;
} catch (e) {
result = e;
isError = true;
type = "error";
}
const elapsed = Date.now() - start;
const output = await clean(result);
return { output, isError, type, elapsed };
}
export const command = new CommandBuilder()
.setName("eval")
.setDescription("Evaluates JavaScript code (Owner Only).")
.setRequirement(r => r.setOwnerOnly(true))
.setCategory("util")
.addTextOption(o =>
o.setName("expression")
.setDescription("The JavaScript expression to evaluate")
.setRequired(true)
);
export async function run(msg, data) {
const expression = data.get("expression").value;
const context = Object.assign({ message: msg }, this);
// 1. Run the evaluation
const { output, isError, type, elapsed } = await runEval(expression, context);
// 2. Chunk the output to bypass Discord limits (Max embed description is 4096 chars)
// We use 3800 to leave room for the header and markdown formatting
const chunkSize = 3800;
const chunks = [];
for (let i = 0; i < output.length; i += chunkSize) {
chunks.push(output.slice(i, i + chunkSize));
}
const totalPages = chunks.length;
let currentPage = 0;
// Helper to build the specific embed page
const buildPageContent = (pageIdx, expired = false) => {
const icon = isError ? "❌" : "✅";
const title = `${icon} Eval Result`;
// Embed description includes the metadata and the codeblock
const desc = `**Type:** \`${type}\` • **Time:** \`${elapsed}ms\`\n\`\`\`js\n${chunks[pageIdx]}\n\`\`\``;
// Customize footer based on state
let footerText = `Page ${pageIdx + 1}/${totalPages}`;
if (expired) footerText = "⌛ Controls expired";
else if (totalPages > 1) footerText += " • ⬅️ ➡️ Navigate • ❌ Delete";
else footerText += " • ❌ Delete";
const embed = new EmbedBuilder()
.setColor(isError ? "#ff0000" : getGlobalColor()) // Red if error, default otherwise
.setTitle(title)
.setDescription(desc)
.setFooter({ text: footerText })
.toJSON();
return { embeds: [embed] };
};
// 3. Send the initial message using the wrapper
const replyMsg = await msg.replyEmbed(buildPageContent(0));
if (!replyMsg?.message) return;
// 4. Setup React UI
// If it's only 1 page, we just show the Delete button. Otherwise, add arrows.
const navEmojis = totalPages > 1 ? ["⬅️", "➡️", "❌"] : ["❌"];
let unobserve = null;
let emojiTimeout = null;
for (const emoji of navEmojis) {
await replyMsg.message.react(emoji).catch(() => {});
}
// Helper: Clear reactions when time runs out
const clearReactions = async () => {
try {
await replyMsg.message.removeAllReactions();
} catch (e) {
for (const emoji of navEmojis) {
try {
await replyMsg.message.removeReaction(emoji);
} catch (_) {}
}
}
};
// Helper: Reset inactivity timer
const resetTimer = () => {
clearTimeout(emojiTimeout);
emojiTimeout = setTimeout(async () => {
if (unobserve) unobserve();
await clearReactions();
await replyMsg.editEmbed(buildPageContent(currentPage, true)).catch(() => {});
}, EMOJI_REMOVE_TIMEOUT);
};
// 5. Start listening for reactions
unobserve = replyMsg.onReaction(navEmojis, async (e) => {
// Handle specific actions
if (e.emoji_id === "❌") {
// Clean up and delete the message
clearTimeout(emojiTimeout);
if (unobserve) unobserve();
await replyMsg.message.delete().catch(() => {});
return; // Exit completely
}
resetTimer();
if (e.emoji_id === "⬅️") {
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
} else if (e.emoji_id === "➡️") {
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
}
// Update Embed
await replyMsg.editEmbed(buildPageContent(currentPage)).catch(() => {});
});
resetTimer();
}
+31
View File
@@ -0,0 +1,31 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("forceleave")
.addAlias("fl")
.setDescription("Make Remix leave a channel even if you're not in it.")
.setRequirement(r => r.addPermission("ManageChannels"))
.setCategory("music")
.addChannelOption(o =>
o.setName("channelId")
.setDescription("The channel that should be left.")
.setRequired(true)
);
function embed(desc) {
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] };
}
export async function run(msg, data) {
const cid = data.get("channelId").value;
const targetChannel = this.client.channels.cache.get(cid);
if (!targetChannel) return msg.replyEmbed(embed("❌ Channel not found."));
if (msg.message.guildId !== targetChannel.guildId)
return msg.replyEmbed(embed("❌ This command has to be run in the same server as the voice channel."));
const p = this.players.playerMap.get(cid);
if (!p) return msg.replyEmbed(embed("❌ Player not found."));
if (!p.connection) return msg.replyEmbed(embed("❌ Player not initialized."));
this.players.leave(msg, cid);
}
+32
View File
@@ -0,0 +1,32 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("invite")
.setDescription("Get the invite link for Remix and the support server.", "commands.invite")
.addAliases("addbot", "remix")
.setCategory("util");
export async function run(message) {
const description =
"Add Remix to your server directly from [FluxerList](<https://fluxerlist.com/bots/remix>).\n\n" +
"Join our community at [fluxer.gg/remix](https://fluxer.gg/remix) for support, updates, and direct feedback.";
const botUser = message.handler.client.user;
const botIcon = botUser?.displayAvatarURL?.() || null;
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setAuthor({
name: "Invite Remix",
iconURL: botIcon
})
.setDescription(description)
.toJSON();
await message.replyEmbed({
embeds: [embed]
});
}
+121
View File
@@ -0,0 +1,121 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
import Player from "../src/Player.mjs";
export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
if (!this.client.channels.cache.has(cid)) {
ecb();
const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription("Couldn't find the channel `" + cid + "`\nUse the help command to learn more about this. (`%help join`)")
.toJSON();
return message.replyEmbed({ embeds: [embed] });
}
if (this.players.playerMap.has(cid)) {
cb(this.players.playerMap.get(cid));
const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription("Already joined <#" + cid + ">.")
.toJSON();
return message.replyEmbed({ embeds: [embed] });
}
// Guard: moonlink must be ready before we can play anything
if (!this.moonlink) {
const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription("⚠️ Audio node is still connecting — please try again in a few seconds.")
.toJSON();
ecb();
return message.replyEmbed({ embeds: [embed] });
}
const p = new Player(this.config.token, {
client: this.client,
config: this.config,
nodelink: this.config.nodelink,
moonlink: this.moonlink ?? null,
messageChannel: message.channel,
settingsMgr: this.settingsMgr ?? this.settings ?? null,
observedVoiceUsers: this.observedVoiceUsers ?? null,
});
p.on("autoleave", () => {
const guildId = message.channel?.guildId
?? message.channel?.guild?.id
?? message.message?.guildId
?? message.channel?.server_id
?? message.channel?.serverId;
const is247 = (() => {
try {
const raw = this.settingsMgr?.getServer?.(guildId)?.get?.("stay_247");
return raw && raw !== "none";
} catch (_) { return false; }
})();
const prefix = (() => {
try {
return this._commands?.getPrefix?.(message.channel?.guild?.id) ?? "%";
} catch (_) { return "%"; }
})();
const desc = is247
? `Left channel <#${cid}> because of inactivity.`
: `Left channel <#${cid}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``;
const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription(desc)
.toJSON();
message.channel.sendEmbed({ embeds: [embed] });
this.players.playerMap.delete(cid);
p.destroy();
});
p.on("message", m => {
const guildId = message.channel?.guild?.id ?? message.channel?.server_id ?? message.channel?.serverId;
const raw = this.settingsMgr?.getServer?.(guildId)?.get("songAnnouncements");
const disabled = raw === false || raw === 0 ||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
if (disabled) return;
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(m).toJSON();
message.channel.sendEmbed({ embeds: [embed] });
});
this.players.playerMap.set(cid, p);
const joiningEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription("⏳ Joining Channel...").toJSON();
const statusMsg = await message.replyEmbed({ embeds: [joiningEmbed] });
try {
await p.join(cid);
const okEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(`✅ Successfully joined <#${cid}>`).toJSON();
await statusMsg.editEmbed({ embeds: [okEmbed] });
cb(p);
} catch (e) {
this.players.playerMap.delete(cid);
p.destroy();
const errEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(`❌ Failed to join: ${e.message}`).toJSON();
await statusMsg.editEmbed({ embeds: [errEmbed] });
ecb(e);
}
}
export const command = new CommandBuilder()
.setName("join")
.setDescription("Make the bot join your voice channel, or specify one.", "commands.join")
.setId("join")
.setCategory("music");
export function run(message) {
// @fluxerjs/core Message has no .member property — voice channel detection
// is handled entirely by checkVoiceChannels() via the VoiceManager state map.
const cid = this.players.checkVoiceChannels(message);
if (!cid) {
const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription("❌ You're not in a voice channel. Please join one first.")
.toJSON();
return message.replyEmbed({ embeds: [embed] });
}
this.players.initPlayer(message, cid);
}
export const exportDef = {
name: "joinChannel",
object: joinChannel
};
+71
View File
@@ -0,0 +1,71 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { logger } from "../src/constants/Logger.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("leave")
.setDescription("Make the bot leave your current voice channel", "commands.leave")
.addAliases("l", "stop")
.setCategory("music");
function embed(desc) {
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] };
}
export async function run(msg) {
const guildId = msg.channel?.guild?.id ?? msg.message?.guildId;
const userChannelId = this.players.checkVoiceChannels(msg);
if (!userChannelId) return msg.replyEmbed(embed("⚠️ Please join a voice channel first."));
const cid = String(userChannelId).replace(/\D/g, "");
if (!this.players.playerMap.has(cid)) {
const guildChannels = [...this.players.playerMap.entries()]
.filter(([chId, p]) => p._guildId === guildId)
.map(([chId]) => `<#${chId}>`);
if (guildChannels.length === 0) return msg.replyEmbed(embed("I'm not in a voice channel."));
if (guildChannels.length === 1) return msg.replyEmbed(embed(`⚠️ Please join ${guildChannels[0]} to use this command.`));
return msg.replyEmbed(embed(
`⚠️ I'm playing in multiple channels! Please join one of them:\n` +
guildChannels.map(c => `• ${c}`).join("\n")
));
}
const player = this.players.playerMap.get(cid);
if (!player?.connection) return msg.replyEmbed(embed("Player not initialized."));
const set = this.getSettings(msg);
const raw = set?.get("stay_247");
const ch247 = (!raw || raw === "none")
? new Set()
: Array.isArray(raw)
? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean))
: new Set([String(raw).replace(/\D/g, "")]);
if (ch247.has(cid)) {
const mode = set?.get("stay_247_mode") ?? "auto";
this.markIntentionalLeave(cid);
this.players.playerMap.delete(cid);
await player.leave().catch(() => {});
player.destroy();
if (mode === "auto") {
msg.replyEmbed(embed(`✅ Successfully Left — rejoining <#${cid}> in 5 seconds.\nTo disable 24/7 mode permanently, use \`%247 off\`.`));
const leave247Delay = this.config?.timers?.leave247RejoinDelay ?? 5000;
setTimeout(() => {
if (this._spawnPlayer) {
this._spawnPlayer(guildId, cid).catch(e =>
logger.warn("[leave] 247 rejoin failed for", cid, e.message)
);
}
}, leave247Delay);
} else {
msg.replyEmbed(embed(`✅ Successfully Left.\nℹ️ 24/7 mode is **on** — bot won't rejoin automatically. Use \`%play\` to bring it back, or \`%247 off\` to fully disable.`));
}
} else {
await this.leaveChannel(cid, guildId, msg);
}
}
+91
View File
@@ -0,0 +1,91 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { QueuePaginator, getGlobalColor } from "../src/MessageHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
const PAGE_SIZE = 10;
const SESSION_MS = 30 * 1000;
export const command = new CommandBuilder()
.setName("list")
.setDescription("List the songs in the queue of your current voice channel.", "commands.list")
.setCategory("music")
.addAliases("queue", "q")
.addNumberOption(o =>
o.setName("page")
.setDescription("Page number to jump to.")
.setRequired(false)
);
export async function run(message, data) {
const p = await this.getPlayer(message);
if (!p) return;
const current = p.queue.getCurrent();
const totalTracks = p.queue.size();
if (!current && totalTracks === 0) {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription("📭 The queue is empty. Use `%play` to add songs!").toJSON();
return message.replyEmbed({ embeds: [embed] });
}
const totalPages = totalTracks > 0
? Math.max(1, Math.ceil(totalTracks / PAGE_SIZE))
: 1;
const pageVal = data.get("page")?.value;
const startPage = Math.max(1, Math.min((!pageVal || isNaN(pageVal)) ? 1 : pageVal, totalPages));
const buildEmbed = (page) => {
const safePage = (isNaN(page) || page < 1) ? 1 : Math.min(Math.floor(page), totalPages);
const loopState = p.queue.songLoop ? "🔂 Song" : p.queue.loop ? "🔁 Queue" : "🛑 Off";
let desc = "";
// ── Header: track count + remaining time ──────────────────────────────
const remaining = p.getQueueRemainingTime();
desc += `📋 **${totalTracks} track${totalTracks !== 1 ? "s" : ""} in queue** • ⏱️ \`${remaining}\`\n`;
// ── Now Playing block ─────────────────────────────────────────────────
if (current) {
const elapsed = p.getCurrentElapsedDuration();
const total = p.getCurrentDuration();
const link = current.spotifyUrl || current.url || "";
let title = current.title;
if (title.length > 50) title = title.slice(0, 47) + "...";
const titleFmt = link ? `[${title}](${link})` : title;
desc += `\n🎵 **Now Playing**\n`;
desc += `${titleFmt} • \`${elapsed} / ${total}\`\n`;
}
desc += `\n`;
// ── Queue list ────────────────────────────────────────────────────────
if (totalTracks === 0) {
desc += "_Queue is empty._";
} else {
const { items, start } = p.queue.getPage(safePage, PAGE_SIZE);
items.forEach((vid, i) => {
const index = String(start + i + 1).padStart(2, " ");
const dur = vid.duration ? p.getDuration(vid.duration) : "?:??";
const link = vid.spotifyUrl || vid.url || "";
let title = vid.title;
if (title.length > 45) title = title.slice(0, 42) + "...";
title = link ? `[${title}](${link})` : title;
desc += `\`${index}.\` ${title} • \`${dur}\`\n`;
});
}
return new EmbedBuilder()
.setColor(getGlobalColor())
.setAuthor({ name: "🎧 Queue" })
.setDescription(desc.trim())
.setFooter({ text: `Page ${safePage}/${totalPages} • ${loopState}` })
.toJSON();
};
new QueuePaginator(message, this.messages, this.client)
.setTimeout(SESSION_MS)
.send(buildEmbed, totalPages, startPage);
}
+24
View File
@@ -0,0 +1,24 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("login")
.setDescription("Confirm a login of your account on the website", "commands.login")
.setCategory("util")
.addStringOption(o =>
o.setName("id")
.setDescription("The id you got from logging in at the dashboard.", "options.login.id")
.setRequired(true));
export async function run(msg, data) {
const log = data.get("id").value;
const verified = await this.loadedModules.get("wb-dashboard").instance.login(log, msg.author);
const desc = (typeof verified === "string")
? "❌ Login failed! Reason: `" + verified + "`. If this is an error and the issue persists, please contact a team member through the server in my description."
: (verified === true)
? "✅ Login succeeded! You can continue to the webpage now."
: "⚠️ An unknown error occurred. Please contact a team member if this issue persists!";
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON();
msg.replyEmbed({ embeds: [embed] });
}
+24
View File
@@ -0,0 +1,24 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("loop")
.setDescription("Toggle the looping of your queue/song.", "commands.loop")
.setCategory("music")
.addChoiceOption(opt =>
opt.setName("type")
.addChoices("queue", "song")
.setDescription("Specifies what loop should be toggled.", "options.loop.type")
.setRequired(true));
export async function run(message, data) {
const p = await this.getPlayer(message);
if (!p) return;
const res = p.loop(data.get("type").value);
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(res)
.toJSON();
message.replyEmbed({ embeds: [embed] });
}
+176
View File
@@ -0,0 +1,176 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { logger } from "../src/constants/Logger.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
import { Utils } from "../src/Utils.mjs";
export const command = new CommandBuilder()
.setName("lyrics")
.setDescription("Display synced lyrics from NodeLink", "commands.lyrics")
.addAliases("lyric", "ly")
.setCategory("music");
const LOADING_FRAMES = ["◐", "◓", "◑", "◒"];
const EMOJI_REMOVE_TIMEOUT = 60_000;
const SESSION_MS = 180_000;
export async function run(message) {
const p = await this.getPlayer(message, false, false, false);
if (!p) return;
const current = p.queue.getCurrent();
if (!current) {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription("❌ There's nothing playing at the moment.").toJSON();
return message.replyEmbed({ embeds: [embed] });
}
// Animated loading spinner
let frame = 0;
const loadingMsg = await message.replyEmbed({ embeds: [
new EmbedBuilder().setColor(getGlobalColor())
.setDescription(`${LOADING_FRAMES[0]} Searching lyrics for **${Utils.truncate(current.title, 40)}**...`)
.toJSON()
] });
const loadingInterval = setInterval(() => {
frame = (frame + 1) % LOADING_FRAMES.length;
loadingMsg.editEmbed({ embeds: [
new EmbedBuilder().setColor(getGlobalColor())
.setDescription(`${LOADING_FRAMES[frame]} Searching lyrics for **${Utils.truncate(current.title, 40)}**...`)
.toJSON()
] }).catch(() => {});
}, 800);
try {
const result = await p.lyrics();
clearInterval(loadingInterval);
if (!result || !result.text) {
return loadingMsg.editEmbed({ embeds: [
new EmbedBuilder().setColor(getGlobalColor())
.setDescription(
`❌ No lyrics available for **${Utils.truncate(current.title, 40)}**.\n\n` +
`💡 NodeLink lyrics plugin may not have this track. Try a popular song!`
).toJSON()
] });
}
try { await loadingMsg.message.delete(); } catch {}
const syncIndicator = result.synced ? " ⏱️ Synced" : "";
const displayTitle = Utils.cleanTitle(current.title);
const artist = current.artists?.[0]?.name || current.author?.name || "Unknown Artist";
const lines = result.text.split("\n").filter(l => l.trim());
const totalLines = lines.length;
const LINES_PER_PAGE = 25;
const totalPages = Math.ceil(totalLines / LINES_PER_PAGE);
// Single page — no pagination needed
if (totalPages === 1) {
const singleEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle(`🎵 ${Utils.truncate(displayTitle, 50)}`)
.setDescription([
`by *${artist}*${syncIndicator}`,
``,
"```",
lines.join("\n"),
"```"
].join("\n"))
.setFooter({ text: `NodeLink • ${totalLines} lines` });
if (current.thumbnail) singleEmbed.setThumbnail(current.thumbnail);
return message.replyEmbed({ embeds: [singleEmbed.toJSON()] });
}
// Multi-page
const pages = [];
for (let i = 0; i < totalLines; i += LINES_PER_PAGE) {
pages.push(lines.slice(i, i + LINES_PER_PAGE).join("\n"));
}
let currentPage = 0;
let emojiRemoveTimeout;
const buildContent = (pageIdx, expired = false) => {
const b = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle(`🎵 ${Utils.truncate(displayTitle, 50)}`)
.setDescription([
`by *${artist}*${syncIndicator} • Page ${pageIdx + 1}/${totalPages}`,
``,
"```",
pages[pageIdx],
"```"
].join("\n"))
.setFooter({ text: expired
? `⌛ Controls expired • NodeLink • ${totalLines} lines`
: `NodeLink • ${totalLines} lines total` });
if (current.thumbnail) b.setThumbnail(current.thumbnail);
return { embeds: [b.toJSON()] };
};
const msg = await message.replyEmbed(buildContent(0));
if (!msg?.message) return;
const emojis = ["⬅️", "➡️"];
for (const emoji of emojis) {
await msg.message.react(emoji).catch(() => {});
}
const clearReactions = async () => {
try {
await msg.message.removeAllReactions();
} catch {
for (const emoji of emojis) {
await msg.message.removeReaction(emoji).catch(() => {});
}
}
};
const resetEmojiTimer = () => {
clearTimeout(emojiRemoveTimeout);
emojiRemoveTimeout = setTimeout(async () => {
await clearReactions();
msg.editEmbed(buildContent(currentPage, true)).catch(() => {});
}, EMOJI_REMOVE_TIMEOUT);
};
const unobserve = msg.onReaction(emojis, async (e) => {
resetEmojiTimer();
if (e.emoji_id === "⬅️") {
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
} else if (e.emoji_id === "➡️") {
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
}
msg.editEmbed(buildContent(currentPage)).catch(() => {});
});
resetEmojiTimer();
// Full session close after SESSION_MS
setTimeout(() => {
clearTimeout(emojiRemoveTimeout);
unobserve();
const closedEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle(`🎵 ${Utils.truncate(displayTitle, 50)}`)
.setDescription([
`by *${artist}*${syncIndicator} • Page ${currentPage + 1}/${totalPages}`,
``,
"```",
pages[currentPage],
"```"
].join("\n"))
.setFooter({ text: `Session closed • NodeLink • ${totalLines} lines` });
if (current.thumbnail) closedEmbed.setThumbnail(current.thumbnail);
msg.editEmbed({ embeds: [closedEmbed.toJSON()] }).catch(() => {});
}, SESSION_MS);
} catch (err) {
clearInterval(loadingInterval);
logger.error("[Lyrics Command] Error:", err);
loadingMsg.editEmbed({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`❌ Error: ${Utils.truncate(err.message, 100)}`).toJSON()] }).catch(() => {});
}
}
+28
View File
@@ -0,0 +1,28 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("np")
.setDescription("Request the name and url of the currently playing song.", "commands.np")
.addAliases("current", "nowplaying");
export async function run(msg) {
const p = await this.getPlayer(msg);
if (!p) return;
const loadingEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription("⏳ Loading...")
.toJSON();
const loadingMsg = await msg.replyEmbed({ embeds: [loadingEmbed] });
const data = await p.nowPlaying();
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(data.msg);
if (data.image) embed.setThumbnail(data.image);
loadingMsg.editEmbed({ embeds: [embed.toJSON()] }).catch(() => {});
}
+19
View File
@@ -0,0 +1,19 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("pause")
.setDescription("Pause the playback in your voice channel", "commands.pause")
.setCategory("music");
export async function run(message) {
const p = await this.getPlayer(message);
if (!p) return;
const res = p.pause();
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(res)
.toJSON();
message.replyEmbed({ embeds: [embed] });
}
+68
View File
@@ -0,0 +1,68 @@
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";
function parseInlineProvider(raw) {
const match = raw.match(/^([a-z]+):\s*(.+)$/i);
if (!match) return { provider: null, query: raw.trim() };
const maybeProvider = match[1].toLowerCase();
if (PROVIDER_CHOICES.includes(maybeProvider)) {
return { provider: maybeProvider, query: match[2].trim() };
}
return { provider: null, query: raw.trim() };
}
export const command = new CommandBuilder()
.setName("play")
.setId("play")
.setCategory("music")
.setDescription(
"Play a song or playlist from a URL or search query.\n" +
"Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and more.\n" +
"Default search: YouTube Music. Use `-p <provider>` or inline prefix e.g. `sp: blinding lights`.",
"commands.play"
)
.addExamples(
"$prefixplay take over league of legends",
"$prefixplay sp: blinding lights",
"$prefixplay dz: get lucky",
"$prefixplay -p yt take over league of legends",
"$prefixplay https://open.spotify.com/track/...",
"$prefixp take over league of legends"
)
.addTextOption(option =>
option.setName("query")
.setDescription("A search query, URL, or provider-prefixed query like `sp: song name`.", "options.play.query")
.setRequired(true)
)
.addChoiceOption(o =>
o.setName("provider")
.setDescription("The search provider. Default: YouTube Music. Or use inline prefix: sp:, dz:, am:, yt:, sc: etc.", "options.play.provider")
.addFlagAliases("p", "u", "use")
.addChoices(...PROVIDER_CHOICES)
.setDefault("yt")
, true)
.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";
const searchEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription("🔍 Searching...")
.toJSON();
const statusMsg = await message.replyEmbed({ embeds: [searchEmbed] });
const messages = p.play(query, false, provider);
messages.on("message", d => {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d).toJSON();
statusMsg.editEmbed({ embeds: [embed] }).catch(() => {});
});
}
+490
View File
@@ -0,0 +1,490 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { Utils } from "../src/Utils.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("player")
.setDescription("Create an interactive player control panel with live progress", "commands.player")
.setCategory("music");
// Visual states
const STATES = {
playing: "🎵",
paused: "⏸️",
stopped: "🔇",
loading: "⏳"
};
// Control layout
const CONTROLS = {
prev: { emoji: "⏮️", action: "previous", desc: "Previous" },
play: { emoji: "▶️", action: "resume", desc: "Play" },
pause: { emoji: "⏸️", action: "pause", desc: "Pause" },
stop: { emoji: "⏹️", action: "stop", desc: "Stop" },
next: { emoji: "⏭️", action: "skip", desc: "Skip" },
loop: { emoji: "🔁", action: "loop", desc: "Loop" },
shuffle: { emoji: "🔀", action: "shuffle", desc: "Shuffle" },
volDown: { emoji: "🔉", action: "voldown", desc: "Volume Down" },
volUp: { emoji: "🔊", action: "volup", desc: "Volume Up" },
lyrics: { emoji: "📜", action: "lyrics", desc: "Lyrics" },
close: { emoji: "❌", action: "close", desc: "Close" }
};
// Progress bar characters
const PROGRESS = {
filled: "▰",
empty: "▱",
indicator: "●",
start: "▏",
end: "▕"
};
// Auto-remove timer: 1 minute
const EMOJI_REMOVE_TIMEOUT = 60000;
export async function run(msg) {
const player = await this.getPlayer(msg, false, false, false);
if (!player) return;
const timeout = this.config?.timers?.playerSessionTimeout ?? this.config.playerAFKTimeout ?? 300000;
const controlsLayout = [
[CONTROLS.prev, CONTROLS.play, CONTROLS.pause, CONTROLS.stop, CONTROLS.next],
[CONTROLS.loop, CONTROLS.shuffle, CONTROLS.volDown, CONTROLS.volUp, CONTROLS.lyrics],
[CONTROLS.close]
];
const allControls = controlsLayout.flat();
const controlEmojis = allControls.map(c => c.emoji);
const buildEmbed = (state = {}) => {
const current = player.queue.getCurrent();
const isPlaying = !player.paused && current;
const statusEmoji = isPlaying ? STATES.playing : player.paused ? STATES.paused : STATES.stopped;
let progressBar = "";
let timeDisplay = "`0:00 / 0:00`";
if (current?.duration && player.startedPlaying) {
const elapsed = Date.now() - player.startedPlaying;
const totalMs = typeof current.duration === "object"
? (current.duration.seconds ?? 0) * 1000
: current.duration;
const progress = Math.min(elapsed / totalMs, 1);
const barLength = 20;
const filled = Math.floor(progress * barLength);
const position = Math.min(Math.max(filled, 0), barLength - 1);
const emptyCount = Math.max(barLength - position - 1, 0);
progressBar = PROGRESS.start +
PROGRESS.filled.repeat(position) +
(isPlaying ? PROGRESS.indicator : PROGRESS.filled) +
PROGRESS.empty.repeat(emptyCount) +
PROGRESS.end;
// Use Utils.prettifyMS instead of local formatTime
const elapsedStr = Utils.prettifyMS(elapsed);
const totalStr = Utils.prettifyMS(totalMs);
timeDisplay = `\`${elapsedStr} / ${totalStr}\``;
} else {
progressBar = PROGRESS.start + PROGRESS.empty.repeat(20) + PROGRESS.end;
}
const volPercent = Math.round((player.preferredVolume || 1) * 100);
const volBars = Math.ceil(volPercent / 10);
const volumeBar = "█".repeat(volBars) + "░".repeat(10 - volBars);
const queueSize = player.queue.size();
const loopStatus = player.queue.songLoop ? "🔂 Song" : player.queue.loop ? "🔁 Queue" : "❌ Off";
const nowPlaying = current
// Use Utils.truncate instead of local truncate
? `[${Utils.truncate(current.title, 45)}](${current.spotifyUrl || current.url})`
: "*Nothing playing*";
const description = [
`${statusEmoji} **Now Playing**`,
`${nowPlaying}`,
``,
`${progressBar}`,
`${timeDisplay}`,
``,
`🔊 Volume: \`${volPercent}%\` ${volumeBar}`,
`📋 Queue: \`${queueSize}\` tracks | Loop: ${loopStatus}`,
``,
state.message ? `💬 *${state.message}*` : "💡 *React to control playback*",
``,
`⏱️ Session expires in ${Math.ceil(timeout / 60000)}m of inactivity`
].join("\n");
const builder = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle("🎧 Music Player Controls")
.setDescription(description)
.setFooter({
text: `Requested by ${msg.author?.username || "Unknown"} • Controls active`,
iconURL: msg.author?.avatarURL
})
.setTimestamp();
if (current?.thumbnail) builder.setThumbnail(current.thumbnail);
return builder.toJSON();
};
const message = await msg.replyEmbed({ embeds: [buildEmbed()] });
if (!message?.message) return;
// Add reactions with staggered animation
for (const row of controlsLayout) {
for (const control of row) {
try {
await message.message.react(control.emoji);
await Utils.sleep(200); // Use Utils.sleep instead of inline Promise
} catch (_) {}
}
}
let sessionTimeout;
let updateInterval;
let emojiRemoveTimeout;
let lastState = {};
// Track active lyrics message
let activeLyricsMsg = null;
let lyricsUnobserve = null;
let lyricsEmojiTimeout = null;
// Helper: Clear all reactions
const clearReactions = async () => {
try {
await message.message.removeAllReactions();
} catch (e) {
for (const emoji of controlEmojis) {
try {
await message.message.removeReaction(emoji);
} catch (_) {}
}
}
};
// Helper: Reset emoji removal timer
const resetEmojiTimer = () => {
clearTimeout(emojiRemoveTimeout);
emojiRemoveTimeout = setTimeout(async () => {
await clearReactions();
const disabledEmbed = buildEmbed({ message: "⌛ Controls disabled (react to re-enable)" });
disabledEmbed.footer = { text: "Controls expired • React to refresh" };
await message.editEmbed({ embeds: [disabledEmbed] }).catch(() => {});
}, EMOJI_REMOVE_TIMEOUT);
};
// Helper: Clear lyrics reactions
const clearLyricsReactions = async (lyricsMsg) => {
if (!lyricsMsg?.message) return;
try {
await lyricsMsg.message.removeAllReactions();
} catch (e) {
for (const emoji of ["⬅️", "➡️", "❌"]) {
try {
await lyricsMsg.message.removeReaction(emoji);
} catch (_) {}
}
}
};
const refresh = (extra = {}) => {
const embed = buildEmbed(extra);
message.editEmbed({ embeds: [embed] }).catch(() => {});
lastState = extra;
};
const closeSession = async (reason = "timeout") => {
clearTimeout(sessionTimeout);
clearTimeout(emojiRemoveTimeout);
clearInterval(updateInterval);
unobserve?.();
// Remove all player event listeners added by this session
player.off("startplay", onStartPlay);
player.off("playback", onPlayback);
player.off("stopplay", onStopPlay);
player.off("queue", onQueue);
player.off("volume", onVolume);
player.off("autoleave", onAutoLeave);
// Cleanup any active lyrics
if (lyricsUnobserve) {
lyricsUnobserve();
clearTimeout(lyricsEmojiTimeout);
}
if (activeLyricsMsg) {
await clearLyricsReactions(activeLyricsMsg);
}
await clearReactions();
const closedEmbed = buildEmbed({
message: `Session closed${reason !== "timeout" ? ` • ${reason}` : " due to inactivity"}`
});
// Override title and footer on the plain object returned by toJSON()
closedEmbed.color = getGlobalColor();
closedEmbed.footer = { text: "Session ended" };
closedEmbed.title = "🎧 Music Player (Inactive)";
await message.editEmbed({
embeds: [closedEmbed],
content: reason === "user" ? "👋 Player controls closed" : undefined
}).catch(() => {});
};
const resetTimeout = () => {
clearTimeout(sessionTimeout);
sessionTimeout = setTimeout(() => closeSession("timeout"), timeout);
};
// Live progress updates
updateInterval = setInterval(() => {
if (!player.paused && player.queue.getCurrent()) {
refresh(lastState);
}
}, this.config?.timers?.playerUpdateInterval ?? 5000);
// Player events — store named handlers so we can remove them on closeSession
const onStartPlay = () => refresh({ message: "▶️ Started playing" });
const onPlayback = (playing) => refresh({ message: playing ? "▶️ Resumed" : "⏸️ Paused" });
const onStopPlay = () => refresh({ message: "⏹️ Stopped" });
const onQueue = (e) => {
if (e.type === "shuffle") refresh({ message: "🔀 Queue shuffled" });
if (e.type === "add") refresh({ message: `➕ Added: ${Utils.truncate(e.data.data.title, 30)}` });
};
const onVolume = (v) => refresh({ message: `🔊 Volume: ${Math.round(v * 100)}%` });
const onAutoLeave = () => closeSession("disconnected");
player.on("startplay", onStartPlay);
player.on("playback", onPlayback);
player.on("stopplay", onStopPlay);
player.on("queue", onQueue);
player.on("volume", onVolume);
player.on("autoleave", onAutoLeave);
// Reaction handler
const unobserve = message.onReaction(controlEmojis, async (e) => {
const control = allControls.find(c => c.emoji === e.emoji_id);
if (!control) return;
resetEmojiTimer();
resetTimeout();
let reply = "";
let shouldUpdate = true;
try {
switch (control.action) {
case "previous":
reply = "⏮️ Previous track (not implemented)";
break;
case "resume":
if (player.paused) {
reply = player.resume();
} else if (!player.queue.getCurrent() && !player.queue.isEmpty()) {
player.playNext();
reply = "▶️ Starting playback";
} else {
reply = "▶️ Already playing";
}
break;
case "pause":
reply = player.pause();
break;
case "stop":
await player._stopMediaPlayer();
player.queue.reset();
reply = "⏹️ Stopped and cleared";
break;
case "skip":
reply = player.skip();
break;
case "loop": {
const currentLoop = player.queue.loop;
const currentSongLoop = player.queue.songLoop;
if (!currentLoop && !currentSongLoop) {
player.queue.setSongLoop(true);
reply = "🔂 Song loop enabled";
} else if (currentSongLoop) {
player.queue.setSongLoop(false);
player.queue.setLoop(true);
reply = "🔁 Queue loop enabled";
} else {
player.queue.setLoop(false);
reply = "❌ Loop disabled";
}
break;
}
case "shuffle":
reply = player.shuffle();
break;
case "voldown": {
const newVolDown = Utils.clamp((player.preferredVolume || 1) - 0.1, 0, 1);
reply = player.setVolume(newVolDown);
break;
}
case "volup": {
const newVolUp = Utils.clamp((player.preferredVolume || 1) + 0.1, 0, 1);
reply = player.setVolume(newVolUp);
break;
}
case "lyrics":
reply = "📜 Fetching lyrics...";
refresh({ message: reply });
try {
// Cleanup previous lyrics
if (lyricsUnobserve) {
lyricsUnobserve();
clearTimeout(lyricsEmojiTimeout);
if (activeLyricsMsg) await clearLyricsReactions(activeLyricsMsg);
}
const lyricsResult = await player.lyrics();
if (!lyricsResult) {
reply = "❌ No lyrics found in NodeLink";
shouldUpdate = true;
break;
}
const syncBadge = lyricsResult.synced ? " ⏱️ Synced" : "";
const lines = lyricsResult.text.split('\n');
const totalLines = lines.length;
const LINES_PER_PAGE = 25;
const totalPages = Math.ceil(totalLines / LINES_PER_PAGE);
// Build pages
const pages = [];
for (let i = 0; i < totalLines; i += LINES_PER_PAGE) {
pages.push(lines.slice(i, i + LINES_PER_PAGE).join('\n'));
}
let currentPage = 0;
const buildLyricsContent = (pageIdx, expired = false, closed = false) => {
const title = Utils.truncate(
player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '',
50
);
const footerText = closed
? `👋 Lyrics closed • NodeLink • ${totalLines} lines`
: expired
? `⌛ Controls expired • NodeLink • ${totalLines} lines`
: `NodeLink • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`;
const desc = [
`**${title}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}`,
``,
'```',
pages[pageIdx],
totalPages > 1 && !expired && !closed ? `\n\n💡 ⬅️ ➡️ Navigate • ❌ Close` : '',
'```'
].join('\n');
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText }).toJSON()] };
};
// Send initial lyrics
activeLyricsMsg = await msg.replyEmbed(buildLyricsContent(0));
// Add pagination and close button if needed
if (activeLyricsMsg?.message && totalPages > 1) {
const navEmojis = ["⬅️", "➡️", "❌"];
for (const emoji of navEmojis) {
await activeLyricsMsg.message.react(emoji).catch(() => {});
}
// Reset timer helper
const resetLyricsTimer = () => {
clearTimeout(lyricsEmojiTimeout);
lyricsEmojiTimeout = setTimeout(async () => {
await clearLyricsReactions(activeLyricsMsg);
await activeLyricsMsg.editEmbed(buildLyricsContent(currentPage, true, false)).catch(() => {});
}, EMOJI_REMOVE_TIMEOUT);
};
// Navigation handler
lyricsUnobserve = activeLyricsMsg.onReaction(navEmojis, async (e) => {
// Close button
if (e.emoji_id === "❌") {
lyricsUnobserve();
clearTimeout(lyricsEmojiTimeout);
await clearLyricsReactions(activeLyricsMsg);
await activeLyricsMsg.editEmbed(buildLyricsContent(currentPage, false, true)).catch(() => {});
return;
}
// Reset timer on navigation
resetLyricsTimer();
if (e.emoji_id === "⬅️") {
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
} else if (e.emoji_id === "➡️") {
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
}
await activeLyricsMsg.editEmbed(buildLyricsContent(currentPage));
});
// Start 1 minute timer
resetLyricsTimer();
} else if (activeLyricsMsg?.message) {
// Single page - just add close button
await activeLyricsMsg.message.react("❌").catch(() => {});
const resetLyricsTimer = () => {
clearTimeout(lyricsEmojiTimeout);
lyricsEmojiTimeout = setTimeout(async () => {
await clearLyricsReactions(activeLyricsMsg);
await activeLyricsMsg.editEmbed(buildLyricsContent(0, true, false)).catch(() => {});
}, EMOJI_REMOVE_TIMEOUT);
};
lyricsUnobserve = activeLyricsMsg.onReaction(["❌"], async (e) => {
if (e.emoji_id === "❌") {
lyricsUnobserve();
clearTimeout(lyricsEmojiTimeout);
await clearLyricsReactions(activeLyricsMsg);
await activeLyricsMsg.editEmbed(buildLyricsContent(0, false, true)).catch(() => {});
}
});
resetLyricsTimer();
}
reply = `Lyrics displayed (${totalLines} lines, ${totalPages} pages)`;
} catch (err) {
// Use Utils.truncate instead of local truncate
reply = `⚠️ Lyrics error: ${Utils.truncate(err.message, 50)}`;
}
shouldUpdate = true;
break;
case "close":
await closeSession("user");
return;
}
} catch (err) {
reply = `⚠️ Error: ${err.message}`;
}
if (shouldUpdate) refresh({ message: reply });
});
// Start timers
resetTimeout();
resetEmojiTimer();
}
+60
View File
@@ -0,0 +1,60 @@
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";
function parseInlineProvider(raw) {
const match = raw.match(/^([a-z]+):\s*(.+)$/i);
if (!match) return { provider: null, query: raw.trim() };
const maybeProvider = match[1].toLowerCase();
if (PROVIDER_CHOICES.includes(maybeProvider)) {
return { provider: maybeProvider, query: match[2].trim() };
}
return { provider: null, query: raw.trim() };
}
export const command = new CommandBuilder()
.setName("playnext")
.setId("playnext")
.setDescription("Same as %play but adds the result to the top of the queue.", "commands.playnext")
.setCategory("music")
.addExamples(
"$prefixplaynext blinding lights",
"$prefixplaynext sp: blinding lights",
"$prefixplaynext -p dz get lucky"
)
.addTextOption(option =>
option.setName("query")
.setDescription("A search query, URL, or provider-prefixed query like `sp: song name`.", "options.playnext.query")
.setRequired(true)
)
.addChoiceOption(o =>
o.setName("provider")
.setDescription("The search provider. Default: YouTube Music.", "options.playnext.provider")
.addFlagAliases("p", "u", "use")
.addChoices(...PROVIDER_CHOICES)
.setDefault("yt")
, true)
.addAlias("pn");
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";
const searchEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription("🔍 Searching...")
.toJSON();
const statusMsg = await message.replyEmbed({ embeds: [searchEmbed] });
const messages = p.playFirst(query, provider);
messages.on("message", d => {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d).toJSON();
statusMsg.editEmbed({ embeds: [embed] }).catch(() => {});
});
}
+153
View File
@@ -0,0 +1,153 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
const NUMBER_EMOJIS = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣"];
const CANCEL_EMOJI = "❌";
const PREV_EMOJI = "⬅️";
const NEXT_EMOJI = "➡️";
function mkEmbed(desc, title) {
const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc);
if (title) b.setTitle(title);
return { embeds: [b.toJSON()] };
}
export const command = function() {
if (!this.config.radio?.length) return null;
return new CommandBuilder()
.setName("radio")
.setDescription("Play a radio station. Use `%radio list` to browse all stations.", "commands.radio")
.addAliases("r")
.setCategory("music")
.addTextOption(o =>
o.setName("station")
.setDescription("Station name, 'list' to browse, or leave blank for default.")
.setRequired(false)
);
};
export async function run(msg, data) {
const radios = this.config.radio;
if (!radios?.length) return msg.replyEmbed(mkEmbed("❌ No radio stations are configured."));
const input = (data.get("station")?.value ?? "").trim().toLowerCase();
if (input === "list") {
let page = 0;
const perPage = NUMBER_EMOJIS.length;
const totalPages = Math.ceil(radios.length / perPage);
const buildPage = () => {
const start = page * perPage;
const pickable = radios.slice(start, start + perPage);
let desc = `📻 **Radio Stations (Page ${page + 1}/${totalPages})**\n\n`;
pickable.forEach((r, i) => {
desc += `${NUMBER_EMOJIS[i]} **${r.detailedName}** (\`${r.name}\`)\n`;
desc += ` ${r.description.replaceAll("\n", "\n ")}\n\n`;
});
desc += `━━━━━━━━━━━━━━━━━━━━━━\n`;
desc += `${PREV_EMOJI} Previous ${NEXT_EMOJI} Next ${CANCEL_EMOJI} Cancel`;
return { payload: mkEmbed(desc), pickable };
};
let { payload, pickable } = buildPage();
const listMsg = await msg.replyEmbed(payload);
if (!listMsg) return;
const baseEmojis = [...NUMBER_EMOJIS, PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI];
for (const e of baseEmojis) await listMsg.message.react(e).catch(() => {});
let settled = false;
const clearReactions = async () => {
const rawMsg = listMsg.message;
try {
await rawMsg.removeAllReactions();
} catch (_) {
for (const emoji of baseEmojis) {
try { await rawMsg.removeReaction(emoji); } catch (_) {}
}
}
};
const timeout = setTimeout(() => {
if (settled) return;
settled = true;
unobserve();
clearReactions().catch(() => {});
listMsg.editEmbed(mkEmbed("📻 Radio selection timed out.")).catch(() => {});
}, 60_000);
const normalize = (s) => s.replace(/\uFE0F/g, "");
const unobserve = listMsg.onReaction(baseEmojis, async (e) => {
if (settled) return;
const emoji = normalize(e.emoji_id);
if (emoji === normalize(CANCEL_EMOJI)) {
settled = true;
clearTimeout(timeout);
unobserve();
await clearReactions();
listMsg.editEmbed(mkEmbed("❌ Radio selection cancelled.")).catch(() => {});
return;
}
if (emoji === normalize(NEXT_EMOJI)) page = (page + 1) % totalPages;
else if (emoji === normalize(PREV_EMOJI)) page = (page - 1 + totalPages) % totalPages;
else {
const idx = NUMBER_EMOJIS.findIndex(x => normalize(x) === emoji);
if (idx !== -1 && idx < pickable.length) {
settled = true;
clearTimeout(timeout);
unobserve();
await clearReactions();
const selected = radios[page * perPage + idx];
return playStation(this, msg, selected, listMsg);
}
}
const next = buildPage();
pickable = next.pickable;
await listMsg.editEmbed(next.payload).catch(() => {});
}, msg.author);
return;
}
if (input) {
const radio = radios.find(r => r.name.toLowerCase() === input);
if (!radio) {
const names = radios.map(r => `\`${r.name}\``).join(", ");
return msg.replyEmbed(mkEmbed(`❌ Unknown station \`${input}\`. Available: ${names}\n\nUse \`%radio list\` to browse.`));
}
return playStation(this, msg, radio);
}
return playStation(this, msg, radios[0]);
}
async function playStation(ctx, msg, radio, editTarget = null) {
const p = await ctx.getPlayer(msg, true, true, true);
if (!p) return;
const current = p.queue.getCurrent();
const hasRadioQueued = p.queue.data.some(t => t.type === "radio");
if (current?.type === "radio" || hasRadioQueued) await p.switchRadio(radio);
else p.playRadio(radio);
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle(`📻 ${radio.detailedName}`)
.setDescription(
`**[${radio.detailedName}](${radio.author.url})**\n\n` +
`${radio.description}\n\n` +
`_Use \`%skip\` to stop the radio, or \`%radio list\` to switch stations._`
)
.toJSON();
if (editTarget) editTarget.editEmbed({ embeds: [embed] }).catch(() => {});
else msg.replyEmbed({ embeds: [embed] }).catch(() => {});
}
+204
View File
@@ -0,0 +1,204 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
import fs from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
export const command = new CommandBuilder()
.setName("reload")
.setDescription("Reload commands, src modules, or audio modules. Leave blank to see all targets.")
.setCategory("util")
.addStringOption(o =>
o.setName("target")
.setDescription("Command/module name, or: all | commands | src | audio")
.setRequired(false)
)
.setRequirement(r => r.setOwnerOnly(true));
function embed(desc) {
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] };
}
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const ROOT = path.resolve(__dirname, "..");
// ── Reload a single command ───────────────────────────────────────────────────
async function reloadCommand(ctx, name) {
if (name === "index")
return { ok: false, msg: "❌ `index.mjs` cannot be hot-reloaded — do a full restart." };
const command = ctx.handler.commands.find(c => c.name === name);
if (!command) return { ok: false, msg: `❌ Unknown command \`${name}\`` };
const file = ctx.commandFiles.get(command.uid);
if (!file) return { ok: false, msg: `❌ No file tracked for \`${name}\`` };
// Unregister old
command.subcommands.forEach(sub => ctx.runnables.delete(sub.uid));
ctx.handler.removeCommand(command);
ctx.runnables.delete(command.uid);
ctx.commandFiles.delete(command.uid);
// Re-import with cache-buster
const url = "file://" + file + "?t=" + Date.now();
const cData = await import(url);
const raw = cData.command ?? cData.default?.command;
const builder = typeof raw === "function" ? raw.call(ctx) : raw;
if (!builder) return { ok: false, msg: `❌ No builder returned from \`${name}\`` };
const runFn = cData.run ?? cData.default?.run;
const exportDef = cData.exportDef ?? cData.export ?? cData.default?.exportDef ?? cData.default?.export;
if (exportDef) ctx[exportDef.name] = exportDef.object;
ctx.handler.addCommand(builder);
ctx.commandFiles.set(builder.uid, file);
if (runFn) {
ctx.runnables.set(builder.uid, runFn);
builder.subcommands.forEach(sub => ctx.runnables.set(sub.uid, runFn));
}
return { ok: true, msg: `✅ \`${name}\`` };
}
// ── Reload a src/ or audio/ module ───────────────────────────────────────────
async function reloadModule(ctx, filePath, label) {
if (!fs.existsSync(filePath))
return { ok: false, msg: `❌ File not found: \`${label}\`` };
try {
await import(pathToFileURL(filePath).href + "?t=" + Date.now());
return { ok: true, msg: `✅ \`${label}\`` };
} catch (e) {
return { ok: false, msg: `❌ \`${label}\`: ${e.message}` };
}
}
// ── List all module files in a subdirectory ───────────────────────────────────
function allModuleFiles(subdir) {
const dir = path.join(ROOT, subdir);
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir)
.filter(f => f.endsWith(".mjs") || f.endsWith(".js"))
.map(f => ({ file: path.join(dir, f), label: `${subdir}/${f}` }));
}
// ── Paginated embed helper ────────────────────────────────────────────────────
async function showPaged(msg, title, lines, pageSize = 14) {
const pages = [];
for (let i = 0; i < lines.length; i += pageSize)
pages.push(lines.slice(i, i + pageSize));
if (pages.length === 0) pages.push(["*(nothing)*"]);
const arrows = ["⬅️", "➡️"];
const curr = { n: 0 };
const mkEmbed = (n) => ({
embeds: [
new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle(title)
.setDescription(pages[n].join("\n") + (pages.length > 1 ? `\n\nPage **${n + 1}** / **${pages.length}**` : ""))
.toJSON()
]
});
const m = await msg.replyEmbed(mkEmbed(0));
if (!m || pages.length <= 1) return;
m.message.react(arrows[0]).catch(() => {});
m.message.react(arrows[1]).catch(() => {});
const unsub = m.onReaction(arrows, (e) => {
if (e.emoji_id === arrows[0]) curr.n = Math.max(0, curr.n - 1);
else curr.n = Math.min(pages.length - 1, curr.n + 1);
m.editEmbed(mkEmbed(curr.n)).catch(() => {});
});
setTimeout(() => { unsub?.(); }, 5 * 60_000);
}
// ── Batch results → paginated display ────────────────────────────────────────
async function showResults(msg, results, label) {
const ok = results.filter(r => r.ok).length;
const bad = results.filter(r => !r.ok).length;
const header = `✅ **${ok}** reloaded · ❌ **${bad}** failed`;
await showPaged(msg, `🔄 Reload — ${label}`, [header, "", ...results.map(r => r.msg)]);
}
// ── Main ──────────────────────────────────────────────────────────────────────
export async function run(msg, data) {
const target = (data.get("target")?.value ?? "").trim().toLowerCase();
// No target — show paginated list of everything reloadable
if (!target) {
const cmdLines = this.handler.commands.map(c => `📦 \`${c.name}\` *(command)*`);
const srcLines = allModuleFiles("src").map(m => `🔧 \`${m.label}\` *(src)*`);
const audLines = allModuleFiles("audio").map(m => `🎵 \`${m.label}\` *(audio)*`);
const lines = [
"Run `%reload <target>` or use a batch keyword:",
"`all` · `commands` · `src` · `audio`",
"",
...cmdLines,
...srcLines,
...audLines,
];
return showPaged(msg, "🔄 Reload — Available Targets", lines);
}
// Batch keywords
if (target === "commands") {
const results = await Promise.all(
this.handler.commands.map(c => reloadCommand(this, c.name))
);
return showResults(msg, results, "Commands");
}
if (target === "src") {
const results = await Promise.all(
allModuleFiles("src").map(m => reloadModule(this, m.file, m.label))
);
return showResults(msg, results, "src/");
}
if (target === "audio") {
const results = await Promise.all(
allModuleFiles("audio").map(m => reloadModule(this, m.file, m.label))
);
return showResults(msg, results, "audio/");
}
if (target === "all") {
const results = await Promise.all([
...this.handler.commands.map(c => reloadCommand(this, c.name)),
...allModuleFiles("src").map(m => reloadModule(this, m.file, m.label)),
...allModuleFiles("audio").map(m => reloadModule(this, m.file, m.label)),
]);
return showResults(msg, results, "Everything");
}
// Single command by name
if (this.handler.commands.some(c => c.name === target)) {
const res = await reloadCommand(this, target);
return msg.replyEmbed(embed(res.msg));
}
// Single src/ or audio/ module by filename (with or without extension/subdir)
const allMods = [...allModuleFiles("src"), ...allModuleFiles("audio")];
const mod = allMods.find(m =>
m.label.toLowerCase() === target ||
path.basename(m.file).replace(/\.m?js$/, "").toLowerCase() === target
);
if (mod) {
const res = await reloadModule(this, mod.file, mod.label);
return msg.replyEmbed(embed(res.msg));
}
return msg.replyEmbed(embed(
`❌ Unknown target \`${target}\`.\nRun \`%reload\` with no arguments to see all reloadable targets.`
));
}
+23
View File
@@ -0,0 +1,23 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("remove")
.setDescription("Remove a specific song from the queue.", "commands.remove")
.setCategory("music")
.addNumberOption(opt =>
opt.setName("index")
.setDescription("The position of the song in the queue. You can view the indices with the 'list' command", "options.remove.index")
.setRequired(true));
export async function run(message, data) {
const p = await this.getPlayer(message, false, false, false);
if (!p) return;
const res = p.remove(data.options[0].value);
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(res)
.toJSON();
message.replyEmbed({ embeds: [embed] });
}
+19
View File
@@ -0,0 +1,19 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("resume")
.setDescription("Resume the playback in your voice channel", "commands.resume")
.setCategory("music");
export async function run(message) {
const p = await this.getPlayer(message, false, false, false);
if (!p) return;
const res = p.resume();
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(res)
.toJSON();
message.replyEmbed({ embeds: [embed] });
}
+168
View File
@@ -0,0 +1,168 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { Message, getGlobalColor } from "../src/MessageHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { PROVIDER_CHOICES, PROVIDER_NAMES } from "../src/constants/providers.mjs";
const NUMBER_EMOJIS = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣"];
const CANCEL_EMOJI = "❌";
// SESSION_MS is now read from config.timers.searchSessionTimeout (fallback: 30s)
function parseInlineProvider(raw) {
const match = raw.match(/^([a-z]+):\s*(.+)$/i);
if (!match) return { provider: null, query: raw.trim() };
const maybeProvider = match[1].toLowerCase();
if (PROVIDER_CHOICES.includes(maybeProvider))
return { provider: maybeProvider, query: match[2].trim() };
return { provider: null, query: raw.trim() };
}
export const command = new CommandBuilder()
.setName("search")
.setDescription(
"Display search results for a query and pick one to play.\n" +
"Supports all providers — use inline prefix e.g. `sp: song` or `-p dz`.",
"commands.search"
)
.setCategory("music")
.addExamples(
"$prefixsearch never gonna give you up",
"$prefixsearch sp: blinding lights",
"$prefixsearch -p dz get lucky"
)
.addChoiceOption(o =>
o.setName("provider")
.setDescription("The search provider. Default: YouTube Music.", "options.search.provider")
.addChoices(...PROVIDER_CHOICES)
.setDefault("ytm")
.addFlagAliases("p", "u", "use")
, true)
.addTextOption(o =>
o.setName("query")
.setDescription("The query to search for, or a provider-prefixed query like `sp: song name`.", "options.search.query")
.setRequired(true)
);
export async function run(msg, data) {
const p = await this.getPlayer(msg, 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";
const name = PROVIDER_NAMES[provider] ?? "YouTube Music";
// Send loading embed
const channel = msg.channel?.channel ?? msg.message?.channel;
if (!channel?.send) return;
/**
* Build a search-result embed using EmbedBuilder.
* @param {string} description
* @param {string} [footerText]
* @param {string} [authorLabel] - defaults to `name` (provider name)
*/
const makeEmbed = (description, footerText, authorLabel = name) => {
const b = new EmbedBuilder()
.setColor(getGlobalColor())
.setAuthor({ name: authorLabel })
.setDescription(description);
if (footerText) b.setFooter({ text: footerText });
return b.toJSON();
};
const nativeMsg = msg.message ?? msg;
const rawMsg = await nativeMsg.reply(
{ embeds: [makeEmbed("⏳ Loading results...", null, `Searching ${name}...`)] },
{ ping: false }
).catch(() => null);
if (!rawMsg) return;
// Fetch results
const res = await p.fetchResults(query, msg.authorId, provider);
if (!res?.count) {
rawMsg.edit({ embeds: [makeEmbed("❌ No results found.")] }).catch(() => {});
return;
}
// Build results embed
const results = p.searches.get(msg.authorId) ?? [];
const reactions = NUMBER_EMOJIS.slice(0, res.count);
let desc = "";
results.forEach((v, i) => {
const dur = v.duration ? p.getDuration(v.duration) : "?:??";
const title = v.title || "Unknown";
const url = v.url || "";
desc += `${NUMBER_EMOJIS[i]} [${title}](${url}) — \`${dur}\`\n`;
});
desc += `\n${CANCEL_EMOJI} Cancel`;
await rawMsg.edit({
embeds: [makeEmbed(
desc,
"React with a number to add to queue • ❌ to cancel • 30s timeout",
`${name} — Search Results`
)]
}).catch(() => {});
// Add reactions
for (const emoji of [...reactions, CANCEL_EMOJI]) {
await rawMsg.react(emoji).catch(() => {});
}
const allReactions = [...reactions, CANCEL_EMOJI];
const client = this.client;
const channelId = rawMsg.channelId ?? rawMsg.channel_id ?? rawMsg.channel?.id;
const msgId = rawMsg.id;
const clearReactions = async () => {
try {
await rawMsg.removeAllReactions();
} catch (_) {}
};
const wrapped = new Message(rawMsg, this.messages);
const authorId = msg.message?.author?.id ?? msg.authorId;
const unobserve = wrapped.onReaction(allReactions, async (e, reactionMsg) => {
// Only react to the command author
if (e.user_id && e.user_id !== authorId) return;
clearTimeout(timer);
unobserve();
await clearReactions();
if (e.emoji_id === CANCEL_EMOJI) {
rawMsg.edit({
embeds: [makeEmbed("❌ Cancelled.", null, `${name} — Search Results`)]
}).catch(() => {});
return;
}
const idx = reactions.indexOf(e.emoji_id);
if (idx === -1) return;
const v = p.playResult(msg.authorId, idx);
if (!v) return;
rawMsg.edit({
embeds: [makeEmbed(
`✅ Added [${v.title}](${v.url}) to the queue!`,
null,
`${name} — Search Results`
)]
}).catch(() => {});
});
// Read session timeout from config (fallback 30 s)
const SESSION_MS = this.config?.timers?.searchSessionTimeout ?? 30_000;
const timer = setTimeout(() => {
unobserve();
clearReactions().catch(() => {});
rawMsg.edit({
embeds: [makeEmbed("⏰ Search timed out.", "Session closed", `${name} — Search Results`)]
}).catch(() => {});
}, SESSION_MS); // configurable via config.timers.searchSessionTimeout
}
+115
View File
@@ -0,0 +1,115 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("servers")
.setDescription("Fetch a list of servers the bot is in")
.setRequirement(r => r.setOwnerOnly(true))
.setCategory("util");
// Auto-remove timer: 1 minute
const EMOJI_REMOVE_TIMEOUT = 60000;
export async function run(msg) {
const guilds = [...this.client.guilds.cache.values()];
// Fallback if the bot is in 0 servers
if (guilds.length === 0) {
const emptyEmbed = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle("🌐 Servers (0)")
.setDescription("_No servers found._")
.toJSON();
return msg.replyEmbed({ embeds: [emptyEmbed] });
}
const itemsPerPage = 50;
const totalPages = Math.ceil(guilds.length / itemsPerPage);
const pages = [];
// Build the content for each page
for (let i = 0; i < guilds.length; i += itemsPerPage) {
const chunk = guilds.slice(i, i + itemsPerPage);
const list = chunk.map((g, index) => `${i + index + 1}. **${g.name}** (\`${g.id}\`)`).join("\n");
pages.push(list);
}
let currentPage = 0;
// Helper function to generate the embed for a specific page
const buildPageContent = (pageIdx, expired = false) => {
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle(`🌐 Servers (${guilds.length}) - Page ${pageIdx + 1}/${totalPages}`)
.setDescription(pages[pageIdx])
.setFooter({
text: expired
? "⌛ Controls expired"
: totalPages > 1
? "💡 ⬅️ ➡️ Navigate"
: "List complete"
})
.toJSON();
return { embeds: [embed] };
};
// Send the initial message using the framework's wrapper
const replyMsg = await msg.replyEmbed(buildPageContent(0));
// Safety check and single-page exit
if (!replyMsg?.message) return;
if (totalPages <= 1) return;
const navEmojis = ["⬅️", "➡️"];
let unobserve = null;
let emojiTimeout = null;
// Add reactions
for (const emoji of navEmojis) {
await replyMsg.message.react(emoji).catch(() => {});
}
// Helper: Clear all reactions (matches player.mjs fallback logic)
const clearReactions = async () => {
try {
await replyMsg.message.removeAllReactions();
} catch (e) {
for (const emoji of navEmojis) {
try {
await replyMsg.message.removeReaction(emoji);
} catch (_) {}
}
}
};
// Helper: Reset the expiration timer
const resetTimer = () => {
clearTimeout(emojiTimeout);
emojiTimeout = setTimeout(async () => {
if (unobserve) unobserve();
await clearReactions();
await replyMsg.editEmbed(buildPageContent(currentPage, true)).catch(() => {});
}, EMOJI_REMOVE_TIMEOUT);
};
// Start listening for reactions using the framework's native listener
unobserve = replyMsg.onReaction(navEmojis, async (e) => {
resetTimer(); // Reset the 1-minute timer when interacting
if (e.emoji_id === "⬅️") {
// Go backward (loops to the end if on the first page)
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
} else if (e.emoji_id === "➡️") {
// Go forward (loops to the beginning if on the last page)
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
}
// Update the embed using the framework's native edit method
await replyMsg.editEmbed(buildPageContent(currentPage)).catch(() => {});
});
// Start the initial countdown
resetTimer();
}
+511
View File
@@ -0,0 +1,511 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
import runnables from "../settings/runnables.mjs";
function embed(desc, opts = {}) {
const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc);
if (opts.title) b.setTitle(opts.title);
if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL });
return { embeds: [b.toJSON()] };
}
// ── Constants ─────────────────────────────────────────────────────────────────
const SHORTCUTS = {
prefix: "prefix",
pfx: "prefix",
"247": "stay_247",
};
/** Aliases accepted for boolean settings */
const BOOL_TRUE = new Set(["true", "1", "yes", "on", "enable", "enabled"]);
const BOOL_FALSE = new Set(["false", "0", "no", "off", "disable", "disabled"]);
/** Settings whose values should be displayed as booleans */
const BOOL_SETTINGS = new Set(["songAnnouncements"]);
/** Valid locale codes */
const VALID_LOCALES = new Set(["en", "ar-SA", "ckb", "de-DE", "pt-BR"]);
/** Volume constraints */
const VOLUME_MIN = 1;
const VOLUME_MAX = 200;
// ── Helpers ───────────────────────────────────────────────────────────────────
/** Extract clean numeric channel ID from any format */
function cleanId(raw) {
return String(raw).replace(/\D/g, "");
}
/** Parse "true/false" and their aliases → boolean | null */
function parseBool(str) {
const s = String(str).toLowerCase().trim();
if (BOOL_TRUE.has(s)) return true;
if (BOOL_FALSE.has(s)) return false;
return null;
}
/** Format a setting value for display */
function displayValue(key, value) {
if (BOOL_SETTINGS.has(key)) return value ? "✅ enabled" : "❌ disabled";
if (value === null || value === undefined || value === "none") return "none";
return `\`${value}\``;
}
/** Resolve guild ID from a message context */
function getGuildId(message) {
return message.message?.guild?.id ?? message.channel?.guild?.id ?? null;
}
/** Resolve guild name from a message context */
function getGuildName(message) {
return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server";
}
// ── 24/7 helpers ──────────────────────────────────────────────────────────────
function get247Channels(set) {
const raw = set.get("stay_247");
if (!raw || raw === "none") return new Set();
if (typeof raw === "string") {
const id = cleanId(raw);
return id ? new Set([id]) : new Set();
}
if (Array.isArray(raw)) {
return new Set(raw.map(id => cleanId(id)).filter(Boolean));
}
return new Set();
}
function save247Channels(set, channels) {
const arr = [...channels];
set.set("stay_247", arr.length > 0 ? arr : "none");
}
function format247Status(set) {
const channels = get247Channels(set);
const mode = set.get("stay_247_mode") ?? "off";
if (channels.size === 0) return "❌ disabled";
const channelList = [...channels].map(id => `<#${id}>`).join(", ");
const modeLabel = mode === "auto" ? "🔄 auto" : mode === "on" ? "✅ on" : "❌ off";
return `${modeLabel} — ${channelList}`;
}
async function handle247(ctx, message, value) {
const set = ctx.getSettings(message);
const guildId = getGuildId(message);
const mode = value.toLowerCase().trim();
// Normalise legacy true/false
const resolved = mode === "true" ? "auto" : mode === "false" ? "off" : mode;
if (!["off", "on", "auto"].includes(resolved)) {
return message.replyEmbed(embed(
`❌ Invalid value \`${value}\` for 24/7 mode.\n\n` +
`**Valid options:**\n` +
`• \`off\` — bot leaves after inactivity\n` +
`• \`on\` — bot stays, but won't rejoin after restart or force-kick\n` +
`• \`auto\` — bot stays and always rejoins after restart or force-kick`
));
}
// ── OFF ───────────────────────────────────────────────────────────────────
if (resolved === "off") {
if (!guildId) return message.replyEmbed(embed("❌ Could not detect your server."));
const channelId = ctx.players.checkVoiceChannels(message);
const channels = get247Channels(set);
if (channelId) {
const id = cleanId(channelId);
channels.delete(id);
save247Channels(set, channels);
ctx.markIntentionalLeave?.(id);
const player = ctx.players.playerMap.get(id);
if (player) {
ctx.players.playerMap.delete(id);
await player.leave().catch(() => {});
player.destroy();
}
if (channels.size === 0) set.set("stay_247_mode", "off");
return message.replyEmbed(embed(`✅ 24/7 mode **disabled** for <#${id}>. Bot has left.`));
}
// Not in a channel — disable all for this guild
save247Channels(set, new Set());
set.set("stay_247_mode", "off");
for (const [chId, player] of [...ctx.players.playerMap.entries()]) {
const ch = ctx.handler.client.channels.cache.get(chId);
if (ch?.guild?.id === guildId || ch?.guildId === guildId) {
ctx.markIntentionalLeave?.(chId);
ctx.players.playerMap.delete(chId);
await player.leave().catch(() => {});
player.destroy();
}
}
return message.replyEmbed(embed("✅ 24/7 mode **disabled** for all channels in this server."));
}
// ── ON / AUTO ─────────────────────────────────────────────────────────────
if (!guildId) return message.replyEmbed(embed("❌ Could not detect your server."));
const channelId = ctx.players.checkVoiceChannels(message);
if (!channelId) {
return message.replyEmbed(embed(
`❌ You're not in a voice channel. Join one first, then run \`%247 ${resolved}\` again.`
));
}
const id = cleanId(channelId);
const channels = get247Channels(set);
channels.add(id);
save247Channels(set, channels);
set.set("stay_247_mode", resolved);
const modeLabel = resolved === "auto"
? "**auto** (stays and rejoins automatically)"
: "**on** (stays but won't rejoin if kicked)";
if (ctx.players.playerMap.has(id)) {
return message.replyEmbed(embed(`✅ 24/7 mode set to ${modeLabel} for <#${id}>.`));
}
try {
await ctx._spawnPlayer(guildId, id);
return message.replyEmbed(embed(`✅ 24/7 mode set to ${modeLabel} for <#${id}>. Bot joined!`));
} catch (e) {
return message.replyEmbed(embed(`✅ 24/7 mode saved, but failed to join: ${e.message}`));
}
}
// ── Per-setting validation & apply ───────────────────────────────────────────
/**
* Validate and save a setting value.
* @returns {string|null} Error message string, or null on success.
* For stay_247, replies directly and always returns null.
*/
async function applySet(ctx, message, set, key, rawValue) {
// Boolean settings
if (BOOL_SETTINGS.has(key)) {
const bool = parseBool(rawValue);
if (bool === null) {
return (
`❌ \`${key}\` must be a boolean.\n` +
`Accepted: \`true\`, \`false\`, \`on\`, \`off\`, \`enable\`, \`disable\``
);
}
set.set(key, bool);
return null;
}
// 24/7 mode — replies on its own
if (key === "stay_247") {
await handle247(ctx, message, rawValue);
return null;
}
// Volume
if (key === "volume") {
const num = parseInt(rawValue, 10);
if (isNaN(num) || num < VOLUME_MIN || num > VOLUME_MAX) {
return `❌ Volume must be a number between **${VOLUME_MIN}** and **${VOLUME_MAX}**.`;
}
set.set(key, num);
return null;
}
// Locale
if (key === "locale") {
if (!VALID_LOCALES.has(rawValue)) {
return (
`❌ \`${rawValue}\` is not a supported locale.\n` +
`Available locales: ${[...VALID_LOCALES].map(l => `\`${l}\``).join(", ")}`
);
}
set.set(key, rawValue);
return null;
}
// Prefix
if (key === "prefix") {
if (!rawValue || rawValue.length > 5) {
return `❌ Prefix must be between **1** and **5** characters.`;
}
if (/\s/.test(rawValue)) {
return `❌ Prefix cannot contain spaces.`;
}
}
// General: run the runnable hook if present
if (runnables[key]) {
const err = runnables[key].call(ctx, rawValue, { msg: message });
if (err) return `❌ ${err}`;
}
set.set(key, rawValue);
return null;
}
// ── Shortcut handler (%prefix, %pfx, %247) ───────────────────────────────────
async function handleShortcut(ctx, message, settingKey, valueTokens) {
const set = ctx.getSettings(message);
// GET (no value provided)
if (valueTokens.length === 0) {
if (settingKey === "stay_247") {
return message.replyEmbed(embed(`24/7 mode: ${format247Status(set)}`));
}
const val = set.get(settingKey);
return message.replyEmbed(embed(`\`${settingKey}\` → ${displayValue(settingKey, val)}`));
}
// SET
const rawValue = valueTokens.join(" ");
const err = await applySet(ctx, message, set, settingKey, rawValue);
if (err) return message.replyEmbed(embed(err));
// handle247 replies on its own
if (settingKey !== "stay_247") {
const val = set.get(settingKey);
return message.replyEmbed(embed(`✅ \`${settingKey}\` set to ${displayValue(settingKey, val)}`));
}
}
// ── Command definition ────────────────────────────────────────────────────────
export const command = function() {
if (this.loader) {
for (const [alias, settingKey] of Object.entries(SHORTCUTS)) {
const builder = new CommandBuilder()
.setName(alias)
.setDescription(`Shortcut for \`${settingKey}\`. Usage: %${alias} [value]`)
.setId(`shortcut_${alias}`)
.setCategory("util")
.setRequirement(e => e.addPermission("ManageGuild"))
.addTextOption(o =>
o.setName("value")
.setDescription(`New value for ${settingKey}`)
.setRequired(false)
);
this.loader.commands.addCommand(builder);
this.loader.runnables.set(builder.uid, run);
}
}
const settingKeys = Object.keys(this.settingsMgr.defaults);
return new CommandBuilder()
.setName("settings")
.setDescription("Change/Get settings in the current server.", "commands.settings")
.addExamples(
"$prefixsettings get",
"$prefixsettings get prefix",
"$prefixsettings set prefix !",
"$prefixsettings set locale de-DE",
"$prefixsettings set songAnnouncements off",
"$prefixsettings set stay_247 auto",
"$prefixsettings set volume 80",
"$prefixsettings reset prefix",
"$prefixsettings help"
)
.setCategory("util")
.setRequirement(e => e.addPermission("ManageGuild"))
.addSubcommand(cmd =>
cmd.setName("set")
.setId("setSettings")
.setDescription("Set the value of a specific setting.", "subcommands.settings.set")
.addChoiceOption(c =>
c.addChoices(...settingKeys)
.setName("setting")
.setDescription("Which setting to change.", "options.settings.set.setting")
.setRequired(true)
)
.addTextOption(c =>
c.setName("value")
.setDescription("The new value.", "options.settings.set.value")
.setRequired(true)
)
)
.addSubcommand(cmd =>
cmd.setName("get")
.setDescription("Get a setting's value, or list all settings.", "subcommands.settings.get")
.setId("getSettings")
.addChoiceOption(c =>
c.addChoices(...settingKeys)
.setName("setting")
.setDescription("Omit to list all settings.", "options.settings.get.setting")
.setRequired(false)
)
)
.addSubcommand(cmd =>
cmd.setName("reset")
.setDescription("Reset a setting to its default value.", "subcommands.settings.reset")
.setId("resetSettings")
.addChoiceOption(c =>
c.addChoices(...settingKeys)
.setName("setting")
.setDescription("Which setting to reset.", "options.settings.reset.setting")
.setRequired(true)
)
)
.addSubcommand(cmd =>
cmd.setName("help")
.setDescription("Show help for the settings system, or explain a specific setting.", "subcommands.settings.help")
.setId("helpSettings")
.addChoiceOption(c =>
c.addChoices(...settingKeys)
.setName("setting")
.setDescription("Omit to see all available settings.", "options.settings.help.setting")
.setRequired(false)
)
);
};
// ── Command runner ────────────────────────────────────────────────────────────
export async function run(message, data) {
const set = this.getSettings(message);
const cmd = data.commandId;
// ── Shortcut commands (%prefix, %pfx, %247) ───────────────────────────────
if (cmd?.startsWith("shortcut_")) {
const alias = cmd.replace("shortcut_", "");
const settingKey = SHORTCUTS[alias];
const raw = (message.content ?? message.message?.content ?? "").trim();
const prefix = set.get("prefix") ?? "%";
const body = raw.startsWith(prefix) ? raw.slice(prefix.length).trim() : raw;
const tokens = body.split(/\s+/).slice(1);
return handleShortcut(this, message, settingKey, tokens);
}
// ── Inline shortcut: %settings <alias> [value] ────────────────────────────
const raw = (message.content ?? message.message?.content ?? "").trim();
const prefix = set.get("prefix") ?? "%";
const body = raw.startsWith(prefix) ? raw.slice(prefix.length).trim() : raw;
const args = body.split(/\s+/);
const inlineShortcut = SHORTCUTS[args[1]?.toLowerCase()];
if (inlineShortcut) {
return handleShortcut(this, message, inlineShortcut, args.slice(2));
}
const settingKey = data.get("setting")?.value;
// ── set ───────────────────────────────────────────────────────────────────
if (cmd === "setSettings") {
const rawValue = data.get("value")?.value;
if (!this.settingsMgr.isOption(settingKey)) {
const available = Object.keys(this.settingsMgr.defaults).join("`, `");
return message.replyEmbed(embed(
`❌ Unknown setting \`${settingKey}\`.\nAvailable: \`${available}\``
));
}
const err = await applySet(this, message, set, settingKey, rawValue);
if (err) return message.replyEmbed(embed(err));
if (settingKey === "stay_247") return; // handle247 replied already
const newVal = set.get(settingKey);
return message.replyEmbed(embed(`✅ \`${settingKey}\` set to ${displayValue(settingKey, newVal)}`));
}
// ── get ───────────────────────────────────────────────────────────────────
if (cmd === "getSettings") {
if (settingKey) {
if (settingKey === "stay_247") {
return message.replyEmbed(embed(`24/7 mode: ${format247Status(set)}`));
}
const val = set.get(settingKey);
const description = this.settingsMgr.descriptions?.[settingKey];
let reply = `**${settingKey}** → ${displayValue(settingKey, val)}`;
if (description) reply += `\n\n*${description}*`;
return message.replyEmbed(embed(reply));
}
// List all settings
const d = set.getAll();
const guildName = getGuildName(message);
const iconUrl = message.message?.guild?.iconURL?.() ?? null;
const lines = Object.entries(d)
.filter(([k]) => k !== "stay_247_mode") // surfaced inline with stay_247
.map(([k]) => {
if (k === "stay_247") {
return `• **stay_247** — ${format247Status(set)}`;
}
return `• **${k}** — ${displayValue(k, d[k])}`;
});
return message.replyEmbed(embed(
`Settings for **${guildName}**\n\n${lines.join("\n")}\n\n` +
`Use \`${prefix}settings help <setting>\` to learn about any setting.`,
{ title: "⚙️ Server Settings", iconURL: iconUrl }
));
}
// ── reset ─────────────────────────────────────────────────────────────────
if (cmd === "resetSettings") {
if (!this.settingsMgr.isOption(settingKey)) {
return message.replyEmbed(embed(`❌ Unknown setting \`${settingKey}\`.`));
}
set.reset(settingKey);
const def = set.get(settingKey);
return message.replyEmbed(embed(
`🔄 \`${settingKey}\` has been reset to its default: ${displayValue(settingKey, def)}`
));
}
// ── help ──────────────────────────────────────────────────────────────────
if (cmd === "helpSettings") {
const pfx = set.get("prefix") ?? "%";
if (!settingKey) {
const keys = Object.keys(this.settingsMgr.defaults);
const keyList = keys.map(k => `\`${k}\``).join(", ");
return message.replyEmbed(embed(
`**⚙️ Settings Help**\n\n` +
`**Available settings:** ${keyList}\n\n` +
`**Subcommands:**\n` +
`• \`${pfx}settings get\` — list all current values\n` +
`• \`${pfx}settings get <setting>\` — view a single setting\n` +
`• \`${pfx}settings set <setting> <value>\` — change a setting\n` +
`• \`${pfx}settings reset <setting>\` — restore default value\n` +
`• \`${pfx}settings help <setting>\` — describe a setting\n\n` +
`**Shortcuts:** \`${pfx}prefix\`, \`${pfx}247\``,
{ title: "⚙️ Settings Help" }
));
}
const description = this.settingsMgr.descriptions?.[settingKey] ?? "No description available.";
const currentVal = set.get(settingKey);
const defaultVal = this.settingsMgr.defaults?.[settingKey];
let extra = "";
if (settingKey === "locale") {
extra = `\n**Valid values:** ${[...VALID_LOCALES].map(l => `\`${l}\``).join(", ")}`;
} else if (settingKey === "volume") {
extra = `\n**Valid range:** ${VOLUME_MIN}–${VOLUME_MAX}`;
} else if (BOOL_SETTINGS.has(settingKey)) {
extra = `\n**Valid values:** \`true\`, \`false\`, \`on\`, \`off\``;
} else if (settingKey === "stay_247") {
extra = `\n**Valid values:** \`off\`, \`on\`, \`auto\``;
}
return message.replyEmbed(embed(
`**⚙️ Setting: \`${settingKey}\`**\n\n` +
`${description}${extra}\n\n` +
`**Current value:** ${displayValue(settingKey, currentVal)}\n` +
`**Default:** ${displayValue(settingKey, defaultVal)}`,
{ title: `⚙️ ${settingKey}` }
));
}
}
+19
View File
@@ -0,0 +1,19 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("shuffle")
.setDescription("Re-orders the queue randomly.", "commands.shuffle")
.setCategory("music");
export async function run(message) {
const p = await this.getPlayer(message, false, false, false);
if (!p) return;
const res = p.shuffle();
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(res)
.toJSON();
message.replyEmbed({ embeds: [embed] });
}
+34
View File
@@ -0,0 +1,34 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("skip")
.setDescription("Skip the current playing song.", "commands.skip")
.addAliases("s")
.setCategory("music");
export async function run(message) {
const p = await this.getPlayer(message);
if (!p) return;
const current = p.queue.getCurrent();
const skippedTitle = current?.title ?? null;
const skippedLink = current ? (current.spotifyUrl || current.url || "") : "";
const err = p.skip();
if (err && err.includes("nothing playing")) {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(err).toJSON();
return message.replyEmbed({ embeds: [embed] });
}
const desc = skippedTitle
? `⏭️ Skipped [${skippedTitle}](${skippedLink})`
: "⏭️ Skipped";
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(desc)
.toJSON();
message.replyEmbed({ embeds: [embed] });
}
+90
View File
@@ -0,0 +1,90 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { Utils } from "../src/Utils.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("stats")
.setDescription("Display stats about the bot like the uptime.", "commands.stats")
.addAliases("info")
.setCategory("util");
// ── User count ────────────────────────────────────────────────────────────────
async function fetchUserCount(client) {
const guildIds = Array.from(client.guilds.cache.keys());
if (guildIds.length === 0) return 0;
try {
const counts = await Promise.all(guildIds.map(async (id) => {
let total = 0, after = "0", done = false;
try {
while (!done) {
const batch = await client.rest?.get(`/guilds/${id}/members?limit=1000&after=${after}`);
if (!batch?.length) { done = true; }
else {
total += batch.length;
done = batch.length < 1000;
if (!done) after = batch[batch.length - 1].user.id;
}
}
return total;
} catch { return 0; }
}));
return counts.reduce((a, b) => a + b, 0);
} catch { return 0; }
}
// ── Embed builder ─────────────────────────────────────────────────────────────
function buildEmbed({ guildCount, userCount, playerCount, ping, uptime, comHash, comLink, reason, footer, loading }) {
const num = (v) => Number(v).toLocaleString();
const ld = (v) => loading ? "..." : v;
const description = [
`📂 **Servers** — \`${num(guildCount)}\``,
`👥 **Users** — \`${ld(num(userCount))}\``,
`🎧 **Players** — \`${num(playerCount)}\``,
`🏓 **Ping** — \`${ld(`${ping}ms`)}\``,
`⏱️ **Uptime** — \`${uptime}\``,
`🔧 **Build** — [\`${comHash}\`](${comLink})`,
reason ? `🪛 **Last restart** — \`${reason}\`` : null,
``,
`☕ [Support us on Ko-fi](https://ko-fi.com/remixbot)`,
`💬 [Community](https://fluxer.gg/Remix)`,
].filter(l => l !== null).join("\n");
return new EmbedBuilder()
.setColor(getGlobalColor())
.setAuthor({ name: "Remix Music Bot" })
.setDescription(description)
.setFooter({ text: footer || "Remix Music Bot" })
.setTimestamp()
.toJSON();
}
// ── Runner ────────────────────────────────────────────────────────────────────
export async function run(message) {
const shared = {
guildCount: this.client.guilds.cache.size,
playerCount: this.players.playerMap.size,
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
comHash: this.comHash,
comLink: this.comLink,
reason: this.config.restart ?? null,
footer: this.config.customStatsFooter || null,
};
const start = Date.now();
const msg = await message.replyEmbed({
embeds: [buildEmbed({ ...shared, userCount: 0, ping: 0, loading: true })]
});
const ping = Date.now() - start;
const users = await fetchUserCount(this.client);
await msg.editEmbed({
embeds: [buildEmbed({ ...shared, userCount: users, ping, loading: false })]
}).catch(() => {});
}
+22
View File
@@ -0,0 +1,22 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("support")
.setDescription("The support server for Remix. Feel free to ask help, report bugs or just chat :)", "commands.support")
.addAliases("server")
.setCategory("util");
export function run(msg) {
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle("💬 Support")
.setDescription(
"For anything regarding Remix, head over to our server:\n" +
"[Remix HQ](https://fluxer.gg/remix)\n\n" +
"If you don't want to join, feel free to contact the team members listed in the server."
)
.toJSON();
msg.replyEmbed({ embeds: [embed] });
}
+63
View File
@@ -0,0 +1,63 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("test")
.setDescription("Shows how many people are in each voice channel.")
.setRequirement(r => r.setOwnerOnly(true));
export async function run(msg, data) {
const guild = msg.channel?.channel?.guild ?? msg.message?.guild;
if (!guild) {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription("❌ Must be used in a server.").toJSON();
return msg.replyEmbed({ embeds: [embed] });
}
const channelCounts = new Map();
for (const [, state] of this.observedVoiceUsers) {
if (state.guildId !== guild.id) continue;
channelCounts.set(state.channelId, (channelCounts.get(state.channelId) ?? 0) + 1);
}
for (const [, state] of this.observedVoiceBots) {
if (state.guildId !== guild.id) continue;
channelCounts.set(state.channelId, (channelCounts.get(state.channelId) ?? 0) + 1);
}
if (channelCounts.size === 0) {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription("No one is in voice.").toJSON();
return msg.replyEmbed({ embeds: [embed] });
}
const getChannelName = async (channelId) => {
const cached = this.client.channels.cache.get(channelId);
if (cached?.name) return cached.name;
const guildCached = guild.channels?.cache?.get?.(channelId) ?? guild.channels?.get?.(channelId);
if (guildCached?.name) return guildCached.name;
if (guild.channels) {
const all = typeof guild.channels.values === "function"
? [...guild.channels.values()] : Object.values(guild.channels);
const found = all.find(c => (c.id ?? c.channel_id) === channelId);
if (found?.name) return found.name;
}
try {
const fetched = await this.client.channels.fetch(channelId);
if (fetched?.name) return fetched.name;
} catch (_) {}
return `Unknown (${channelId})`;
};
let desc = "";
for (const [channelId, total] of channelCounts) {
const name = await getChannelName(channelId);
desc += `🔊 **${name}**: ${total} member${total !== 1 ? "s" : ""}\n`;
}
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle("🎙️ Voice Channel Members")
.setDescription(desc.trim())
.toJSON();
msg.replyEmbed({ embeds: [embed] });
}
+22
View File
@@ -0,0 +1,22 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
export const command = new CommandBuilder()
.setName("thumbnail")
.setDescription("Request the thumbnail of the currently playing song.", "commands.thumbnail")
.addAliases("thumb")
.setCategory("music");
export async function run(msg) {
const p = await this.getPlayer(msg);
if (!p) return;
const data = await p.getThumbnail();
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription(data.msg);
if (data.image) embed.setImage(data.image);
msg.replyEmbed({ embeds: [embed.toJSON()] });
}
+41
View File
@@ -0,0 +1,41 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
const MAX_VOLUME = 200;
export const command = new CommandBuilder()
.setName("volume")
.setDescription("Get or change the current volume.", "commands.volume")
.setCategory("music")
.addNumberOption(o =>
o.setName("volume")
.setDescription(`New volume in % (0–${MAX_VOLUME}). Omit to see the current volume.`)
.setRequired(false)
)
.addAliases("v", "vol");
export async function run(message, data) {
const p = await this.getPlayer(message, false, false, false);
if (!p) return;
const volOption = data.get("volume");
const raw = volOption?.value;
const embed = new EmbedBuilder().setColor(getGlobalColor());
if (!volOption || raw == null || isNaN(Number(raw))) {
const current = Math.round((p.preferredVolume ?? 1) * 100);
embed.setDescription(`🔊 Current volume: \`${current}%\``);
} else {
const pct = Number(raw);
if (pct < 0 || pct > MAX_VOLUME) {
embed.setDescription(`❌ Volume must be between \`0\` and \`${MAX_VOLUME}%\`.`);
} else {
p.setVolume(pct / 100);
embed.setDescription(`🔊 Volume changed to \`${pct}%\` for this session.`);
}
}
message.replyEmbed({ embeds: [embed.toJSON()] });
}
+64
View File
@@ -0,0 +1,64 @@
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
import { PermissionFlags } from "@fluxerjs/core";
const MAX_VOLUME = 200;
export const command = new CommandBuilder()
.setName("volumedefault")
.setDescription("View or set the server default volume. (Requires Manage Server to set)", "commands.volumedefault")
.setCategory("music")
.addNumberOption(o =>
o.setName("volume")
.setDescription(`New volume in % (0–${MAX_VOLUME}) to save as server default. Leave empty to view current.`)
.setRequired(false)
)
.addAliases("vd");
export async function run(message, data) {
const p = await this.getPlayer(message, false, false, false);
if (!p) return;
const set = this.getSettings(message);
const authorId = message.message?.author?.id;
const guild = message.message?.guild ?? null;
const member = guild?.members?.get(authorId) ?? message.message?.member ?? null;
const isOwner = (this.handler?.owners ?? []).includes(authorId);
const hasManage = isOwner
|| member?.permissions?.has(PermissionFlags["Administrator"])
|| member?.permissions?.has(PermissionFlags["ManageGuild"]);
const volOption = data.get("volume");
const raw = volOption?.value;
const embed = new EmbedBuilder().setColor(getGlobalColor());
if (!volOption || raw === null || raw === undefined || isNaN(Number(raw))) {
const currentDefault = set?.get("volume") ?? 100;
const currentPlayerVol = Math.round((p.preferredVolume ?? 1) * 100);
embed
.setTitle("🔊 Volume Settings")
.setDescription(
`• Server default: \`${currentDefault}%\`\n` +
`• Current player volume: \`${currentPlayerVol}%\`\n\n` +
(hasManage
? `To change the default, use: \`${set?.get("prefix") ?? "%"}volumedefault <0-${MAX_VOLUME}>\``
: `⚠️ You need **Manage Server** permission to change the default.`)
);
} else if (!hasManage) {
embed.setDescription("❌ You need **Manage Server** permission to set the server default volume.");
} else {
const pct = Number(raw);
if (pct < 0 || pct > MAX_VOLUME) {
embed.setDescription(`❌ Volume must be between \`0\` and \`${MAX_VOLUME}%\`.`);
} else {
p.setVolume(pct / 100);
if (set) set.set("volume", pct);
embed.setDescription(`🔊 Server default volume saved as \`${pct}%\`.`);
}
}
message.replyEmbed({ embeds: [embed.toJSON()] });
}