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

+17
View File
@@ -0,0 +1,17 @@
node_modules/
storage/data
config.json
settings.json
remix-settings.json
cmdUsage.md
bot.js
bin/
test_data/
*.code-workspace
*old.js
.ytcache/
.yt_auth.json
yt_auth.json
visitor_data.json
.moonlink/
storage/recovery.json
+30
View File
@@ -0,0 +1,30 @@
MIT License
Copyright (c) 2026 Remix
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
BRANDING NOTICE
The name "Remix", the Remix logo, and all associated graphical depictions
(banners, icons, etc.) are under PROPRIETARY copyright of the project creator.
The MIT license does NOT grant you any rights to use the name "Remix" or its
branding in production. If you are self-hosting this software, you must use a
different name and logo.
+91
View File
@@ -0,0 +1,91 @@
<p align="center">
<a href="https://github.com/remix-bot">
<img src="https://i.imgur.com/8hD1Jur.png" alt="Logo" width="80" height="80">
</a>
<h2 align="center">Remix</h2>
<p align="center">
The best high quality Fluxer music bot.
<br>
<a href="https://web.fluxer.app/oauth2/authorize?client_id=1478084469635211806&scope=bot&permissions=3206208">Invite to your server</a>
·
<a href="https://fluxer.gg/Remix">Report bug</a>
·
<a href="https://fluxer.gg/Remix">Request Feature</a>
</p>
</p>
## About The Project
Remix is a free and open source music bot for Fluxer built on [fluxerjs](https://github.com/fluxerjs/core). All commands on Remix are free and will always be free to use.
## Commands
Below is a table of all of Remix's commands.
| Name | Description | Format | Alias |
|-----------|----------------------------------------------------------------------------------------------------|-----------------------------|-------------------------|
| clear | Remove all songs from the queue. | %clear | clear, c |
| join | Make the bot join a specific voice channel. | %join 'Channel ID: channel' | join |
| leave | Make the bot leave your current voice channel | %leave | leave, l |
| list | List the queue in your current voice channel. | %list | list, queue |
| loop | Toggle the looping of your queue/song. | %loop <queue \| song> | loop |
| np | Request the name and URL of the currently playing song. | %np | np, current, nowplaying |
| pause | Pause the playback in your voice channel | %pause | pause |
| play | Play a song from URL/query or a playlist by URL. | %play 'query: text' | play, p |
| player | Create an emoji player control for your voice channel | %player | player |
| playnext | Play a song from URL/query or a playlist by URL. The result will be added to the top of the queue. | %playnext 'query: text' | playnext, pn |
| remove | Remove a specific song from the queue. | %remove 'index: number' | remove |
| resume | Resume the playback in your voice channel | %resume | resume |
| search | Display the search results for a given query | %search 'query: text' | search |
| settings | Change/Get settings in the current server. | %settings <set \| get> | settings, s |
| shuffle | Re-orders the queue randomly. | %shuffle | shuffle |
| skip | Skip the current playing song. | %skip | skip |
| stats | Display stats about the bot like the uptime. | %stats | stats, info |
| test | A test command used for various purposes. | %test 'number: number' | test |
| thumbnail | Request the thumbnail of the currently playing song. | %thumbnail | thumbnail, thumb |
| volume | Change the current volume. | %volume 'volume: number' | volume, v |
## Getting Started
Firstly, you have to [invite Remix](https://web.fluxer.app/oauth2/authorize?client_id=1478084469635211806&scope=bot&permissions=3206208). Then use the `%help` command to get a list of commands that you can use through the bot.
## Hosting The Bot
If you're self-hosting Remix, please make it clear that it is **not the main instance** (or **change the name**) but give credit by **linking to this repo** (for example, in the bot's profile - something like `This bot <is based on/is an instance of> [Remix](https://github.com/remix-bot/fluxer)` will suffice).
- Clone this repo (`git clone https://github.com/remix-bot/fluxer.git`)
- Install the dependencies (`npm install`)
- Set up a `config.json` file
- Rename the `config.example.json` file and fill out the missing values. You can generate Spotify credentials [here](https://developer.spotify.com/)
- A MySQL database is required. For setup instructions see [DB Setup](#setup-database).
- Set up a [NodeLink](https://github.com/PerformanC/NodeLink) instance and configure the `nodelink` section in `config.json`:
```json
"nodelink": {
"host": "localhost",
"port": 3000,
"password": "youshallnotpass"
}
```
- Run the bot (`node index.mjs`)
## Setup Database
1. The main thing you'll need is a MySQL database accessible to your server, either publicly or locally.
2. Create a separate database. This way none of your other data collides with Remix.
3. Enter the connection details into the respective fields in the `config.json` file.
4. Run the following SQL commands to create all the necessary tables:
```sql
CREATE TABLE `settings` (
`id` varchar(70) NOT NULL,
`data` json NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
```
5. You're good to go! If you've used the old settings system and want to migrate your data, check the README in the `settings` folder.
## Contact
If you have any questions or would like to talk with other Remix users you can join our Fluxer server <a href="https://fluxer.gg/Remix">here</a>.
---
&copy; 2026 Remix. Code licensed under [MIT](LICENSE). The Remix name and branding are proprietary and may not be reused.
+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()] });
}
+98
View File
@@ -0,0 +1,98 @@
{
"token": "your bot token",
"fluxer.js": {
"Comment": "Configuration data for @fluxerjs/core Client options. See: https://github.com/fluxerjs/core"
},
"fluxer-api": {
"Comment": "Configuration options for a fluxer REST client if self-hosting. See: https://docs.fluxer.app"
},
"prefix": "your desired prefix (such as %)",
"presenceInterval": null,
"presenceContents": [],
"spotify": {
"clientId": "your spotify client id",
"clientSecret": "your spotify client secret"
},
"nodelink": {
"host": "localhost",
"port": 3000,
"password": "youshallnotpass"
},
"comment-radio": {
"message": "If you have radio stations you'd like to connect, add them to the array below. Radio stations must be rendered like following:",
"station": {
"name": "zamrock",
"detailedName": "ᘔᗩᗰᘔᗩᗰᖴOᖴᒪIᖴE",
"thumbnail": "https://zamrock.net/wp-content/uploads/2024/06/Zamrock_rd_logo_0004-1.gif",
"url": "url to stream from; this will be kept private",
"description": "Genre: Zamrock, provided by [Zamrock.net](https://zamrock.net/)",
"author": {
"name": "Zamrock",
"url": "https://zamrock.net"
},
"keyWords": ["radio", "zamrock", "psychedelic", "blues", "rock"]
}
},
"radio": [],
"cache": {
"guilds": {
"enabled": true,
"max": 5000
},
"members": {
"enabled": true,
"max": 10000
}
},
"helpCatalog": true,
"helpPagination": true,
"mysql": {
"host": "your-mysql-host.com",
"port": 3306,
"user": "youruser",
"password": "password of your user",
"database": "name of the target database"
},
"webPort": 80,
"dashboardUrl": "The url the dashboard is accessible with.",
"ssl": {
"private": "path-to-private-key.pem",
"cert": "path-to-certificate.pem",
"useSSL": false,
"httpPort": 80
},
"sessionSecret": "secret for the expressjs session middleware; https://www.npmjs.com/package/express-session#user-content-secret",
"geniusToken": "Genius access token (Used for lyrics); optional",
"owners": ["user id for owner-only commands", "another user id"],
"playerAFKTimeout": 60000,
"Comment": "The above specifies the time in ms after which a player goes inactive; Optional.",
"customStatsFooter": "Text shown in the footer of the %stats embed; optional.",
"embedColor": "0xe9196c",
"logging": {
"Comment": "Control which log categories appear in the console. Set 'enabled' to false to silence everything except errors. Set any category to false to silence just that group.",
"enabled": true,
"player": true,
"inactivity": true,
"voiceState": true,
"voice247": true,
"mediaplayer": true,
"commands": true,
"guild": true,
"recovery": true,
"settings": true,
"worker": true,
"moonlink": true
},
"timers": {
"Comment": "All timing values in milliseconds (ms). 1000ms = 1 second, 60000ms = 1 minute.",
"inactivityTimeout": 180000,
"aloneCheckInterval": 30000,
"aloneCheckDebounce": 500,
"rejoin247Delay": 3000,
"leave247RejoinDelay": 5000,
"playerUpdateInterval": 5000,
"searchSessionTimeout": 30000,
"playerSessionTimeout": 300000,
"intentionalLeaveTTL": 10000
}
}
+1012
View File
File diff suppressed because it is too large. Load diff
+5352
View File
File diff suppressed because it is too large. Load diff
+25
View File
@@ -0,0 +1,25 @@
{
"type": "module",
"dependencies": {
"@fluxerjs/core": "^1.3.0",
"@fluxerjs/voice": "^1.3.0",
"@livekit/rtc-node": "^0.13.24",
"express": "^4.18.2",
"ffmpeg-static": "^5.1.0",
"ffprobe-static": "^3.1.0",
"follow-redirects": "^1.15.2",
"genius-lyrics": "^4.4.3",
"moonlink.js": "^5.2.0",
"mysql": "^2.18.1",
"revoice.js": "^0.2.1694",
"util": "^0.12.5",
"ws": "^8.19.0"
},
"scripts": {
"dev": "node --inspect index.mjs --trace-warnings",
"start": "node index.mjs",
"commands": "node index.mjs usage",
"defaultsSync": "node index.mjs sreload",
"migrate": "node settings/migrate.mjs"
}
}
+37
View File
@@ -0,0 +1,37 @@
# WIP Web Dashboard for Remix
Control Remix through a web interface and set server settings and similar.
Installation instructions will follow soon:tm:
## Setup
1. Create a mysql server with the following table:
```MySQL
CREATE TABLE `ksiTokens` (
`user` varchar(26) NOT NULL,
`id` varchar(50) NOT NULL,
`token` varchar(70) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`createdAt` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
CREATE TABLE `logins` (
`user` text NOT NULL,
`id` varchar(50) NOT NULL,
`token` varchar(70) NOT NULL,
`verified` tinyint(1) NOT NULL,
`createdAt` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
```
2. Fill out the connection details in `config.json` in the remix root directory (See `config.example.json`)
3. SSL setup:
- Create a certificate. For example [using Let's Encrypt](https://letsencrypt.org/de/getting-started/)
- Find the path to your private key and certificate pem files. Certbot uses `/etc/letsencrypt/live/remix.fairuse.org/privkey.pem` for the private key and `/etc/letsencrypt/live/remix.fairuse.org/fullchain.pem` for the certificate file. Fill in the paths in the config file
- set `useSSL` in `config.json` to `true`
- Make sure to configure the ports correctly. HTTPS connects to port `443` so make sure to set `webPort` accordingly.
Credits for Website design:
- NoLogicAlan
- ophx
- ShadowLp174
- Fantic
+130
View File
@@ -0,0 +1,130 @@
import { EventEmitter } from "node:events";
import { logger } from "../src/constants/Logger.mjs";
import * as fs from "node:fs";
import * as mysql from "mysql";
export class ServerSettings {
/** @type {string} */
id;
/** @type {SettingsManager} */
manager;
data = {};
constructor(id, mgr) {
this.id = id; this.manager = mgr;
this.loadDefaults();
}
set(key, value) { this.data[key] = value; this.manager.update(this, key); }
get(key) { return this.data[key]; }
reset(key) { return this.set(key, this.manager.defaults[key]); }
getAll() { return this.data; }
loadDefaults() { for (let key in this.manager.defaults) { this.data[key] = this.manager.defaults[key]; } }
checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } }
deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } }
get serializationData() { return { ...this.data, id: this.id }; }
serialize() { return this.serializationData; }
serializeObject() { return this.serializationData; }
}
export class SettingsManager extends EventEmitter {
/** @abstract @type {Object} */
defaults;
/** @abstract */
update(server, key) { }
/** @abstract @returns {ServerSettings} */
getServer(id) { }
/** @abstract @returns {boolean} */
hasServer(id) { }
/** @abstract @returns {boolean} */
isOption(key) { }
}
export class MySqlSettingsManager extends SettingsManager {
guilds = new Map();
descriptions = {};
defaults = {};
db = null;
constructor(config, defaultsPath) {
super();
this.db = mysql.createPool({ connectionLimit: 15, ...config });
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
this.load();
}
query(query) {
return new Promise(res => {
this.db.query(query, (error, results, fields) => { res({ error, results, fields }); });
});
}
async load() {
const res = await this.query("SELECT * FROM settings");
if (res.error) {
this._loadAttempts = (this._loadAttempts || 0) + 1;
const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000);
logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error);
return setTimeout(() => { this.load(); }, delay);
}
this._loadAttempts = 0;
res.results.forEach((r) => {
const server = new ServerSettings(r.id, this);
server.deserialize(JSON.parse(r.data));
server.checkDefaults(this.defaults);
this.guilds.set(server.id, server);
});
this.emit("ready");
}
async remoteUpdate(server, key) {
const val = server.data[key];
// Arrays/objects must go through remoteSave — JSON_SET with scalar
// interpolation corrupts arrays by merging IDs into one number on read-back.
if (Array.isArray(val) || (typeof val === "object" && val !== null)) {
return this.remoteSave(server);
}
const escapedKey = mysql.escape(`$.${key}`);
// Preserve native boolean/number types so MySQL stores them as JSON
// booleans/numbers, not as strings. String(true) would store "true"
// which then reads back as a string — breaking strict equality checks.
const escapedVal = (typeof val === "boolean" || typeof val === "number")
? mysql.escape(val)
: mysql.escape(String(val));
const escapedId = mysql.escape(server.id);
const r = await this.query(
`UPDATE settings SET data = JSON_SET(data, ${escapedKey}, ${escapedVal}) WHERE id=${escapedId}`
);
if (r.error) logger.error("[Settings] remoteUpdate error:", r.error);
}
async remoteSave(server) {
const escapedData = mysql.escape(JSON.stringify(server.data));
const escapedId = mysql.escape(server.id);
const r = await this.query(
`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}`
);
if (r.error) logger.error("[Settings] remoteSave error:", r.error);
}
loadDefaultsSync(filePath) {
const d = fs.readFileSync(filePath, "utf8");
const parsed = JSON.parse(d);
this.descriptions = parsed.descriptions;
this.defaults = parsed.values;
}
async saveAsync() {
await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v)));
}
async create(id, server) {
const escapedId = mysql.escape(id);
const escapedData = mysql.escape(JSON.stringify(server.data));
const r = await this.query(
`INSERT INTO settings (id, data) VALUES (${escapedId}, ${escapedData})`
);
if (r.error) logger.error("[Settings] create error:", r.error);
}
update(server, key) {
if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); }
const s = this.guilds.get(server.id);
s.data[key] = server.data[key];
this.remoteUpdate(server, key);
}
isOption(key) { return key in this.defaults; }
hasServer(id) { return this.guilds.has(id); }
getServer(id) { return (!this.guilds.has(id)) ? new ServerSettings(id, this) : this.guilds.get(id); }
}
+22
View File
@@ -0,0 +1,22 @@
import { SettingsManager, RemoteSettingsManager } from "./Settings.mjs";
import fs from "node:fs";
import { logger } from "../src/constants/Logger.mjs";
const config = JSON.parse(fs.readFileSync(new URL("../config.json", import.meta.url)));
const sm = new SettingsManager();
const rsm = new RemoteSettingsManager(config.mysql);
const servers = sm.guilds.entries();
rsm.on("ready", async () => {
for (const [id, s] of servers) {
logger.settings("[migrate] Processing server:", id);
if (rsm.hasServer(id)) {
await rsm.remoteSave(s);
continue;
}
await rsm.create(id, s);
}
process.exit(0);
});
+16
View File
@@ -0,0 +1,16 @@
export default {
prefix: function(value, data) {
// prefix change hook — Settings handles persistence
},
pfp: function(value, data) {
if (value !== "default") {
return "Profile picture customisation is not supported on Fluxer.";
}
},
// stay_247 is managed exclusively by the %247 command and auto-join logic.
stay_247: function(value, data) {
return false;
},
};
+753
View File
@@ -0,0 +1,753 @@
import { pathToFileURL } from "node:url";
import { logger } from "./constants/Logger.mjs";
import { Utils } from "./Utils.mjs";
import { EventEmitter } from "node:events";
import { Message, MessageHandler, PageBuilder } from "./MessageHandler.mjs";
import { Client, PermissionFlags } from "@fluxerjs/core";
import { SettingsManager } from "./Settings.mjs";
import path from "node:path";
import * as fs from "node:fs";
export class CommandBuilder {
constructor() {
this.name = null;
this.description = null;
this.id = null;
this.aliases = [];
/** @type {CommandBuilder[]} */
this.subcommands = [];
/** @type {Option[]} */
this.options = [];
/** @type {CommandRequirement[]} */
this.requirements = [];
this.category = "default";
this.examples = [];
this.uid = Utils.uid();
this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`";
/** @type {CommandBuilder} */
this.parent = null;
}
setName(n) { this.name = n; this.aliases.push(n.toLowerCase()); return this; }
setDescription(d) { this.description = d; return this; }
setId(id) { this.id = id; return this; }
get command() { return (this.parent) ? this.parent.command + " " + this.name : this.name; }
setRequirement(config) { let req = config(new CommandRequirement()); this.requirements.push(req); return this; }
addSubcommand(config) { let sub = config(new CommandBuilder()); sub.parent = this; this.subcommands.push(sub); return this; }
addStringOption(config, flag = false) { this.options.push(config(Option.create("string", flag))); return this; }
addNumberOption(config, flag = false) { this.options.push(config(Option.create("number", flag))); return this; }
addBooleanOption(config, flag = false) { this.options.push(config(Option.create("boolean", flag))); return this; }
addChannelOption(config, flag = false) { this.options.push(config(Option.create("channel", flag))); return this; }
addUserOption(config, flag = false) { this.options.push(config(Option.create("user", flag))); return this; }
addTextOption(config) {
if (this.options.findIndex(e => e.type === "text") !== -1) throw new Error("There can only be 1 text option.");
this.options.push(config(new Option("text")));
return this;
}
addChoiceOption(config, flag = false) { this.options.push(config(Option.create("choice", flag))); return this; }
addAlias(alias) { if (this.aliases.findIndex(e => e === alias.toLowerCase()) !== -1) return this; this.aliases.push(alias.toLowerCase()); return this; }
addAliases(...aliases) { aliases.forEach((a) => this.addAlias(a)); return this; }
setCategory(cat) { this.category = cat; return this; }
addExamples(...examples) { this.examples.push(...examples); return this; }
}
export class CommandRequirement {
ownerOnly = false;
constructor() {
this.permissions = [];
this.permissionError = "You don't have the needed permissions to run this command!";
return this;
}
setOwnerOnly(bool) { this.ownerOnly = bool; return this; }
/**
* @param {string} p Fluxer permission string (discord.js-style, e.g. "ManageChannels", "ManageGuild")
*/
addPermission(p) { this.permissions.push(p); return this; }
addPermissions(...p) { this.permissions.push(...p); return this; }
getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; }
setPermissionError(e) { this.permissionError = e; return this; }
}
export class Option {
// Fluxer uses discord.js-like channel mentions: <#id> and user mentions <@id>
channelRegex = /^<#(?<id>\d+)>/;
userRegex = /^<@!?(?<id>\d+)>/;
idRegex = /^(?<id>\d+)/;
/** @type {Function} */
dynamicDefault;
constructor(type = "string") {
this.name = null;
this.description = null;
this.required = false;
this.id = null;
this.uid = Utils.uid();
this.type = type;
this.tError = null;
this.aliases = [null];
this.choices = [];
this.translations = {};
this.defaultValue = null;
this.dynamicDefault = null;
}
static create(type, flag = false) {
return (!flag) ? new Option(type) : new Flag(type);
}
setName(n) { this.name = n; this.aliases[0] = n; return this; }
setDescription(d) { this.description = d; return this; }
setRequired(r) { this.required = r; return this; }
setId(id) { this.id = id; return this; }
setType(t) { this.type = t; return this; }
addFlagAliases(...a) { this.aliases.push(...a); return this; }
addChoice(c) { if (this.type !== "choice") throw new Error(".addChoice is only available for choice options!"); this.choices.push(c); return this; }
addChoices(...cs) { if (this.type !== "choice") throw new Error(".addChoices is only available for choice options!"); cs.forEach(c => this.addChoice(c)); return this; }
setDefault(value) { this.defaultValue = value; return this; }
setDynamicDefault(callback) { this.dynamicDefault = callback; return this; }
empty(i) {
if (i === undefined || i === null) return true;
return (!i && !(String(i).includes("0")));
}
/**
* @param {string} i
* @param {Client} client
* @param {import("@fluxerjs/core").Message} msg
* @param {string} [type]
* @returns {boolean}
*/
validateInput(i, client, msg, type) {
switch (type || this.type) {
case "text":
case "string":
return !!i;
case "number":
return !isNaN(i) && !isNaN(parseFloat(i));
case "boolean":
return i === "0" || i === "1" || i?.toLowerCase() === "true" || i?.toLowerCase() === "false";
case "choice":
return this.choices.includes(i);
case "user":
return this.userRegex.test(i) || this.idRegex.test(i);
case "channel":
if (i === undefined) return false;
return this.channelRegex.test(i) || this.idRegex.test(i) || client.channels.cache.some(c => c.name === i);
case "voiceChannel": {
if (!i) return false;
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
const guildId = msg?.channel?.guildId ?? msg?.guildId;
// dry-run eval mode
if (guildId === "eval") return (results) ? results.groups["id"] : i;
const voiceTypes = [2, 13]; // GuildVoice and GuildStageVoice
const byName = msg?.guild?.channels?.cache?.find(c => c.name === i && voiceTypes.includes(c.type));
const cObj = results
? client.channels.cache.get(results.groups["id"])
: (byName ?? null);
return cObj ? voiceTypes.includes(cObj.type) : false;
}
}
}
/**
* @param {string} i
* @param {Client} client
* @param {import("@fluxerjs/core").Message} msg
* @param {string} [type]
* @returns {string|number|boolean}
*/
formatInput(i, client, msg, type) {
switch (type || this.type) {
case "text":
case "string":
return i;
case "number":
return parseFloat(i);
case "boolean":
return i?.toLowerCase() === "true" || i === "1";
case "choice":
return i;
case "user": {
const rs = this.userRegex.exec(i) ?? this.idRegex.exec(i);
return rs?.groups["id"] ?? null;
}
case "channel": {
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
const channel = client.channels.cache.find(c => c.name === i);
return results ? results.groups["id"] : (channel ? channel.id : null);
}
case "voiceChannel": {
const r = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
const guildId = msg?.channel?.guildId ?? msg?.guildId;
if (guildId === "eval") return r ? r.groups["id"] : (i || null);
const voiceTypes = [2, 13];
const c = msg?.guild?.channels?.cache?.find(c => c.name === i && voiceTypes.includes(c.type));
return r ? r.groups["id"] : (c ? c.id : null);
}
}
}
get typeError() {
if (this.tError) return this.tError;
switch (this.type) {
case "choice":
return "Invalid value '$currValue'. The option `" + this.name + "` has to be one of the following options: \n- " + this.choices.join("\n- ") + "\nSchematic: `$previousCmd <" + this.type + ">`";
case "voiceChannel":
case "channel":
return "Invalid value '$currValue'. The option `" + this.name + "` has to be a channel mention, id, or name.\nSchematic: `$previousCmd <" + this.type + ">`";
default:
return "Invalid value '$currValue'. The option `" + this.name + "` has to be of type `" + this.type + "`.\nSchematic: `$previousCmd <" + this.type + ">`";
}
}
set typeError(e) { this.tError = e; }
}
export class Flag extends Option {
constructor(type = "string") {
if (type === "text") throw new Error("Flags can't be of type 'text'!");
super(type);
}
}
export class PrefixManager {
/** @type {SettingsManager} */
settings;
constructor(settings) { this.settings = settings; }
getPrefix(guildId) { return this.settings.getServer(guildId).get("prefix"); }
}
export class HelpHandler {
/** @type {CommandHandler} */
commands;
commandsPerPage = 5;
paginationHandler = (msg, helpHandler, cmds) => {
let form = "Available Commands (page $currentPage/$maxPage): \n\n$content";
form += "\n\nRun `$prefix$helpCmd <command>` to learn more about it. You can also include subcommands.\n";
form += "For example: `$prefix$helpCmd settings get`\n\n";
form += "Tip: Use the arrows beneath this message to turn pages, or specify the required page by using `$prefix$helpCmd <page number>`";
const contents = cmds.map((cmd, i) => {
return (i + 1) + ". **" + cmd.name + "**: " + (cmd.description || "").split("\n")[0];
});
const pages = new PageBuilder(contents)
.setForm(helpHandler.commands.format(form, msg.message.guildId))
.setMaxLines(helpHandler.commandsPerPage);
helpHandler.commands.messages.initPagination(pages, msg);
return null;
}
customHelpHandler = null;
constructor(commands) { this.commands = commands; }
static capitalise(string) {
if (string.length < 1) return string;
if (string.length === 1) return string.toUpperCase();
return string.charAt(0).toUpperCase() + string.slice(1);
}
userCommands(cmds) {
return (cmds || this.commands.commands).filter(c =>
c.requirements.findIndex(r => r.ownerOnly) === -1
);
}
pageNumber() {
return Math.ceil(this.commands.commands.length / this.commandsPerPage);
}
help(message) {
if (this.customHelpHandler) return this.customHelpHandler(message);
if (this.paginationHandler) return this.genHelp(null, message, true);
return this.getHelpPage(0, message);
}
getHelpPage(n, msg, cmds = null) {
if (!cmds) cmds = this.commands.commands;
if (!(this.commandsPerPage < cmds.length)) return this.genHelp(null, msg, false, cmds);
let offset = this.commandsPerPage * n;
const commands = cmds.slice(offset, offset + this.commandsPerPage);
let max = Math.ceil(cmds.length / this.commandsPerPage);
return this.genHelp({ curr: n + 1, max, offset }, msg, false, commands);
}
genHelp(page, msg, paginate = false, cmds = null) {
cmds = this.userCommands(cmds);
if (this.paginationHandler && msg && paginate) return this.paginationHandler(msg, this, cmds);
let p = (page) ? ` (page ${page.curr}/${page.max})` : "";
const indexOffset = (page) ? page.offset : 0;
let content = "Available Commands" + p + ": \n\n";
if (page && page.curr !== 1) content += (indexOffset) + ". [...]\n";
cmds.forEach((cmd, i) => { content += (i + 1 + indexOffset) + ". **" + cmd.name + "**: " + cmd.description + "\n"; });
if (page && page.curr !== page.max) content += (cmds.length + indexOffset) + ". [...]\n";
content += "\nRun `$prefix$helpCmd <command>` to learn more about it. You can also include subcommands.\n";
content += "For example: `$prefix$helpCmd command subcommandName`";
if (page) content += "\n\nTip: Turn pages by using `$prefix$helpCmd <page number>`";
return this.commands.format(content, msg.message.guildId);
}
commandDescription(command) { return command.description; }
commandUsage(cmd, msg) {
if (cmd.subcommands.length > 0) {
return this.commands.format("$prefix" + cmd.command, msg.message.guildId) + " <" + cmd.subcommands.map(e => e.name).join(" | ") + "> [...]";
}
let options = this.commands.format("$prefix" + cmd.command, msg.message.guildId);
cmd.options.forEach(o => {
if (o.type === "text") return;
if (o instanceof Flag)
return options += (o.type === "choice") ? "-" + o.aliases[0] + " <" + o.choices.join(" | ") + ">" : " -" + o.aliases[0] + " '" + o.type + "'";
options += (o.type === "choice") ? " <" + o.choices.join(" |") + ">" : " '" + o.name + ": " + o.type + "'";
});
let o = cmd.options.find(e => e.type === "text");
if (o) options += "'" + o.name + ": " + o.type + "'";
return options.trim();
}
getCommandHelp(command, msg) {
let content = `${HelpHandler.capitalise(command.name)}\n`;
content += this.commandDescription(command, msg) + "\n\n";
content += "Usage: \n💻 `" + this.commandUsage(command, msg) + "`\n\n";
if (command.examples.length > 0)
content += "Example(s): \n- `" + command.examples.map(e => this.commands.format(e, msg.message.guildId)).join("`\n- `") + "`\n\n";
if (command.aliases.length > 1) {
content += "Aliases: \n";
command.aliases.forEach(alias => { content += "- " + alias + "\n"; });
content += "\n";
}
if (command.subcommands.length > 0) {
content += "Subcommands: \n";
command.subcommands.forEach(s => {
content += "- " + s.name + ": " + (this.commandDescription(s, msg) || "").split("\n")[0] + ((s.options.length > 0) ? "; (`" + s.options.length + " option(s)`)" : "") + "\n";
});
content += "\n";
} else if (command.options.length > 0) {
content += "Arguments: \n";
command.options.forEach(o => {
const optional = ((o.required) ? "" : "?");
const flag = (o instanceof Flag) ? "-" : "";
if (o.type === "choice") {
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + ";\n - Allowed values: `" + o.choices.join("`, `") + "`\n - Aliases: `" + o.aliases.join("`, `") + "`\n";
} else {
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + "\n - Aliases: `" + o.aliases.join("`, `") + "`\n";
}
content += "\n";
});
content += "\n";
}
if (command.requirements.length > 0) {
content += "Requirements: \n";
command.requirements.forEach(r => {
content += "- " + r.getPermissions().map(e => "Permission `" + e + "`").join("\n- ");
});
}
return content.trim();
}
}
export class CommandHandler extends EventEmitter {
onPing = null;
pingPrefix = true;
owners = [];
/** @type {MessageHandler} */
messages;
/** @type {Client} */
client;
/** @type {PrefixManager} */
prefixes;
/** @type {HelpHandler} */
helpHandler;
commandNames = [];
/** @type {CommandBuilder[]} */
commands = [];
invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`";
textWrapError = "Malformed string `$value`: Missing a closing quote character (`$quote`) after the desired string.";
constructor(handler, prefix = "!") {
super();
this.messages = handler;
this.client = handler.client;
this.prefix = prefix;
this.helpHandler = new HelpHandler(this);
this.helpCommand = "help";
this.replyHandler = (message, msg) => {
msg.replyEmbed(this.format(message, msg.channel.channel.guildId));
};
this.messages.onMessage(this.messageHandler.bind(this));
}
getPrefix(guildId) { return this.prefixes.getPrefix(guildId); }
setPingPrefix(bool) { this.pingPrefix = bool; }
setPrefixManager(manager) { this.prefixes = manager; }
setHelpHandler(handler) { this.helpHandler = handler; }
format(text, guildId) {
const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId);
return text
.replace(/\$prefix/gi, prefix)
.replace(/\$helpCmd/gi, this.helpCommand);
}
removeCommand(command) {
command.aliases.forEach(a => {
const idx = this.commandNames.indexOf(a);
if (idx !== -1) this.commandNames.splice(idx, 1);
});
const idx = this.commands.findIndex(c => c.uid === command.uid);
if (idx !== -1) this.commands.splice(idx, 1);
}
messageHandler(msg) {
if (!msg || !msg.content) return;
const trimmed = msg.content.trim();
if (/^<@!?\d+>$/.test(trimmed)) {
// Only respond if the bot itself was pinged
const botId = this.client.user?.id;
if (botId && (trimmed === `<@${botId}>` || trimmed === `<@!${botId}>`)) {
return this.onPing?.(msg);
}
return;
}
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
const prefix = this.getPrefix(guildId);
const ping = `<@${this.client.user?.id}>`;
const pingBang = `<@!${this.client.user?.id}>`;
if (!(msg.content.startsWith(prefix) || msg.content.startsWith(ping) || msg.content.startsWith(pingBang))) return;
const len = msg.content.startsWith(prefix) ? prefix.length : (msg.content.startsWith(pingBang) ? pingBang.length : ping.length);
const args = msg.content.slice(len).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
if (!args[0]) return;
if (args[0] === this.helpCommand) {
if (!args[1]) {
const res = this.helpHandler.help(msg);
return (typeof res === "string") ? this.replyHandler(res, msg) : undefined;
}
if (args.length > 1 && Utils.isNumber(args[1])) {
const pageNumber = parseInt(args[1]);
if (pageNumber < 1 || pageNumber > this.helpHandler.pageNumber()) return this.replyHandler("`" + pageNumber + "` is not a valid page number!", msg);
return this.replyHandler(this.helpHandler.getHelpPage(pageNumber - 1, msg), msg);
}
if (args.length <= 2) {
let idx = this.commands.findIndex(e => e.aliases.some(al => al.toLowerCase() === args[1].toLowerCase()));
if (idx === -1) return this.replyHandler("Unknown command `$prefix" + args[1] + "`!", msg);
return this.replyHandler(this.helpHandler.getCommandHelp(this.commands[idx], msg), msg);
}
let currCmd = null;
let prefix2 = "";
for (let i = 0; i < args.slice(1).length; i++) {
let a = args.slice(1)[i];
let curr = (currCmd) ? currCmd.subcommands : this.commands;
let idx = curr.findIndex(e => e.aliases.some(al => al.toLowerCase() === a.toLowerCase()));
if (idx === -1) return this.replyHandler("Unknown command `$prefix" + prefix2 + a + "`!", msg);
currCmd = curr[idx];
prefix2 += a + " ";
}
return this.replyHandler(this.helpHandler.getCommandHelp(currCmd, msg), msg);
}
if (!this.commandNames.includes(args[0].toLowerCase())) {
this.replyHandler("Unknown Command. Use `$prefix$helpCmd` to view all possible commands.", msg);
return;
}
return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg);
}
processCommand(cmd, args, msg, previous = false, external = false) {
// Guard first — cmd could be undefined if called from an edge case
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
if (cmd.requirements.length > 0 && !external) {
if (!this.assertRequirements(cmd, msg)) return;
}
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
if (!external) this.emit("command", { command: cmd, message: msg });
if (cmd.subcommands.length !== 0) {
const idx = cmd.subcommands.findIndex(el => {
if (!args[1]) return false;
return el.name.toLowerCase() === args[1].toLowerCase();
});
if (idx === -1) {
const list = cmd.subcommands.map(s => s.name).join(" | ");
const e = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`".replace(/\$previousCmd/gi, previous).replace(/\$cmdList/gi, list);
return (!external) ? this.replyHandler(e, msg) : e;
}
return this.processCommand(cmd.subcommands[idx], args.slice(1), msg, previous + this.format(" " + cmd.subcommands[idx].name), external);
}
const opts = [];
const texts = [];
const collectArguments = (index, currVal, as) => {
const lastChar = currVal.charAt(currVal.length - 1);
if (lastChar === '"') return { args: as, index };
const a = args[++index];
if (!a) return null;
as.push(a);
return collectArguments(index, a, as);
};
const options = cmd.options.slice().sort((a, b) => {
const aText = (a.type === "text") ? 1 : 2;
const bText = (b.type === "text") ? 1 : 2;
return aText - bText;
});
const STRING_TYPES = ["string", "text", "channel", "voiceChannel"];
const usedOptions = [];
let usedArgumentCount = 0;
for (let i = 0, argIndex = 1; i < options.length; i++) {
if (options[i] instanceof Flag) i++;
const o = options[i];
if (o?.type === "text") { texts.push(o); continue; }
if ((args[argIndex] || "").startsWith("-")) {
const flagName = args[argIndex].slice(1);
const op = cmd.options.find(e => e.aliases.includes(flagName));
if (!op) {
const error = this.invalidFlagError.replace(/\$previousCmd/gi, previous).replace(/\$invalidFlag/gi, "-" + flagName);
return (!external) ? this.replyHandler(error, msg) : error;
}
previous += " " + args[argIndex];
let value = args[++argIndex];
if ((value || "").startsWith('"') && (STRING_TYPES.includes(op.type))) {
const data = collectArguments(argIndex, value, [value]);
if (!data) return this.replyHandler(this.textWrapError.replace(/\$value/gi, args.slice(argIndex).join(" ")).replace(/\$quote/gi, args[argIndex].charAt(0)), msg);
argIndex += data.index - argIndex;
value = data.args.join(" ").slice(1, data.args.join(" ").length - 1);
}
argIndex++;
i--;
const valid = op.validateInput(value, this.client, msg.message);
if (!valid && (op.required || !op.empty(value))) {
const e = op.typeError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value);
return (!external) ? this.replyHandler(e, msg) : e;
}
usedArgumentCount += 2;
previous += " " + value;
opts.push({ value: op.formatInput(value, this.client, msg.message), name: op.name, id: op.id, uid: op.uid });
usedOptions.push(op.uid);
continue;
}
if (!o) continue;
if (opts.findIndex(op => op.uid === o.uid) !== -1) continue;
let value = args[argIndex];
if ((args[argIndex] || "").startsWith('"') && (STRING_TYPES.includes(o.type))) {
const data = collectArguments(argIndex, args[argIndex], [args[argIndex]]);
if (!data) return this.replyHandler(this.textWrapError.replace(/\$value/gi, args.slice(argIndex).join(" ")).replace(/\$quote/gi, args[argIndex].charAt(0)), msg);
argIndex += data.index - argIndex;
value = data.args.join(" ");
value = value.slice(1, value.length - 1);
}
let valid = o.validateInput(value, this.client, msg.message);
if (!valid && o.dynamicDefault) {
value = o.dynamicDefault(this.client, msg);
valid = o.validateInput(value, this.client, msg.message);
}
if (!valid && (o.required || !o.empty(value))) {
const e = o.typeError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value);
return (!external) ? this.replyHandler(e, msg) : e;
}
if (o.empty(value)) value = o.defaultValue;
opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid });
usedOptions.push(o.uid);
previous += " " + value;
argIndex++;
usedArgumentCount++;
}
if (texts.length > 0) {
let o = texts[0];
let text = args.slice(usedArgumentCount + 1).join(" ");
if (o.required && !o.validateInput(text, this.client, msg.message)) {
let e = o.typeError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, text);
return (!external) ? this.replyHandler(e, msg) : e;
}
const quote = (['"', "'"].includes(text.charAt(0))) ? text.charAt(0) : null;
if (quote && text.charAt(text.length - 1) === quote) text = text.slice(1, text.length - 1);
opts.push({ name: o.name, value: text, id: o.id, uid: o.uid });
usedOptions.push(o.uid);
}
options.filter(o => !usedOptions.includes(o.uid)).forEach(o => {
if (!o.defaultValue) return;
opts.push({ name: o.name, value: o.defaultValue, id: o.id, uid: o.uid });
});
const commandRunData = {
command: cmd,
commandId: cmd.id,
options: opts,
message: msg,
get: function (oName) { return this.options.find(o => o.name === oName); },
getById: function (id) { return this.options.find(o => o.id === id); }
};
if (!external) this.emit("run", commandRunData);
return commandRunData;
}
/**
* Checks requirements using fluxerjs (discord.js-like) permission API.
*/
assertRequirements(cmd, msg) {
const authorId = msg.message?.author?.id;
const isOwner = this.owners.includes(authorId);
for (let i = 0; i < cmd.requirements.length; i++) {
let req = cmd.requirements[i];
if (req.ownerOnly && !isOwner) return false;
if (req.permissions.length > 0 && !isOwner) {
const guild = msg.message?.guild ?? null;
if (!guild) continue;
const member = guild.members.get(authorId) ?? null;
if (member?.permissions) {
// cached — check directly
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
if (missing.length > 0) {
this.replyHandler(req.permissionError, msg);
return false;
}
} else {
// not cached — fetch async and re-run
guild.fetchMember(authorId).then(member => {
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
if (missing.length > 0) {
this.replyHandler(req.permissionError, msg);
} else {
// Re-parse args the same way messageHandler does so quoted args survive.
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
const prefix2 = this.getPrefix(guildId2);
const rawContent = msg.message.content;
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
// Pass external=true to skip re-checking requirements and avoid
// re-entering the fetch loop if the member is still not cached.
this.processCommand(cmd, args, msg, false, true);
}
}).catch(() => this.replyHandler(req.permissionError, msg));
return false;
}
}
}
return true;
}
validateInput(type, i, m) { return (new Option()).validateInput(i, this.client, m, type); }
formatInput(type, i, m) { return (new Option()).formatInput(i, this.client, m, type); }
addCommand(builder) {
this.commandNames.push(...builder.aliases);
this.commands.push(builder);
this.commands.sort((a, b) => {
let A = a.name.toUpperCase();
let B = b.name.toUpperCase();
return (A < B) ? -1 : (A > B) ? 1 : 0;
});
return this.commands;
}
}
export class CommandLoader {
/** @type {CommandHandler} */
commands;
/** @type {Map<string, string>} */
commandFiles = new Map();
/** @type {Map<string, Function>} */
runnables = new Map();
context;
constructor(commands, context) {
this.commands = commands;
this.context = context;
this.context.loader ??= this;
// expose loader helpers on context so reload.js can use them
this.context.commandFiles = this.commandFiles;
this.context.runnables = this.runnables;
this.commands.on("run", (data) => {
if (!this.runnables.has(data.command.uid)) return;
const runFc = this.runnables.get(data.command.uid);
try {
const result = runFc.call(this.context, data.message, data);
if (result && typeof result.catch === "function") {
result.catch(e => {
const id = Utils.uid();
logger.error("Error running command; error id #" + id, e);
data.message.replyEmbed("An error occurred. Error id: `#" + id + "`");
});
}
} catch (e) {
const id = Utils.uid();
logger.error("Error running command; error id #" + id, e);
data.message.replyEmbed("An error occurred. Error id: `#" + id + "`");
}
});
}
/**
* Normalise both ESM named-export shape and legacy default-export shape.
* Named ESM: export const command; export function run; export const exportDef
* Legacy CJS: module.exports = { command, run, export }
*/
canonData(cData) {
if (cData.command !== undefined) {
return {
command: cData.command,
run: cData.run,
exportDef: cData.exportDef ?? cData.export ?? null
};
}
const d = cData.default ?? cData;
return {
command: d.command,
run: d.run,
exportDef: d.exportDef ?? d.export ?? null
};
}
loadFromDir(dir) {
const files = fs.readdirSync(dir)
.filter(f => !f.startsWith(".") && (f.endsWith(".js") || f.endsWith(".mjs")));
return Promise.all(files.map(async commandFile => {
const file = path.join(dir, commandFile);
const cData = this.canonData(await import(pathToFileURL(file).href));
const builder = (typeof cData.command === "function")
? cData.command.call(this.context)
: cData.command;
if (!builder) return logger.warn("No builder returned. Skipping '" + commandFile + "'");
if (cData.exportDef)
this.context[cData.exportDef.name] = cData.exportDef.object;
this.commands.addCommand(builder);
this.commandFiles.set(builder.uid, file);
if (!cData.run) return;
this.runnables.set(builder.uid, cData.run);
builder.subcommands.forEach(sub => {
this.runnables.set(sub.uid, cData.run);
});
}));
}
}
File diff suppressed because it is too large. Load diff
+284
View File
@@ -0,0 +1,284 @@
/**
* MoonlinkManager.mjs
*
* Wraps moonlink.js Manager with a custom connector for Fluxer.
* FIXED: Correct payload format for packetUpdate
*/
import { Manager } from "moonlink.js";
import { logger } from "./constants/Logger.mjs";
import { EventEmitter } from "node:events";
import { Events } from "@fluxerjs/core";
// ═══════════════════════════════════════════════════════════════════════════════
// MoonlinkManager ──────────────────────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════
export class MoonlinkManager extends EventEmitter {
/** @type {Manager} */
manager = null;
/** @type {string|null} */
sessionId = null;
/** @type {import("@fluxerjs/core").Client} */
_client = null;
/**
* @param {{ host: string, port: number, password: string, secure?: boolean }} nodeCfg
* @param {import("@fluxerjs/core").Client} client
*/
constructor(nodeCfg, client) {
super();
this.setMaxListeners(50); // reconnects temporarily stack listeners during re-init
this._nodeCfg = nodeCfg;
this._client = client;
this.manager = new Manager({
nodes: [
{
host: nodeCfg.host ?? "localhost",
port: nodeCfg.port ?? 3000,
password: nodeCfg.password ?? "youshallnotpass",
secure: nodeCfg.secure ?? false,
identifier: "main",
}
],
options: {
resume: true,
resumeTimeout: 60_000,
defaultPlayer: {
volume: 100,
selfDeaf: true,
selfMute: false,
autoPlay: false,
autoLeave: false,
},
search: {
defaultPlatform: "ytmsearch",
},
send: (guildId, payload) => this._sendPayload(guildId, payload),
},
});
// Set up voice state forwarding from Fluxer to moonlink
this._setupVoiceForwarding(client);
// Forward key events
this.manager.on("nodeReady", (node) => {
this.sessionId = node.sessionId ?? null;
logger.moonlink(`[Moonlink] Node ready: ${node.identifier} | session: ${this.sessionId}`);
this.emit("ready", this.sessionId);
});
this.manager.on("nodeConnected", (node) => {
logger.moonlink(`[Moonlink] Node connected: ${node.identifier}`);
});
this.manager.on("nodeDisconnect", (node, reason) => {
logger.warn("[Moonlink] Node disconnected:", node.identifier, reason);
});
this.manager.on("nodeError", (node, err) => {
logger.error("[Moonlink] Node error:", node.identifier, err?.message ?? err);
});
this.manager.on("trackStart", (player, track) => {
this.emit("trackStart", player, track);
});
this.manager.on("trackEnd", (player, track, reason) => {
this.emit("trackEnd", player, track, reason);
});
this.manager.on("queueEnd", (player) => {
this.emit("queueEnd", player);
});
this.manager.on("playerDisconnected", (player) => {
this.emit("playerDisconnected", player);
});
}
/**
* Send voice payload to Discord via Fluxer's WebSocket
* @param {string} guildId
* @param {{ op: number, d: object }} payload
* @private
*/
_sendPayload(guildId, payload) {
try {
const shard = this._client?.ws?.shards?.get?.(0);
if (!shard) {
logger.warn("[MoonlinkManager] No WebSocket shard available");
return;
}
if (typeof shard.send === "function") {
shard.send(payload);
} else if (shard.ws?.send) {
shard.ws.send(JSON.stringify(payload));
} else {
logger.warn("[MoonlinkManager] Cannot send - no valid send method found");
}
} catch (e) {
logger.warn("[MoonlinkManager] Send error:", e.message);
}
}
/**
* Forward voice state updates from Fluxer to moonlink
* @param {import("@fluxerjs/core").Client} client
* @private
*/
_setupVoiceForwarding(client) {
// @fluxerjs/core emits VoiceStateUpdate with a SINGLE argument:
// (data: GatewayVoiceStateUpdateDispatchData) — raw gateway snake_case fields.
// This is NOT discord.js style (oldState, newState).
client.on(Events.VoiceStateUpdate, (data) => {
try {
// data is the raw GatewayVoiceStateUpdateDispatchData — always snake_case
const guildId = data.guild_id;
if (!guildId) {
logger.warn("[MoonlinkManager] voiceStateUpdate: No guild_id found in data", data);
return;
}
// Build the proper payload format that moonlink expects:
// { op: 0, t: "VOICE_STATE_UPDATE", d: { guild_id, user_id, channel_id, ... } }
const payload = {
op: 0, // Dispatch
t: "VOICE_STATE_UPDATE",
d: {
guild_id: guildId,
channel_id: data.channel_id ?? null,
user_id: data.user_id,
session_id: data.session_id ?? "",
deaf: data.deaf ?? false,
mute: data.mute ?? false,
self_deaf: data.self_deaf ?? false,
self_mute: data.self_mute ?? false,
self_stream: data.self_stream ?? false,
self_video: data.self_video ?? false,
suppress: data.suppress ?? false,
member: data.member ?? null,
}
};
this.manager.packetUpdate(payload);
} catch (e) {
logger.warn("[MoonlinkManager] voiceStateUpdate forward error:", e.message);
}
});
// Raw WS — only for VOICE_SERVER_UPDATE (VOICE_STATE_UPDATE is handled above via Events listener)
// Store the handler reference so we can remove the stale listener before re-attaching
// on gateway reconnects. Without this, each reconnect stacks another handler on the socket.
const attachRawWs = () => {
try {
const shard0 = client.ws?.shards?.get?.(0);
const wsObj = shard0?.ws ?? null;
if (!wsObj) return;
// Remove previous handler if any
if (this._rawWsHandler) {
try {
if (typeof wsObj.removeEventListener === "function") wsObj.removeEventListener("message", this._rawWsHandler);
else if (typeof wsObj.off === "function") wsObj.off("message", this._rawWsHandler);
} catch (_) {}
}
this._rawWsHandler = (rawData) => {
try {
const text = typeof rawData === "string" ? rawData : rawData?.data;
const payload = typeof text === "string" ? JSON.parse(text) : rawData;
if (payload?.t === "VOICE_SERVER_UPDATE") {
if (!payload.d?.guild_id) {
logger.warn("[MoonlinkManager] VOICE_SERVER_UPDATE: Missing guild_id", payload);
return;
}
this.manager.packetUpdate(payload);
}
} catch (_) {}
};
if (typeof wsObj.addEventListener === "function") {
wsObj.addEventListener("message", this._rawWsHandler);
} else if (typeof wsObj.on === "function") {
wsObj.on("message", this._rawWsHandler);
}
} catch (e) {
logger.warn("[MoonlinkManager] Raw WS setup error:", e.message);
}
};
attachRawWs();
// Re-attach after every gateway reconnect so the new socket gets the listener
client.on(Events.Ready, attachRawWs);
}
/**
* Call after client.login() resolves and client.user.id is available.
* Safe to call on every reconnect — removes stale internal listeners before re-init
* to prevent the MaxListenersExceededWarning that moonlink.js triggers by adding
* a new nodeReady/nodeConnected listener to the node socket on every init() call.
* @param {string} clientId
*/
async init(clientId) {
// Raise the limit on both this emitter and the internal manager so reconnects
// don't spam MaxListenersExceededWarning while we're between socket teardown
// and the re-init completing.
this.setMaxListeners(50);
try { this.manager.setMaxListeners?.(50); } catch (_) {}
// Strip any stale nodeReady listeners the previous init() call registered
// so they don't stack up across gateway reconnects.
try {
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
const sock = node.socket ?? node.ws ?? null;
if (sock && typeof sock.removeAllListeners === "function") {
sock.removeAllListeners("open");
sock.removeAllListeners("close");
sock.removeAllListeners("error");
sock.removeAllListeners("message");
}
}
} catch (_) {}
await this.manager.init(clientId);
}
/**
* Search for tracks. Returns a moonlink SearchResult.
* @param {string} query
* @param {string} [source] e.g. "ytmsearch", "spsearch"
* @param {*} [requester]
*/
search(query, source, requester) {
return this.manager.search({ query, source, requester });
}
/**
* Get or create a moonlink Player for a guild.
* @param {{ guildId: string, voiceChannelId: string, textChannelId?: string, volume?: number }} opts
* @returns {import("moonlink.js").Player}
*/
createPlayer(opts) {
return this.manager.players.create(opts);
}
/**
* Get an existing player by guildId.
* @param {string} guildId
* @returns {import("moonlink.js").Player|undefined}
*/
getPlayer(guildId) {
return this.manager.players.get(guildId);
}
destroy() {
try {
for (const node of this.manager.nodes.nodes.values()) {
node.socket?.close?.();
}
} catch (_) {}
}
}
+1606
View File
File diff suppressed because it is too large. Load diff
+382
View File
@@ -0,0 +1,382 @@
/**
* PlayerManager.mjs — Manages voice channel players across servers
*
* Updated for moonlink.js: passes the MoonlinkManager instance into every
* new Player so it can resolve tracks and retrieve session IDs.
*/
import Player from "./Player.mjs";
import { CommandHandler } from "./CommandHandler.mjs";
import { Message } from "./MessageHandler.mjs";
import { SettingsManager } from "./Settings.mjs";
import { Utils } from "./Utils.mjs";
import { logger } from "./constants/Logger.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "./MessageHandler.mjs";
/** Helper — build a plain embed payload from a description string */
function mkEmbed(desc) {
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] };
}
export class PlayerManager {
/** @type {SettingsManager} */
settings;
/** @type {CommandHandler} */
commands;
/** @type {Map<string, Player>} */
playerMap = new Map();
/** @type {Object} */
config;
/** @type {Object} */
playerConfig;
/**
* @param {SettingsManager} settings
* @param {CommandHandler} commands
* @param {Object} config
* @param {Object} config.config - Parsed config.json
* @param {Object} config.player - Config data passed to new Player instances
*/
constructor(settings, commands, config) {
this.commands = commands;
this.settings = settings;
this.config = config.config;
this.playerConfig = config.player;
}
// ═══════════════════════════════════════════════════════════════════════════
// Voice Channel Detection
// ═══════════════════════════════════════════════════════════════════════════
/**
* Attempt to detect the voice channel a user is currently in.
* @param {Message} message
* @returns {string|null} Voice channel ID or null
*/
checkVoiceChannels(message) {
if (!message) return null;
const userId = message.author?.id;
const serverId = message.channel?.server_id ??
message.channel?.serverId ??
message.message?.server_id ??
message.message?.serverId;
if (!userId) return null;
// Fallback: find any existing player in this server
if (serverId) {
for (const [channelId] of this.playerMap) {
const channel = this.commands.client?.channels?.get(channelId) ??
this.commands.client?.channels?.cache?.get(channelId);
if (channel?.guildId === serverId || channel?.server_id === serverId || channel?.serverId === serverId) {
return channelId;
}
}
}
return null;
}
// ═══════════════════════════════════════════════════════════════════════════
// Player Retrieval
// ═══════════════════════════════════════════════════════════════════════════
/**
* Get or create a player for the user's voice channel.
* @param {Message} message
* @param {boolean} [promptJoin=true]
* @param {boolean} [verifyUser=true]
* @param {boolean} [shouldJoin=false]
* @returns {Promise<Player|null>}
*/
async getPlayer(message, promptJoin = true, verifyUser = true, shouldJoin = false) {
const serverId = message.channel?.server_id ??
message.channel?.serverId ??
message.message?.server_id ??
message.message?.serverId;
const userChannelId = this.checkVoiceChannels(message);
if (userChannelId) {
const player = this.playerMap.get(userChannelId);
if (player) {
player.textChannel = message.channel;
return player;
}
}
const serverPlayers = serverId
? [...this.playerMap.entries()].filter(([chId]) => {
const ch = this.commands.client?.channels?.get(chId) ??
this.commands.client?.channels?.cache?.get(chId);
return ch?.guildId === serverId || ch?.server_id === serverId || ch?.serverId === serverId;
})
: [];
if (serverPlayers.length > 0) {
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
if (!userChannelId) {
message.replyEmbed(mkEmbed(`⚠️ Please join ${channelList} to use this command.`));
return null;
}
const match = serverPlayers.find(([chId]) => chId === userChannelId);
if (match) {
match[1].textChannel = message.channel;
return match[1];
}
message.replyEmbed(mkEmbed(`⚠️ I'm already playing in ${channelList}. Join that channel.`));
return null;
}
if (!userChannelId) {
message.replyEmbed(mkEmbed("⚠️ Please join a voice channel first."));
return null;
}
if (shouldJoin) {
return new Promise((resolve) => {
this.initPlayer(message, userChannelId, (p) => resolve(p));
});
}
return null;
}
// ═══════════════════════════════════════════════════════════════════════════
// Channel Selection Prompt
// ═══════════════════════════════════════════════════════════════════════════
/**
* Prompt the user to select a voice channel.
* @param {Message} msg
* @returns {Promise<string|false>}
*/
async promptVC(msg) {
const autoDetected = this.checkVoiceChannels(msg);
if (autoDetected) {
return new Promise(resolve => this.initPlayer(msg, autoDetected, () => resolve(autoDetected)));
}
const serverId = msg.channel?.server_id ?? msg.channel?.serverId;
const allChannels = serverId
? [...(this.commands.client?.channels?.values?.() ??
this.commands.client?.channels?.cache?.values?.() ?? [])]
.filter(c => {
const cServerId = c.server_id ?? c.serverId;
return cServerId === serverId && c.channel_type === "VoiceChannel";
})
: [];
const reactions = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣"];
const channelArr = allChannels.slice(0, 9);
let channelSelection = "";
if (channelArr.length > 0) {
channelSelection = "Please select one of the following channels by clicking on the reactions below\n\n";
channelArr.forEach((c, i) => { channelSelection += `${i + 1}. <#${c._id ?? c.id}>\n`; });
}
const selectionMsg = await msg.replyEmbed(mkEmbed(
(channelSelection ? channelSelection + "\n**..or**" : "Please") +
" send a message with the voice channel! (Mention/Id/Name)\nSend 'x' to cancel."
));
return new Promise(resolve => {
let unsubscribeReactions;
let unsubscribeMessages;
const cleanup = () => {
unsubscribeMessages?.();
unsubscribeReactions?.();
};
const timeout = setTimeout(() => {
cleanup();
msg.replyEmbed(mkEmbed("⏱️ Voice selection timed out."));
resolve(false);
}, 30_000);
if (typeof selectionMsg?.onReaction === "function" && channelArr.length > 0) {
unsubscribeReactions = selectionMsg.onReaction(
reactions.slice(0, channelArr.length),
(e) => {
const idx = reactions.indexOf(e.emoji_id ?? e.emoji?.id ?? e.emoji);
const channel = channelArr[idx];
if (!channel) return;
clearTimeout(timeout);
cleanup();
const cid = channel._id ?? channel.id;
this.initPlayer(msg, cid, () => resolve(cid));
},
msg.author
);
}
unsubscribeMessages = msg.channel.onMessageUser((m) => {
const content = m.content?.toLowerCase() ?? "";
if (content === "x") {
clearTimeout(timeout);
cleanup();
m.replyEmbed(mkEmbed("Cancelled!"));
resolve(false);
return;
}
if (!this.commands.validateInput("voiceChannel", m.content, m)) {
m.replyEmbed(mkEmbed("Invalid voice channel. Try again or type `x`."));
return;
}
const channel = this.commands.formatInput("voiceChannel", m.content, m);
clearTimeout(timeout);
cleanup();
this.initPlayer(m, channel, () => resolve(channel));
}, msg.author);
});
}
// ═══════════════════════════════════════════════════════════════════════════
// Leave
// ═══════════════════════════════════════════════════════════════════════════
/**
* Make the player leave its current voice channel.
* @param {Message} msg
* @param {string} [cid]
*/
async leave(msg, cid) {
if (!cid) {
const serverId = msg.channel?.server_id ?? msg.channel?.serverId ??
msg.message?.server_id ?? msg.message?.serverId;
if (serverId) {
cid = [...this.playerMap.keys()].find((id) => {
const ch = this.commands.client?.channels?.get(id) ??
this.commands.client?.channels?.cache?.get(id);
return ch?.guildId === serverId || ch?.server_id === serverId || ch?.serverId === serverId;
});
}
}
const player = cid ? this.playerMap.get(cid) : null;
if (!player) return msg.replyEmbed(mkEmbed("I'm not in a voice channel."));
this.playerMap.delete(cid);
await msg.replyEmbed(mkEmbed("✅ Successfully Left"));
await player.leave();
player.destroy();
}
// ═══════════════════════════════════════════════════════════════════════════
// Player Initialisation
// ═══════════════════════════════════════════════════════════════════════════
/**
* Create and register a new Player for the given voice channel.
* @param {Message} message
* @param {string} cid - Voice channel ID
* @param {Function} [cb]
*/
initPlayer(message, cid, cb = () => {}) {
const channel = this.commands.client?.channels?.get(cid) ??
this.commands.client?.channels?.cache?.get(cid);
if (!channel) {
return message.replyEmbed(mkEmbed(
`Couldn't find the channel \`${cid}\`\nUse the help command to learn more about this.`
));
}
const isVoice = channel.channel_type === "VoiceChannel" ||
channel.type === "VoiceChannel" ||
channel.type === 2;
if (!isVoice) {
return message.replyEmbed(mkEmbed("❌ Please join a **voice channel** first before using this command!"));
}
if (this.playerMap.has(cid)) {
const existing = this.playerMap.get(cid);
existing.textChannel = message.channel;
cb(existing);
return message.replyEmbed(mkEmbed(`Already joined <#${cid}>.`));
}
const player = new Player(this.config.token, {
...this.playerConfig,
client: this.commands.client,
config: this.config,
nodelink: this.config.nodelink,
moonlink: this.playerConfig?.moonlink ?? null,
settingsMgr: this.settings,
observedVoiceUsers: this.observedVoiceUsers ?? null,
});
player.textChannel = message.channel;
player.on("autoleave", () => {
const ch = player.textChannel;
const serverId = ch?.server_id ?? ch?.serverId ?? ch?.guild?.id;
const is247 = (() => {
try {
const raw = this.settings.getServer(serverId)?.get("stay_247");
return raw && raw !== "none";
} catch (_) { return false; }
})();
const prefix = (() => {
try {
return this.settings.getServer(serverId)?.get("prefix") ?? "%";
} 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\``;
ch?.sendEmbed(mkEmbed(desc));
this.playerMap.delete(cid);
player.destroy();
});
player.on("leave", () => {});
player.on("message", (m) => {
const ch = player.textChannel;
const serverId = ch?.server_id ?? ch?.serverId ?? ch?.guild?.id;
const raw = this.settings.getServer(serverId)?.get("songAnnouncements");
const disabled = raw === false || raw === 0 ||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
if (disabled) return;
ch?.sendEmbed(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m));
});
this.playerMap.set(cid, player);
(async () => {
const statusMsg = await message.replyEmbed(mkEmbed("⏳ Joining Channel..."));
try {
await player.join(cid);
await statusMsg.editEmbed(mkEmbed(`✅ Successfully joined <#${cid}>`));
const serverId = message.channel?.server_id ?? message.channel?.serverId;
if (serverId) {
const savedVol = this.settings.getServer(serverId)?.get("volume");
if (savedVol !== undefined && savedVol !== null) {
const vol = Number(savedVol);
if (!isNaN(vol)) player.setVolume(vol / 100);
}
}
cb(player);
} catch (err) {
await statusMsg.editEmbed(mkEmbed(`❌ Failed to join: ${err.message}`)).catch(() => {});
this.playerMap.delete(cid);
player.destroy();
}
})();
}
}
+199
View File
@@ -0,0 +1,199 @@
import fs from "node:fs";
import { logger } from "./constants/Logger.mjs";
import mysql from "mysql";
import { EventEmitter } from "node:events";
export class ServerSettings {
id;
manager;
data = {};
constructor(id, mgr) {
this.id = id;
this.manager = mgr;
this.loadDefaults();
}
set(key, value) { this.data[key] = value; this.manager.update(this, key); }
get(key) { return this.data[key]; }
reset(key) { return this.set(key, this.manager.defaults[key]); }
getAll() { return this.data; }
loadDefaults() { for (let key in this.manager.defaults) { this.data[key] = this.manager.defaults[key]; } }
deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } }
// was `if (!this.data[key])` which clobbered valid falsy values like 0, false, ""
checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } }
get serializationData() { return { ...this.data, id: this.id }; }
serialize() { return this.serializationData; }
serializeObject() { return this.serializationData; }
}
/** @deprecated Use RemoteSettingsManager instead */
export class SettingsManager {
guilds = new Map();
storagePath = "./storage/settings.json";
defaults = {};
descriptions = {};
constructor(storagePath = null) {
if (storagePath) this.storagePath = storagePath;
this.load();
}
loadDefaultsSync(filePath) {
const d = fs.readFileSync(filePath, "utf8");
const parsed = JSON.parse(d);
this.descriptions = parsed.descriptions;
this.defaults = parsed.values;
}
load() {
if (!fs.existsSync(this.storagePath)) {
fs.writeFileSync(this.storagePath, JSON.stringify({ guilds: [] }));
}
const json = JSON.parse(fs.readFileSync(this.storagePath, "utf8"));
const entries = json.guilds || json.servers || [];
entries.forEach((s) => {
const server = new ServerSettings(s.id, this);
server.deserialize(s);
server.checkDefaults(this.defaults);
this.guilds.set(s.id, server);
});
}
save() {
const s = [];
this.guilds.forEach((val) => { s.push(val.serialize()); });
fs.writeFileSync(this.storagePath, JSON.stringify({ guilds: s }));
}
saveAsync() {
return new Promise((res) => {
const s = [];
this.guilds.forEach((val) => { s.push(val.serializeObject()); });
fs.writeFile(this.storagePath, JSON.stringify({ guilds: s }), () => { res(); });
});
}
update(server, key) {
if (!this.guilds.has(server.id)) this.guilds.set(server.id, server);
const s = this.guilds.get(server.id);
s.data[key] = server.data[key];
}
isOption(key) { return key in this.defaults; }
hasServer(id) { return this.guilds.has(id); }
getServer(id) {
if (this.guilds.has(id)) return this.guilds.get(id);
// Create AND store so any .set() calls on the returned object are persisted.
// Previously this returned a detached instance, causing settings writes to silently disappear.
const server = new ServerSettings(id, this);
server.checkDefaults(this.defaults);
this.guilds.set(id, server);
return server;
}
}
export class RemoteSettingsManager extends EventEmitter {
guilds = new Map();
descriptions = {};
defaults = {};
db = null;
// track retry count and apply exponential backoff on load failures
_loadAttempts = 0;
constructor(config, defaultsPath) {
super();
this.db = mysql.createPool({ connectionLimit: 15, ...config });
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
this.load();
}
query(q) {
return new Promise(res => {
this.db.query(q, (error, results, fields) => { res({ error, results, fields }); });
});
}
async load() {
const res = await this.query("SELECT * FROM settings");
if (res.error) {
this._loadAttempts++;
// exponential backoff with a cap of 30s instead of forever-at-2s
const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000);
logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error);
return setTimeout(() => { this.load(); }, delay);
}
this._loadAttempts = 0;
res.results.forEach((r) => {
const server = new ServerSettings(r.id, this);
server.deserialize(JSON.parse(r.data));
server.checkDefaults(this.defaults);
this.guilds.set(server.id, server);
});
this.emit("ready");
}
async remoteUpdate(server, key) {
const val = server.data[key];
// Arrays/objects must go through remoteSave — JSON_SET with scalar
// interpolation corrupts arrays by merging IDs into one number on read-back.
if (Array.isArray(val) || (typeof val === "object" && val !== null)) {
return this.remoteSave(server);
}
// Use mysql.escape() for every user-supplied value to prevent SQL injection.
const escapedPath = mysql.escape(`$.${key}`);
const escapedVal = mysql.escape(String(val));
const escapedId = mysql.escape(server.id);
const r = await this.query(`UPDATE settings SET data = JSON_SET(data, ${escapedPath}, ${escapedVal}) WHERE id=${escapedId}`);
if (r.error) logger.error("[Settings] remoteUpdate error:", r.error);
}
async remoteSave(server) {
const escapedData = mysql.escape(JSON.stringify(server.data));
const escapedId = mysql.escape(server.id);
const r = await this.query(`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}`);
if (r.error) logger.error("[Settings] remoteSave error:", r.error);
}
loadDefaultsSync(filePath) {
const d = fs.readFileSync(filePath, "utf8");
const parsed = JSON.parse(d);
this.descriptions = parsed.descriptions;
this.defaults = parsed.values;
}
async saveAsync() {
await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v)));
}
async create(id, server) {
const escapedId = mysql.escape(id);
const escapedData = mysql.escape(JSON.stringify(server.data));
const r = await this.query(`INSERT INTO settings (id, data) VALUES (${escapedId}, ${escapedData})`);
if (r.error) logger.error("[Settings] create error:", r.error);
}
update(server, key) {
if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); }
const s = this.guilds.get(server.id);
s.data[key] = server.data[key];
this.remoteUpdate(server, key);
}
isOption(key) { return key in this.defaults; }
hasServer(id) { return this.guilds.has(id); }
getServer(id) {
if (!this.guilds.has(id)) {
// Return a fresh object but don't register it yet;
// update() will call create() on the first real write.
return new ServerSettings(id, this);
}
return this.guilds.get(id);
}
/**
* Drop a server from the in-memory cache without touching the DB row.
* This lets settings be restored automatically if the bot is re-invited.
* @param {string} id - Guild / server ID
*/
removeServer(id) {
this.guilds.delete(id);
}
}
+511
View File
@@ -0,0 +1,511 @@
/**
* Utils.mjs — Utility functions for the music bot
* @module Utils
*/
/**
* @class Utils
* @description Static utility methods for time formatting, array manipulation,
* string processing, and validation used across the music bot.
*/
export class Utils {
// ═════════════════════════════════════════════════════════════════════════════
// Time & Duration
// ═════════════════════════════════════════════════════════════════════════════
/**
* Format milliseconds to human-readable time string (H:MM:SS or M:SS)
* @param {number} milliseconds - Duration in milliseconds
* @returns {string} Formatted time string
* @example Utils.prettifyMS(125000) // "2:05"
* @example Utils.prettifyMS(3661000) // "1:01:01"
*/
static prettifyMS(milliseconds) {
if (!milliseconds || milliseconds < 0 || !isFinite(milliseconds)) {
return "0:00";
}
const totalSeconds = Math.floor(milliseconds / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const pad = (n) => String(n).padStart(2, "0");
return hours > 0
? `${hours}:${pad(minutes)}:${pad(seconds)}`
: `${minutes}:${pad(seconds)}`;
}
/**
* Parse duration string (H:MM:SS or M:SS) to milliseconds
* @param {string} str - Duration string
* @returns {number} Milliseconds, 0 if invalid
*/
static parseDuration(str) {
if (!str || typeof str !== "string") return 0;
const parts = str.split(":").map((s) => parseInt(s.trim(), 10)).reverse();
if (parts.some(isNaN) || parts.some(n => n < 0)) return 0;
let ms = 0;
if (parts[0] !== undefined) ms += parts[0] * 1000; // seconds
if (parts[1] !== undefined) ms += parts[1] * 60 * 1000; // minutes
if (parts[2] !== undefined) ms += parts[2] * 3600 * 1000; // hours
return ms;
}
/**
* Format seconds to MM:SS (for NodeLink duration compatibility)
* @param {number} seconds - Duration in seconds
* @returns {string} Formatted time
*/
static formatSeconds(seconds) {
if (!seconds || seconds < 0 || !isFinite(seconds)) return "0:00";
return this.prettifyMS(seconds * 1000);
}
// ═════════════════════════════════════════════════════════════════════════════
// Array Manipulation
// ═════════════════════════════════════════════════════════════════════════════
/**
* Shuffles array in-place using Fisher-Yates algorithm
* @template T
* @param {T[]} array - Array to shuffle
* @returns {T[]} Same array reference (shuffled)
*/
static shuffleArr(array) {
if (!Array.isArray(array) || array.length < 2) return array;
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
/**
* Get random element from array
* @template T
* @param {T[]} array - Source array
* @returns {T | undefined} Random element or undefined if empty
*/
static randomElement(array) {
if (!Array.isArray(array) || array.length === 0) return undefined;
return array[Math.floor(Math.random() * array.length)];
}
/**
* Chunk array into smaller arrays
* @template T
* @param {T[]} array - Array to chunk
* @param {number} size - Chunk size (minimum 1)
* @returns {T[][]} Array of chunks
*/
static chunk(array, size) {
if (!Array.isArray(array) || size < 1) return [];
const chunks = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
/**
* Remove duplicates from array (primitive values only)
* @template T
* @param {T[]} array - Array with potential duplicates
* @returns {T[]} New array without duplicates
*/
static unique(array) {
if (!Array.isArray(array)) return [];
return [...new Set(array)];
}
// ═════════════════════════════════════════════════════════════════════════════
// String Formatting
// ═════════════════════════════════════════════════════════════════════════════
/**
* Truncate text with ellipsis
* @param {string} str - String to truncate
* @param {number} [maxLen=100] - Maximum length
* @param {string} [suffix="..."] - Suffix to add
* @returns {string} Truncated string
*/
static truncate(str, maxLen = 100, suffix = "...") {
if (!str || typeof str !== "string") return "";
if (str.length <= maxLen) return str;
if (maxLen <= suffix.length) return str.substring(0, maxLen);
return str.substring(0, maxLen - suffix.length) + suffix;
}
/**
* Clean song title by removing common suffixes/prefixes for better matching
* Used for lyrics search and display normalization
* @param {string} title - Raw title
* @returns {string} Cleaned title
*/
static cleanTitle(title) {
if (!title || typeof title !== "string") return "Unknown";
return title
.replace(/\s*[\(\[][^\)\]]*(?:feat|ft|featuring|remix|edit|version|prod|official|audio|video|lyrics|visualizer)[^\)\]]*[\)\]]/gi, "")
.replace(/\s*-\s*(?:feat|ft|featuring)\.?.*/gi, "")
.replace(/\s*\|.*$/g, "") // Remove pipe and everything after
.replace(/\s*【.*?】/g, "") // Remove Japanese brackets
.replace(/\s*\[.*?\]/g, "") // Remove square brackets
.replace(/\s*\(.*?\)/g, "") // Remove parentheses
.replace(/\s{2,}/g, " ") // Collapse multiple spaces
.trim();
}
/**
* Sanitize string for safe filename
* @param {string} str - Input string
* @param {number} [maxLen=50] - Maximum length
* @returns {string} Safe filename
*/
static sanitizeFilename(str, maxLen = 50) {
if (!str || typeof str !== "string") return "unknown";
return str
.replace(/[^a-z0-9\u4e00-\u9fa5]/gi, "_") // Keep CJK chars too
.replace(/_{2,}/g, "_")
.substring(0, maxLen)
.replace(/^_+|_+$/g, "");
}
/**
* Escape markdown characters for Discord
* @param {string} text - Raw text
* @returns {string} Escaped text
*/
static escapeMarkdown(text) {
if (!text || typeof text !== "string") return "";
return text
.replace(/\\/g, "\\\\")
.replace(/`/g, "\\`")
.replace(/\*/g, "\\*")
.replace(/_/g, "\\_")
.replace(/~/g, "\\~")
.replace(/\|/g, "\\|");
}
/**
* Format number with commas (e.g., 1,000,000)
* @param {number} num - Number to format
* @returns {string} Formatted number
*/
static formatNumber(num) {
if (num === null || num === undefined || isNaN(num)) return "0";
return num.toLocaleString();
}
/**
* Format bytes to human readable (KB, MB, GB)
* @param {number} bytes - Bytes to format
* @param {number} [decimals=2] - Decimal places
* @returns {string} Human readable size
*/
static formatBytes(bytes, decimals = 2) {
if (!bytes || bytes === 0) return "0 Bytes";
if (bytes < 0) return "Unknown";
const k = 1024;
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
const i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length - 1);
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
}
// ═════════════════════════════════════════════════════════════════════════════
// ID Generation
// ═════════════════════════════════════════════════════════════════════════════
/**
* Generate random unique ID
* @param {number} [length=16] - Desired length of ID (8-32 recommended)
* @returns {string} Random ID
*/
static uid(length = 16) {
const targetLen = Math.max(8, Math.min(length, 32));
const timestamp = Date.now().toString(36).toUpperCase();
let random = "";
// Generate enough random data
while ((timestamp + random).length < targetLen) {
random += Math.random().toString(36).substring(2).toUpperCase();
}
return (timestamp + random).substring(0, targetLen);
}
/**
* Generate UUID v4 (RFC4122 compliant)
* @returns {string} UUID string
*/
static uuid() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
// ═════════════════════════════════════════════════════════════════════════════
// Validation & Safety (CRITICAL for worker.mjs compatibility)
// ═════════════════════════════════════════════════════════════════════════════
/**
* Check if a string represents a finite number
* @param {string} str
* @returns {boolean}
*/
static isNumber(str) {
if (str === null || str === undefined || str === "") return false;
return !isNaN(str) && isFinite(str);
}
/**
* Check if value is a valid URL
* Used by worker.mjs YTUtils.isValidUrl
* @param {string} str - String to check
* @returns {boolean} True if valid URL
*/
static isValidUrl(str) {
if (!str || typeof str !== "string") return false;
try {
new URL(str);
return true;
} catch {
return false;
}
}
/**
* Clamp number between min and max
* @param {number} num - Number to clamp
* @param {number} min - Minimum value
* @param {number} max - Maximum value
* @returns {number} Clamped value
*/
static clamp(num, min, max) {
if (isNaN(num)) return min;
return Math.max(min, Math.min(max, num));
}
/**
* Safe JSON parse with fallback
* @template T
* @param {string} str - JSON string
* @param {T} [fallback=null] - Fallback value on error
* @returns {T | null} Parsed object or fallback
*/
static safeJsonParse(str, fallback = null) {
if (!str || typeof str !== "string") return fallback;
try {
return JSON.parse(str);
} catch {
return fallback;
}
}
// ═════════════════════════════════════════════════════════════════════════════
// Async Utilities
// ═════════════════════════════════════════════════════════════════════════════
/**
* Sleep/delay promise
* @param {number} ms - Milliseconds to sleep
* @returns {Promise<void>}
*/
static sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
}
/**
* Retry an async operation with exponential backoff
* @template T
* @param {() => Promise<T>} fn - Function to retry
* @param {number} [attempts=3] - Max retry attempts
* @param {number} [delay=1000] - Initial delay in ms
* @param {number} [backoff=2] - Backoff multiplier
* @returns {Promise<T>}
*/
static async retry(fn, attempts = 3, delay = 1000, backoff = 2) {
if (typeof fn !== "function") {
throw new TypeError("First argument must be a function");
}
let lastError;
for (let i = 0; i < attempts; i++) {
try {
return await fn();
} catch (err) {
lastError = err;
if (i < attempts - 1) {
await this.sleep(delay * Math.pow(backoff, i));
}
}
}
throw lastError;
}
/**
* Timeout wrapper for promises
* @template T
* @param {Promise<T>} promise - Promise to wrap
* @param {number} ms - Timeout in milliseconds
* @param {string} [message="Operation timed out"] - Error message
* @returns {Promise<T>}
*/
static timeout(promise, ms, message = "Operation timed out") {
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error(message)), ms);
});
return Promise.race([promise, timeoutPromise]);
}
// ═════════════════════════════════════════════════════════════════════════════
// Object Utilities
// ═════════════════════════════════════════════════════════════════════════════
/**
* Deep clone an object (JSON method - not suitable for circular refs)
* @template T
* @param {T} obj - Object to clone
* @returns {T} Cloned object
*/
static deepClone(obj) {
if (obj === null || typeof obj !== "object") return obj;
try {
return JSON.parse(JSON.stringify(obj));
} catch {
return obj;
}
}
/**
* Pick specific keys from object
* @template T, K
* @param {T} obj - Source object
* @param {K[]} keys - Keys to pick
* @returns {Pick<T, K>} New object with picked keys
*/
static pick(obj, keys) {
if (!obj || typeof obj !== "object") return {};
const result = {};
for (const key of keys) {
if (key in obj) result[key] = obj[key];
}
return result;
}
/**
* Omit specific keys from object
* @template T, K
* @param {T} obj - Source object
* @param {K[]} keys - Keys to omit
* @returns {Omit<T, K>} New object without omitted keys
*/
static omit(obj, keys) {
if (!obj || typeof obj !== "object") return {};
const result = { ...obj };
for (const key of keys) {
delete result[key];
}
return result;
}
// ═════════════════════════════════════════════════════════════════════════════
// Music-Specific Helpers
// ═════════════════════════════════════════════════════════════════════════════
/**
* Create progress bar string
* @param {number} current - Current position in ms or 0-1 ratio
* @param {number} [total] - Total duration in ms (if omitted, current is treated as 0-1 ratio)
* @param {number} [length=15] - Bar length in characters
* @param {string} [filledChar="▬"] - Filled character
* @param {string} [emptyChar="▬"] - Empty character
* @param {string} [indicator="🔘"] - Position indicator
* @returns {string} Progress bar string
*/
static progressBar(
current,
total,
length = 15,
filledChar = "▬",
emptyChar = "▬",
indicator = "🔘"
) {
let progress;
if (total !== undefined && total > 0) {
progress = this.clamp(current / total, 0, 1);
} else {
progress = this.clamp(current, 0, 1);
}
const position = Math.floor(progress * length);
let bar = "";
for (let i = 0; i < length; i++) {
if (i === position) {
bar += indicator;
} else if (i < position) {
bar += filledChar;
} else {
bar += emptyChar;
}
}
return bar;
}
/**
* Format track info for display
* @param {object} track - Track object
* @param {boolean} [includeDuration=true] - Include duration
* @returns {string} Formatted string
*/
static formatTrackInfo(track, includeDuration = true) {
if (!track) return "Unknown Track";
const title = this.cleanTitle(track.title || "Unknown");
const author = track.author?.name || track.author || "Unknown Artist";
if (includeDuration && track.duration) {
const duration = typeof track.duration === "number"
? this.prettifyMS(track.duration)
: track.duration.timestamp || track.duration.seconds
? this.formatSeconds(track.duration.seconds)
: "?:??";
return `${title} - ${author} [${duration}]`;
}
return `${title} - ${author}`;
}
/**
* Parse YouTube-like ISO duration (PT4M13S) to milliseconds
* @param {string} isoDuration - ISO 8601 duration
* @returns {number} Milliseconds
*/
static parseISODuration(isoDuration) {
if (!isoDuration || typeof isoDuration !== "string") return 0;
const match = isoDuration.match(
/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?/
);
if (!match) return 0;
const hours = parseInt(match[1] || 0, 10);
const minutes = parseInt(match[2] || 0, 10);
const seconds = parseFloat(match[3] || 0);
return (hours * 3600 + minutes * 60 + seconds) * 1000;
}
}
+65
View File
@@ -0,0 +1,65 @@
/**
* Logger — configurable console output for Fluxer.
*
* Categories (all under config.logging):
* enabled — master switch; false silences everything except errors
* player — voice connect/disconnect, stream start, volume restore
* inactivity — alone-check, inactivity timer, human detection
* voice247 — 24/7 rejoin, auto-save channel, intentional leave skip
* voiceState — raw VOICE_STATE_UPDATE events (human join/leave detection)
* mediaplayer — MediaPlayer publish, LiveKit room state, connection recovery
* commands — command load, module load, error IDs
* guild — GuildCreate / GuildDelete lifecycle
* recovery — session save/restore on reboot
* settings — settings DB load, remote update errors
* worker — worker URL cleaning, result logging
* moonlink — moonlink node events
* errors — always on; console.error calls (cannot be disabled)
*/
let _config = null;
/**
* Call once at startup with the loaded config object.
* @param {object} config
*/
export function initLogger(config) {
_config = config?.logging ?? {};
}
function isEnabled(category) {
if (!_config) return true; // default on if not yet initialised
if (_config.enabled === false) return false;
// If the category key is missing, default to true
return _config[category] !== false;
}
function ts() {
return new Date().toISOString().replace("T", " ").slice(0, 19);
}
export const logger = {
// ── always-on (errors / warnings critical to operation) ──────────────────
error(tag, ...args) {
console.error(`[${ts()}] ${tag}`, ...args);
},
warn(tag, ...args) {
// warnings are on unless master switch is off
if (_config?.enabled === false) return;
console.warn(`[${ts()}] ${tag}`, ...args);
},
// ── categorised logs ─────────────────────────────────────────────────────
player(...args) { if (isEnabled("player")) console.log(`[${ts()}]`, ...args); },
inactivity(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); },
voice247(...args) { if (isEnabled("voice247")) console.log(`[${ts()}]`, ...args); },
voiceState(...args) { if (isEnabled("voiceState")) console.log(`[${ts()}]`, ...args); },
mediaplayer(...args) { if (isEnabled("mediaplayer")) console.log(`[${ts()}]`, ...args); },
commands(...args) { if (isEnabled("commands")) console.log(`[${ts()}]`, ...args); },
guild(...args) { if (isEnabled("guild")) console.log(`[${ts()}]`, ...args); },
recovery(...args) { if (isEnabled("recovery")) console.log(`[${ts()}]`, ...args); },
settings(...args) { if (isEnabled("settings")) console.log(`[${ts()}]`, ...args); },
worker(...args) { if (isEnabled("worker")) console.log(`[${ts()}]`, ...args); },
moonlink(...args) { if (isEnabled("moonlink")) console.log(`[${ts()}]`, ...args); },
aloneCheck(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); },
};
+77
View File
@@ -0,0 +1,77 @@
import { logger } from "../Logger.mjs";
import ffmpeg from "ffmpeg-static";
import { Transform } from "node:stream";
import { spawn } from "node:child_process";
class StreamMerger extends Transform {
ffmpegPath = ffmpeg;
ffmpeg = null;
streamTree = [];
constructor(streamOptions) {
super(streamOptions);
}
_transform(chunk, _enc, cb) {
if (!this.ffmpeg) { this.push(chunk); return cb(); }
this.ffmpeg.stdio[3].write(chunk);
cb();
}
pipe(stream) {
return super.pipe(stream);
}
setupBaseFfmpeg() {
this.ffmpeg = this.spawnFfmpeg();
this.ffmpeg.stderr.on("data", (chunk) => { logger.mediaplayer("[ffmpeg]", chunk.toString().trim()); });
this.ffmpeg.stdout.on("data", (chunk) => { this.push(chunk); });
}
spawnFfmpeg() {
const args = "-i pipe:3 -re -i pipe:4 -vn -fflags nobuffer -filter_complex amix=inputs=2:duration=longest pipe:1".split(" ");
return spawn(this.ffmpegPath, args, {
windowsHide: true,
stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"]
});
}
findOpenNode() {
if (this.streamTree.length === 0) {
this.streamTree.push({ process: this.ffmpeg, pipes: [4], available: true, children: [] });
return this.streamTree[0];
}
const findChild = (node) => {
if (node.available) return node;
for (const child of node.children) {
const c = findChild(child);
if (c) return c;
}
return null;
};
for (const node of this.streamTree) {
const firstChild = findChild(node);
if (firstChild) return firstChild;
}
return null;
}
addStream(s) {
if (!this.ffmpeg) this.setupBaseFfmpeg();
const open = this.findOpenNode();
if (!open) throw "Impossible case detected. No free merge node found.";
const p = this.spawnFfmpeg();
const node = { process: p, pipes: [4], available: true, parent: open, children: [] };
open.children.push(node);
s.pipe(p.stdio[3]);
p.stderr.on("data", (c) => { logger.mediaplayer("[ffmpeg]", c.toString().trim()); });
p.stdio[4].write(Buffer.alloc(1024, 0));
p.stdout.pipe(open.process.stdio[open.pipes[0]]);
const pipeNumber = open.pipes[0].valueOf();
open.pipes.splice(0, 1);
if (open.pipes.length === 0) open.available = false;
p.on("exit", () => {
open.pipes.push(pipeNumber);
open.available = true;
const idx = open.children.findIndex(c => c === node);
if (idx === -1) throw "Impossible case detected. Damaged node structure.";
open.children.splice(idx, 1);
});
}
}
export default StreamMerger;
+57
View File
@@ -0,0 +1,57 @@
import { https } from "follow-redirects";
class Tuna {
apiKey = null;
constructor(auth) {
this.apiKey = auth.key;
}
get(path, params = {}) {
return new Promise((resolve, rej) => {
var query = "";
for (let key in params) {
query += ((query.length === 0) ? "?" : "&") + key + "=" + encodeURIComponent(params[key]);
}
var options = {
method: "GET",
hostname: "tuna-api.voicemod.net",
path: path + query,
headers: { "x-api-key": this.apiKey },
maxRedirects: 20
};
var req = https.request(options, function(res) {
var chunks = [];
res.on("data", (chunk) => { chunks.push(chunk); });
res.on("end", () => { resolve(JSON.parse(Buffer.concat(chunks).toString())); });
res.on("error", (error) => { rej(error); });
});
req.end();
});
}
search(query, page = 1, size = 10) {
return new Promise(async res => {
const results = await this.get("/v1/sounds/search", { size, page, search: query });
results.items = results.items.map(s => {
s.download = function() {
return new Promise(resolve => {
https.get(this.oggPath, (r) => { resolve(r); });
});
};
return s;
});
res(results);
});
}
getSound(id) {
return new Promise(async res => {
const sound = await this.get("/v1/sounds/" + id);
sound.download = function() {
return new Promise(res => {
https.get(this.oggPath, (result) => { res(result); });
});
};
res(sound);
});
}
}
export default Tuna;
+103
View File
@@ -0,0 +1,103 @@
/**
* providers.mjs — Single source of truth for all provider data.
*
* PROVIDERS — full map: { prefix, label } — used by worker.mjs for search
* PROVIDER_NAMES — derived label-only map — used by Player.mjs for display
* PROVIDER_CHOICES — ordered list of valid keys — used by command option builders
*
* Edit only here; worker.mjs and Player.mjs import from this file.
*/
export const PROVIDERS = {
// ── Standard search ──────────────────────────────────────────────────────
yt: { prefix: "ytsearch", label: "YouTube" },
ytm: { prefix: "ytmsearch", label: "YouTube Music" },
scld: { prefix: "scsearch", label: "SoundCloud" },
sc: { prefix: "scsearch", label: "SoundCloud" },
sp: { prefix: "spsearch", label: "Spotify" },
spotify: { prefix: "spsearch", label: "Spotify" },
am: { prefix: "amsearch", label: "Apple Music" },
apple: { prefix: "amsearch", label: "Apple Music" },
dz: { prefix: "dzsearch", label: "Deezer" },
deezer: { prefix: "dzsearch", label: "Deezer" },
td: { prefix: "tdsearch", label: "Tidal" },
tidal: { prefix: "tdsearch", label: "Tidal" },
bc: { prefix: "bcsearch", label: "Bandcamp" },
bandcamp: { prefix: "bcsearch", label: "Bandcamp" },
adm: { prefix: "admsearch", label: "Audiomack" },
audiomack: { prefix: "admsearch", label: "Audiomack" },
gaana: { prefix: "gaanasearch", label: "Gaana" },
js: { prefix: "jssearch", label: "JioSaavn" },
jiosaavn: { prefix: "jssearch", label: "JioSaavn" },
lf: { prefix: "lfsearch", label: "Last.fm" },
lastfm: { prefix: "lfsearch", label: "Last.fm" },
pd: { prefix: "pdsearch", label: "Pandora" },
pandora: { prefix: "pdsearch", label: "Pandora" },
vk: { prefix: "vksearch", label: "VK Music" },
mc: { prefix: "mcsearch", label: "Mixcloud" },
mixcloud: { prefix: "mcsearch", label: "Mixcloud" },
nc: { prefix: "ncsearch", label: "NicoVideo" },
nicovideo: { prefix: "ncsearch", label: "NicoVideo" },
bb: { prefix: "bilibili", label: "Bilibili" },
bilibili: { prefix: "bilibili", label: "Bilibili" },
sh: { prefix: "shsearch", label: "Shazam" },
shazam: { prefix: "shsearch", label: "Shazam" },
sl: { prefix: "slsearch", label: "Songlink" },
songlink: { prefix: "slsearch", label: "Songlink" },
qb: { prefix: "qbsearch", label: "Qobuz" },
qobuz: { prefix: "qbsearch", label: "Qobuz" },
ym: { prefix: "ymsearch", label: "Yandex Music" },
yandex: { prefix: "ymsearch", label: "Yandex Music" },
au: { prefix: "ausearch", label: "Audius" },
audius: { prefix: "ausearch", label: "Audius" },
az: { prefix: "azsearch", label: "Amazon Music" },
amazon: { prefix: "azsearch", label: "Amazon Music" },
ag: { prefix: "agsearch", label: "Anghami" },
anghami: { prefix: "agsearch", label: "Anghami" },
bk: { prefix: "bksearch", label: "Bluesky" },
bluesky: { prefix: "bksearch", label: "Bluesky" },
// ── Recommendations ──────────────────────────────────────────────────────
ytrec: { prefix: "ytrec", label: "YouTube (recommended)" },
sprec: { prefix: "sprec", label: "Spotify (recommended)" },
dzrec: { prefix: "dzrec", label: "Deezer (recommended)" },
tdrec: { prefix: "tdrec", label: "Tidal (recommended)" },
jsrec: { prefix: "jsrec", label: "JioSaavn (recommended)" },
vkrec: { prefix: "vkrec", label: "VK Music (recommended)" },
// ── TTS ──────────────────────────────────────────────────────────────────
gtts: { prefix: "gtts", label: "Google TTS" },
tts: { prefix: "gtts", label: "Google TTS" },
ftts: { prefix: "ftts", label: "Flowery TTS" },
};
/** Label-only map — convenience alias for display use (e.g. Player.mjs). */
export const PROVIDER_NAMES = Object.fromEntries(
Object.entries(PROVIDERS).map(([k, v]) => [k, v.label])
);
export const PROVIDER_CHOICES = [
"ytm", "yt", "scld", "sc",
"sp", "spotify",
"am", "apple",
"dz", "deezer",
"td", "tidal",
"bc", "bandcamp",
"adm", "audiomack",
"gaana",
"js", "jiosaavn",
"lf", "lastfm",
"pd", "pandora",
"vk",
"mc", "mixcloud",
"nc", "nicovideo",
"bb", "bilibili",
"sh", "shazam",
"sl", "songlink",
"qb", "qobuz",
"ym", "yandex",
"au", "audius",
"az", "amazon",
"ag", "anghami",
"bk", "bluesky",
"ytrec", "sprec", "dzrec", "tdrec", "jsrec", "vkrec",
"gtts", "tts", "ftts",
];
+43
View File
@@ -0,0 +1,43 @@
import ffprobe from "ffprobe-static";
import { spawn } from "node:child_process";
export default function probe(file) {
return new Promise((res, rej) => {
// Pass args as an array — splitting a string on " " breaks paths that contain spaces.
const args = [
"-hide_banner",
"-show_entries", "format_tags:format=duration",
"-print_format", "json",
"-i", file,
];
const proc = spawn(ffprobe.path, args);
const chunks = [];
const errChunks = [];
proc.stdout.on("data", (d) => { chunks.push(d); });
proc.stderr.on("data", (d) => { errChunks.push(d); });
proc.on("error", (err) => {
rej(new Error("[probe] Failed to spawn ffprobe: " + err.message));
});
proc.on("close", (code) => {
try {
const raw = Buffer.concat(chunks).toString();
if (!raw.trim()) {
const errMsg = Buffer.concat(errChunks).toString().trim();
return rej(new Error("[probe] ffprobe produced no output" + (errMsg ? ": " + errMsg : "")));
}
const data = JSON.parse(raw);
res({
album: data.format?.tags?.album,
artist: data.format?.tags?.artist,
title: data.format?.tags?.StreamTitle || data.format?.tags?.title || "Unknown",
duration: (data.format?.duration ?? 0) * 1000
});
} catch (e) {
rej(new Error("[probe] Failed to parse ffprobe output: " + e.message));
}
});
});
}
+362
View File
@@ -0,0 +1,362 @@
/**
* worker.mjs — NodeLink REST edition (moonlink.js session-aware)
*
* Track resolution runs in a Worker thread so it never blocks the main loop.
* The Manager's active session ID is forwarded via workerData so all REST
* requests carry the correct Session-Id header (populated by moonlink.js).
*
* No direct moonlink.js import here — Worker threads can't share the Manager
* instance, so we call NodeLink REST directly (same protocol moonlink uses).
*/
import { workerData, parentPort } from "worker_threads";
import { EventEmitter } from "events";
import http from "http";
import https from "https";
import { Utils } from "./Utils.mjs";
import { PROVIDERS } from "./constants/providers.mjs";
import { logger } from "./constants/Logger.mjs";
// ═══════════════════════════════════════════════════════════════════════════════
// NodeLink Configuration (forwarded from Player via workerData)
// ═══════════════════════════════════════════════════════════════════════════════
const nl = workerData?.data?.nodelink ?? {};
const NL_HOST = nl.host ?? "localhost";
const NL_PORT = nl.port ?? 3000;
const NL_PASSWORD = nl.password ?? "youshallnotpass";
const NL_SESSION_ID = nl.sessionId ?? null; // provided by moonlink.js Manager
const NL_GUILD_ID = workerData?.data?.guildId ?? null;
// ═══════════════════════════════════════════════════════════════════════════════
// HTTP Helper
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Make a GET request to NodeLink and return the parsed JSON body.
* @param {string} path - API path (e.g. "/v4/loadtracks?identifier=…")
* @returns {Promise<object>}
*/
function nlGet(path) {
return new Promise((resolve, reject) => {
const isHttps = NL_PORT === 443;
const mod = isHttps ? https : http;
const protocol = isHttps ? "https" : "http";
const req = mod.get(
`${protocol}://${NL_HOST}:${NL_PORT}${path}`,
{
headers: {
Authorization: NL_PASSWORD,
...(NL_SESSION_ID ? { "Session-Id": NL_SESSION_ID } : {}),
...(NL_GUILD_ID ? { "Guild-Id": NL_GUILD_ID } : {}),
}
},
(res) => {
const chunks = [];
res.on("data", d => chunks.push(d));
res.on("end", () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString()));
} catch (e) {
reject(new Error(`NodeLink JSON parse error: ${e.message}`));
}
});
}
);
req.on("error", reject);
req.setTimeout(30_000, () => {
req.destroy();
reject(new Error("NodeLink request timeout"));
});
});
}
/**
* Call NodeLink /v4/loadtracks.
* @param {string} identifier
* @returns {Promise<object>}
*/
async function loadTracks(identifier) {
return nlGet(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`);
}
// ═══════════════════════════════════════════════════════════════════════════════
// Track Conversion
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Convert a NodeLink track object to the internal video format.
* @param {object} track
* @returns {object|null}
*/
function trackToVideo(track) {
if (!track || typeof track !== "object") return null;
const info = track.info ?? {};
const ms = info.length ?? 0;
return {
videoId: info.identifier ?? "",
encoded: track.encoded ?? "",
sourceName: info.sourceName ?? "unknown",
title: Utils.cleanTitle(info.title ?? "Unknown"),
url: info.uri ?? `https://www.youtube.com/watch?v=${info.identifier}`,
thumbnail: info.artworkUrl ?? null,
spotifyUrl: null,
duration: {
timestamp: Utils.prettifyMS(ms),
seconds: Math.floor(ms / 1000),
},
author: {
name: info.author ?? "Unknown",
url: info.uri ?? null,
},
artists: null,
};
}
// ═══════════════════════════════════════════════════════════════════════════════
// Provider Configuration (imported from constants/providers.mjs)
// ═══════════════════════════════════════════════════════════════════════════════
const TYPE_MODIFIERS = ["track","playlist","album","artist","channel","user"];
// ═══════════════════════════════════════════════════════════════════════════════
// YTUtils Class
// ═══════════════════════════════════════════════════════════════════════════════
class YTUtils extends EventEmitter {
constructor() { super(); }
isValidUrl(str) { return Utils.isValidUrl(str); }
_prefix(p) { return PROVIDERS[p]?.prefix ?? "ytmsearch"; }
_providerLabel(p) { return PROVIDERS[p]?.label ?? "YouTube Music"; }
_buildIdentifier(provider, query) {
const prefix = this._prefix(provider);
const colonIdx = query.indexOf(":");
if (colonIdx !== -1) {
const maybeType = query.slice(0, colonIdx).toLowerCase();
if (TYPE_MODIFIERS.includes(maybeType)) return `${prefix}:${query}`;
}
return `${prefix}:track:${query}`;
}
/**
* Clean YouTube Radio/Mix URLs to extract just the video
* YouTube Radio URLs (list=RD...) often cause metadata mismatches
*/
_cleanYouTubeUrl(url) {
try {
const urlObj = new URL(url);
// Check if it's a YouTube Radio/Mix URL
const list = urlObj.searchParams.get("list");
if (list && list.startsWith("RD")) {
// Extract just the video ID and create clean URL
const videoId = urlObj.searchParams.get("v");
if (videoId) {
logger.worker(`[Worker] Cleaning YouTube Radio URL, extracted video: ${videoId}`);
return `https://www.youtube.com/watch?v=${videoId}`;
}
}
// Remove start_radio parameter if present
if (urlObj.searchParams.has("start_radio")) {
urlObj.searchParams.delete("start_radio");
return urlObj.toString();
}
return url;
} catch (e) {
return url;
}
}
async getResults(query, limit = 5, provider = "ytm") {
const id = this.isValidUrl(query) ? query : this._buildIdentifier(provider, query);
const data = await loadTracks(id);
let tracks = [];
if (data.loadType === "search") tracks = data.data ?? [];
else if (data.loadType === "track") tracks = [data.data];
else if (data.loadType === "playlist") tracks = data.data?.tracks ?? [];
const validTracks = tracks.filter(track => {
const info = track.info ?? {};
const uri = info.uri || "";
if (uri.includes("/channel/")) return false;
if (uri.includes("/c/") && !uri.includes("/watch")) return false;
if (uri.includes("/playlist?")) return false;
if (uri.includes("/user/")) return false;
if (!info.length || info.length === 0) return false;
return true;
});
const resultTracks = validTracks.length > 0 ? validTracks : tracks;
return { data: resultTracks.slice(0, limit).map(trackToVideo) };
}
async getVideoData(query, provider = "ytm") {
// Handle URLs (including YouTube Radio/Mix)
if (this.isValidUrl(query)) {
this.emit("message", "Loading...");
// Clean YouTube Radio URLs to prevent metadata mismatches
const cleanedUrl = this._cleanYouTubeUrl(query);
if (cleanedUrl !== query) {
logger.worker(`[Worker] URL cleaned: ${query} -> ${cleanedUrl}`);
}
let data;
try {
data = await loadTracks(cleanedUrl);
} catch (e) {
this.emit("message", `**Failed to load: ${e.message}**`);
return { type: "error", data: null, error: e.message };
}
// Handle playlist results
if (data.loadType === "playlist") {
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
tracks.forEach(t => { t.playlistName = data.data?.info?.name ?? null; });
this.emit("message", `Successfully added **${tracks.length}** songs to the queue.`);
return { type: "list", data: tracks };
}
// Handle single track
if (data.loadType === "track") {
const video = trackToVideo(data.data);
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video };
}
// Handle search results (take first)
if (data.loadType === "search" && data.data?.length) {
const video = trackToVideo(data.data[0]);
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video };
}
// No recognizable loadType
this.emit("message", `**Could not load that URL.** (loadType: ${data.loadType || "unknown"})`);
return { type: "error", data: null, error: "Unknown loadType: " + (data.loadType || "none") };
}
// Handle search queries (non-URLs)
this.emit("message", `Searching ${this._providerLabel(provider)}...`);
let data;
try {
data = await loadTracks(this._buildIdentifier(provider, query));
} catch (e) {
this.emit("message", `**Search failed: ${e.message}**`);
return { type: "error", data: null, error: e.message };
}
// Handle search results
if (data.loadType === "search" && data.data?.length) {
const validTrack = data.data.find(track => {
const info = track.info ?? {};
const uri = info.uri || "";
if (uri.includes("/channel/")) return false;
if (uri.includes("/c/") && !uri.includes("/watch")) return false;
if (!info.length || info.length === 0) return false;
return true;
});
const trackToUse = validTrack || data.data[0];
const video = trackToVideo(trackToUse);
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video };
}
// Handle playlist from search
if (data.loadType === "playlist") {
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
if (tracks.length > 0) {
this.emit("message", `Successfully added **${tracks.length}** songs to the queue.`);
return { type: "list", data: tracks };
}
}
// Single track from search
if (data.loadType === "track") {
const video = trackToVideo(data.data);
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video };
}
// Nothing found
this.emit("message", `**No results found for '${query}'.**`);
return { type: "error", data: null, error: "No results found" };
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// Worker Entry Point
// ═══════════════════════════════════════════════════════════════════════════════
const jobId = workerData?.jobId;
const data = workerData?.data;
if (!jobId) {
logger.error("No jobId provided to worker");
process.exit(1);
}
const utils = new YTUtils();
const post = (event, payload) => {
parentPort.postMessage(JSON.stringify({ event, data: payload }));
};
utils.on("message", (m) => {
if (jobId === "dev") { logger.worker("[Message]", m); return; }
post("message", m);
});
utils.on("error", (m) => {
if (jobId === "dev") { logger.worker("[Error]", m); return; }
post("error", m);
});
(async () => {
if (jobId === "dev") {
try {
const result = await utils.getVideoData("Neoni funeral", "ytm");
logger.worker("[Worker result]", result);
} catch (e) {
logger.error("[Worker error]", e);
}
return;
}
try {
switch (jobId) {
case "generalQuery": {
const result = await utils.getVideoData(data.query, data.provider);
post("finished", result);
break;
}
case "searchResults": {
const result = await utils.getResults(data.query, data.resultCount, data.provider);
post("finished", result);
break;
}
case "search": {
const result = await utils.getVideoData(String(data), "ytm");
post("finished", result?.data ?? null);
break;
}
default:
logger.error("Invalid jobId:", jobId);
post("error", `Unknown jobId: ${jobId}`);
}
} catch (err) {
post("error", err.message);
} finally {
process.exit(0);
}
})();
+20
View File
@@ -0,0 +1,20 @@
{
"values": {
"songAnnouncements": true,
"prefix": "%",
"pfp": "default",
"locale": "en",
"stay_247": "none",
"stay_247_mode": "off",
"volume": 100
},
"descriptions": {
"songAnnouncements": "Whether the bot should announce every song in a new message when it starts playing. Set to `true` or `1` to enable.",
"prefix": "The prefix used to trigger commands.",
"pfp": "What profile picture the bot should use. Presets: `default | dark | light | mono | <custom url>`.",
"locale": "The preferred language of your server.",
"stay_247": "24/7 mode channels. Managed automatically by %247 — do not edit manually.",
"stay_247_mode": "Controls 247 behaviour. Set via %247 off/on/auto. off = disabled, on = stay but no rejoin on force-kick, auto = stay and always rejoin.",
"volume": "The default playback volume for this server (1-200). Saved automatically when you use %volume. Restored every time the bot joins a channel."
}
}
+118
View File
@@ -0,0 +1,118 @@
{
"cmdBuilder" : {
"requirement" : {
"permission" : "ليس لديك الصلاحية لكي تأمر هذا الأمر!"
},
"subcommand" : {
"invalid" : "أمر فرعي لا يوجد. جرب أحد من الأمور الآتية: `$previousCmd <$cmdlist>`"
}
},
"cmdHandler" : {
"command" : {
"invalid" : "أمر مجهول {{command}}!",
"suggestion" : "هل كنت تقصد {{command}}؟ (أكتب {{acceptCommand}} لكي تأمر بهذا الأمر)"
},
"help" : {
"pageStructure" : "الأوامر المتوفرة (صفحة $currPage/$maxPage): $content أَصدر أمر `$prefix$helpCmd <أمر>` لكي تستعلم عن الأمر. لديك أيضاً القدرة أن تستعلم عن الأمور الفرعية. علي سبيل المثال: `$prefix$helpCmd settings get` نصيحة: استخدم الأسهم أسفل هذه الرسالة لتقليب الصفحات، أو اختر الصفحة المطلوبة باستخدام `$prefix$helpCmd <رقم الصفحة>`"
},
"invalidFlag" : "خيار غير صالح `$invalidFlag`. إنه لا يطابق أي خيارات لهذا الأمر. `$previousCmd $invalidFlag`",
"page" : {
"invalid" : "{{number}} ليس رقم لصفحة صحيح!"
},
"permissions" : {
"message" : "الرجاء الإعطاء لي إذن {{permission}} في قناة {{channel}} أو اتصل بمسؤول السيرفر. أنا ليس لدي القدرة أن أعمل من غير هذا الإذن."
}
},
"commands" : {
"clear" : "أزل جميع الأغاني من القائمة.",
"join" : "اجعل البوت يدخل لقناة صوتية محددة.",
"leave" : "اجعل البوت يغادر القناة الصوتية الحالية لك",
"list" : "درج الأغاني في القائمة الخاصة بقناة الصوت الحالية.",
"login" : "أكد تسجيل الدخول لحسابك علي الموقع",
"loop" : "بدل تكرار القائمة لديك أو الأغنية.",
"lyrics" : "جلب كلمات الأغنية الحالية. يرجي الملاحظة أن الكلمات قد تكون مختلفة عن الكلمات الفعلية لأن Genius لا يجد الأغنية الصحيحة دائما.",
"np" : "أطلب الاسم والرابط للأغنية الحالية.",
"pause" : "توقيف الصوت في القناة الصوتية",
"ping" : "بادئتي في هذا الخادم هي: {{prefix}}. استخدم {{helpCmd}} لكي تبدأ!",
"play" : "شغل فيديو يوتيوب من رابط أو بحث أو قائمة تشغيل علي يوتيوب من رابط. بعض الخدمات الأخري مدعومة أيضاً.",
"player" : "إنشاء رسالة تحكم بالإيموجي لقناتك الصوتية",
"playnext" : "مثل %play. النتيجة ستضاف في أعلي قائمة الإنتظار.",
"remove" : "مسح أغنية معينة من قائمة الانتظار.",
"resume" : "تكملة تشغيل الصوت في قناتك الصوتية",
"search" : "عرض نتائج البحث عن بحث ما",
"settings" : "تغيير أو جلب الإعدادات للسيرفر الحالي.",
"shuffle" : "يرتب قائمة الإنتظار عشوائياً.",
"skip" : "تخطي الأغنية الحالية.",
"stats" : "عرض إحصائيات عن البوت مثل مدة التشغيل.",
"support" : "سيرفر الدعم لRemix. لا تتردد في طلب المساعدة، التبليغ عن المشاكل أو التحادث :)",
"thumbnail" : "طلب فن الأغنية الحالية.",
"volume" : "تغيير مقدار الصوت."
},
"options" : {
"join" : {
"channel" : "حدد القناة الذي يدخل إليها البوت. هذا ضروري لدي قيود Revolt الحالية."
},
"login" : {
"id" : "المعرف الذي استلمته عند تسجيل الدخول عند لوحة القيادة."
},
"loop" : {
"type" : "يحدد ما يكرر (قائمة الإنتظار كاملاً أم الأغنية الحالية)."
},
"play" : {
"query" : "رابط أو بحث علي يوتيوب أو رابط قائمة تشغيل أو رابط لأغنية Spotify أو SoundCloud أو YouTube Music."
},
"playnext" : {
"query" : "رابط أو بحث علي يوتيوب أو رابط قائمة تشغيل أو رابط لأغنية Spotify أو SoundCloud أو YouTube Music."
},
"remove" : {
"index" : "موضع الأغنية في قائمة الإنتظار. يمكنك عرض الأرقام التسلسلية بأمر 'list'"
},
"search" : {
"provider" : "مزود البحث (YouTube أو YouTube Music). الإفتراضي: YouTube Music",
"query" : "كلمات البحث."
},
"settings" : {
"get" : {
"setting" : "جلب قيمة لإعداد ما."
},
"set" : {
"setting" : "اسم الإعداد الذي تود أن تعدله.",
"value" : "القيمة الجديدة."
}
},
"volume" : {
"volume" : "حجم الصوت الجديد بالنسب المئوية (علي سبيل المثال `30` أو `100`). إذا كبرت حجم الصوت فوق 100% قد يكون هناك فقدان للجودة."
}
},
"pagination" : {
"embed" : {
"sclosedContent" : "{{content}} الجلسة مغلقة - قلب الصفحات **لن يعمل** من هنا.",
"sclosedTitle" : "الجلسة مغلقة"
},
"error" : {
"perms" : {
"messages" : "لا يمكنني إرسال رسائل في {{channel}}. يرجى الاتصال بمسؤول الخادم ومنحي إذن \"SendMessage\".",
"reactions" : "أحتاج إلى أذونات رد الفعل للعمل. الرجاء الاتصال بمسؤول الخادم لمعالجة هذا."
}
}
},
"subcommands" : {
"settings" : {
"get" : "جلب قيمة إعداد معين أو إعدادات السيرفر.",
"set" : "تعديل قيمة إعداد معين."
}
},
"voice" : {
"join" : {
"cancelled" : "الغاء!",
"error" : {
"dc" : "لا يبدو أننا في نفس القناة الصوتية.",
"invalid" : "قناة صوتية غير صالحة. يرجى المحاولة مرة أخرى والتحقق من الأحرف الكبيرة! (`x` للإلغاء)",
"perms" : "حدث خطأ ما. غير قادر على الانضمام إلى {{channel}}. هل لدي الإذن المطلوب؟"
},
"warning" : {
"nc" : "لا يبدو أنك متصل ب {{channel}}. هل نسيت الانضمام؟"
}
}
}
}
+118
View File
@@ -0,0 +1,118 @@
{
"cmdBuilder" : {
"requirement" : {
"permission" : "تۆ مۆڵەتی پێویستت نییە بۆ جێبەجێکردنی ئەم فەرمانە!"
},
"subcommand" : {
"invalid" : "فەرمانی لاوەکی نادروست. یەکێک لەم هەڵبژاردنانەی خوارەوە تاقی بکەرەوە: `$previousCmd <$cmdlist>`"
}
},
"cmdHandler" : {
"command" : {
"invalid" : "فەرمانی نەناسراو {{command}}!",
"suggestion" : "مەبەستت {{command}} بوو؟ (بۆ جێبەجێکردنی ئەمە بنووسە {{acceptCommand}})"
},
"help" : {
"pageStructure" : "فەرمانە بەردەستەکان (لاپەڕە $currPage/$maxPage): \n\n$content\n\n`$prefix$helpCmd <فەرمان>` بنووسە بۆ زانینی زیاتر. دەتوانیت فەرمانی لاوەکیش لەخۆبگرێت.\nنموونە: `$prefix$helpCmd settings get`\n\nتێبینی: تیرەکانی خوارەوەی ئەم نامەیە بەکاربهێنە بۆ گۆڕینی لاپەڕەکان، یان ژمارەی لاپەڕەی پێویست دیاریبکە بە `$prefix$helpCmd <ژمارەی لاپەڕە>`"
},
"invalidFlag" : "ئاڵای نادروست `$invalidFlag`. لەگەڵ هیچ هەڵبژاردنێکی ئەم فەرمانە نایگونجێت.\n`$previousCmd $invalidFlag`",
"page" : {
"invalid" : "{{number}} ژمارەی لاپەڕەیەکی دروست نییە!"
},
"permissions" : {
"message" : "تکایە مۆڵەتی {{permission}} م پێ بدە لە {{channel}} یان پەیوەندی بە بەڕێوەبەری سێرڤەرەوە بکە. من بەبێ ئەمە ناتوانم نەشتەرگەری بکەم."
}
},
"commands" : {
"clear" : "هەموو گۆرانییەکان لە ڕیزەکە بسڕەوە.",
"join" : "بۆتەکە بکە بچێتە کەناڵێکی دەنگی دیاریکراو.",
"leave" : "وا لە بۆتەکە بکە کەناڵی دەنگی ئێستات بەجێبهێڵێت",
"list" : "گۆرانییەکانی ڕیزەکەی کەناڵی دەنگی ئێستات لیست بکە.",
"login" : "چوونەژوورەوەی ئەکاونتەکەت لە ماڵپەڕەکەدا پشتڕاست بکەرەوە",
"loop" : "گەڕانەوەی ڕیزە/گۆرانییەکە کوز بکەرەوە.",
"lyrics" : "دەقی گۆرانییەکەی ئێستا بهێنەوە. تکایە تێبینی بکە کە دەقەکە لەوانەیە جیاواز بێت لە دەقی ڕاستەقینەکە، چونکە Genius هەمیشە گۆرانییەکەی دروست نادۆزێتەوە.",
"np" : "ناو و بەستەری گۆرانییەکەی ئێستا داوا بکە.",
"pause" : "وەستاندنی پەخشکردنەکە لە کەناڵی دەنگیدا",
"ping" : "پێشگرەکەی من لەم سێرڤەرەدا بریتییە لە: {{prefix}}\n\n{{helpCmd}} بەکاربهێنە بۆ دەستپێکردن!",
"play" : "ڤیدیۆیەکی یوتیوب پەخش بکە بە url/پرسیار یان پلەی لیست بە url. خزمەتگوزارییە تریش پشتگیری دەکرێن.\nبە شێوەیەکی بنەڕەتی گەڕان لەسەر `Youtube Music` دەکرێت.\nئەگەر دەتەوێت لەسەر `YouTube` بگەڕێیت دەبێت ئەمەش بە ئاشکرا دیاری بکەیت بە `-u yt`.",
"player" : "کۆنتڕۆڵی پەخشکەری ئیموجی بۆ کەناڵی دەنگیت دروست بکە",
"playnext" : "وەکوو %play. ئەنجامەکە لە سەرەوەی ڕیزەکە زیاد دەکرێت.",
"remove" : "گۆرانییەکێکی دیاریکراو لە ڕیزەکە دەربهێنە.",
"resume" : "بەردەوامکردنی پەخشکردنەکە لە کەناڵی دەنگیدا",
"search" : "ئەنجامی گەڕان بۆ پرسیارێکی دیاریکراو نیشان بدە",
"settings" : "ڕێکخستنەکان لە سێرڤەری ئێستادا بگۆڕە/بهێنەوە.",
"shuffle" : "ڕیزەکە بە شێوازێکی هەڕەمەکی دووبارە ڕیز بکەرەوە.",
"skip" : "گۆرانییەکەی ئێستا بتێپەڕێ.",
"stats" : "ئامارەکانی بۆت نیشان بدە وەکوو کاتی فعال.",
"support" : "سێرڤەری پشتگیری Remix. بە ئازادی داوای یارمەتی بکە، هەڵەکان ڕاپۆرت بکە یان تەنها چاوپێکەوتن بکە :)",
"thumbnail" : "وێنەی بچووکی گۆرانییەکەی ئێستا داوا بکە.",
"volume" : "دەنگی ئێستا بگۆڕە."
},
"options" : {
"join" : {
"channel" : "کەناڵێک دیاری بکە کە بۆت پێیدا بچێت. ئەمە پێویستە بەهۆی سنووردارییەکانی (ئێستای) Revolt."
},
"login" : {
"id" : "ناسنامەکەی کە لە کاتی چوونەژوورەوە لە داشبۆردەکەدا وەرت گرتووە."
},
"loop" : {
"type" : "دیاریدەکات کام loop دەبێت کوز بکرێتەوە."
},
"play" : {
"query" : "پرسیار/url ی یوتیوب، url ی پلەی لیست، یان بەستەرێک بۆ گۆرانییەکی Spotify، SoundCloud، یان YouTube Music."
},
"playnext" : {
"query" : "پرسیار/url ی یوتیوب، url ی پلەی لیست، یان بەستەرێک بۆ گۆرانییەکی Spotify، SoundCloud، یان YouTube Music."
},
"remove" : {
"index" : "شوێنی گۆرانییەکە لە ڕیزەکەدا. دەتوانیت بە فرمانی 'list' سەیری پێوەرەکان بکەیت"
},
"search" : {
"provider" : "دابینکەری ئەنجامی گەڕان. (YouTube یان YouTube Music)",
"query" : "ئەو پرسیارەی کە پێویستە بەدوایدا بگەڕێیت."
},
"settings" : {
"get" : {
"setting" : "بەهای ئێستای ڕێکخستنێک بەدەست بهێنە."
},
"set" : {
"setting" : "ناوی ئەو ڕێکخستنەی کە دەتەوێت ڕێکی بخەیت.",
"value" : "بەها نوێیەکە."
}
},
"volume" : {
"volume" : "قەبارەی نوێ بە ڕێژەی سەدی (بۆ نموونە `30` یان `100`). ئەگەر بچیتە سەرووی 100% لەوانەیە لەدەستدانی کوالیتی هەبێت."
}
},
"pagination" : {
"embed" : {
"sclosedContent" : "{{content}}\nدانیشتنەکە داخراوە - گۆڕینی لاپەڕەکان **کارناکات** لێرەوە.",
"sclosedTitle" : "دانیشتن داخرا"
},
"error" : {
"perms" : {
"messages" : "من ناتوانم نامە بنێرم لە {{channel}}. تکایە پەیوەندی بە بەڕێوەبەری سێرڤەرێکەوە بکەن و مۆڵەتی \"SendMessage\"م پێ بدەن.",
"reactions" : "بۆ کارکردن پێویستم بە مۆڵەتی کاردانەوە هەیە. تکایە پەیوەندی بە بەڕێوەبەری سێرڤەرێکەوە بکە بۆ چارەسەرکردنی ئەمە."
}
}
},
"subcommands" : {
"settings" : {
"get" : "بەهای ڕێکخستنێکی دیاریکراو یان ڕێکخستنەکانی سێرڤەرەکە بەدەستبهێنە.",
"set" : "بەهای ڕێکخستنێکی دیاریکراو دابنێ."
}
},
"voice" : {
"join" : {
"cancelled" : "هەڵوەشایەوە!",
"error" : {
"dc" : "پێناچێت لە یەک کەناڵی دەنگیدا بین.",
"invalid" : "کەناڵی دەنگی نادروست. تکایە دووبارە هەوڵبدەرەوە و پیتی گەورە بزانە! (`x` بۆ هەڵوەشاندنەوە)",
"perms" : "هەندێ شت بە هەڵە ڕۆیشت. ناتوانرێت بەشداری {{channel}} بکەیت. ئایا مۆڵەتی پێویستم هەیە؟"
},
"warning" : {
"nc" : "پێناچێت تۆ پەیوەندیت بە {{channel}}ەوە هەبێت. لەبیرت چوو بەشداری بکەیت؟"
}
}
}
}
+118
View File
@@ -0,0 +1,118 @@
{
"cmdBuilder" : {
"requirement" : {
"permission" : "Du hast nicht die notwendigen Berechtigungen, dieses Kommando hier auszuführen."
},
"subcommand" : {
"invalid" : "Ungültiger Unterbefehl. Versuche es bitte mit einer dieser Optionen `$previousCmd <$cmdlist>`"
}
},
"cmdHandler" : {
"command" : {
"invalid" : "Unbekanntes Kommando {{command}}!",
"suggestion" : "Meintest du {{command}}? (Nutze {{acceptCommand}}, um dies auszuführen)"
},
"help" : {
"pageStructure" : "Verfügbare Kommandos (page $currPage/$maxPage): $content Nutze das Kommando `$prefix$helpCmd <command>` um mehr zu erfahren. Du kannst auch zusätzliche Unterbefehle nutzen, wie zum Beispiel: `$prefix$helpCmd command subcommandName` Noch ein Tip: Nutze die Pfeile unter dieser Nachricht, um Seiten umzublättern, oder gib eine gewünschte Seitenzahl mit `$prefix$helpCmd <page number>` an!"
},
"invalidFlag" : "Ungültige Flag `$invalidFlag`. Sie stimmt mit keiner der Optionen im Kommando überein. `$previousCmd $invalidFlag`",
"page" : {
"invalid" : "{{number}} ist keine gültige Seiten-Nummer!"
},
"permissions" : {
"message" : "Bitte erteile mir die {{permission}}-Berechtigung in {{channel}} oder informiere einen Server-Admin. Ich habe in diesem Zustand keinen Zugriff, um zu arbeiten."
}
},
"commands" : {
"clear" : "Entferne alle Songs aus der Warteschlange.",
"join" : "Lasse den Bot einem bestimmten Sprachkanal beitreten",
"leave" : "Lasse den Bot deinen aktuellen Sprachkanal verlassen",
"list" : "Listet die Songs in der Warteschlange deines Kanals auf.",
"login" : "Bestätige die Anmeldung deines Kontos auf der Webseite",
"loop" : "Aktiviere/Deaktiviere die Schleife des aktuellen Songs oder der Warteschlange.",
"lyrics" : "Rufe den Songtext des aktuellen Liedes auf. Bitte beachte, dass dieser vom tatsächlichen Text abweichen kann, da Genius nicht immer den richtigen Song findet.",
"np" : "Rufe den Namen und die URL des Songs ab, der gerade abgespielt wird.",
"pause" : "Pausiere die Wiedergabe in deinem Sprachkanal",
"ping" : "Mein Präfix in diesem Server ist: {{prefix}}\n\nFühre {{helpCmd}} aus, um loszulegen!",
"play" : "Spiele ein YouTube-Video mithilfe einer URL/einem Suchbegriff, oder eine Playlist von einer URL. Einige andere Dienste sind auch unterstützt. \nSuchen werden standardmäßig über `Youtube Music` ausgeführt. Um `Youtube` zu verwenden, muss das mit der Option `-u yt` explizit angegeben werden.",
"player" : "Erstellen eine Emoji-Steuerung für deinen Sprachkanal",
"playnext" : "Siehe %play. Die gefundenen Songs werden am Anfang der Warteschlange eingefügt.",
"remove" : "Entferne einen bestimmten Song von der Warteschlange.",
"resume" : "Setze die Wiedergabe in deinem Sprachkanal fort",
"search" : "Listet die Suchergebnisse für eine bestimmte Suchanfrage auf",
"settings" : "Rufe die Einstellungen eines Servers ab, oder ändere diese.",
"shuffle" : "Ordnet die Warteschlange zufällig an.",
"skip" : "Überspringe den aktuellen Song.",
"stats" : "Rufe Statistiken über den Bot ab.",
"support" : "Der Support-Server für Remix. Zögere nicht, um Hilfe zu bitten, Bugs zu melden oder einfach zu chatten :)",
"thumbnail" : "Rufe das Thumbnail des aktuellen Songs ab.",
"volume" : "Ändere die aktuelle Lautstärke."
},
"options" : {
"join" : {
"channel" : "Gebe den Kanal an, dem der Bot beitreten soll. Dies ist aufgrund Revolt-Einschränkungen notwendig."
},
"login" : {
"id" : "Die ID, die du beim Einloggen auf dem Dashboard erhalten hast."
},
"loop" : {
"type" : "Gibt an, welcher Schleifentyp gesetzt werden soll."
},
"play" : {
"query" : "Eine YouTube-Suchanfrage/URL, Playlist-URL oder ein Link zu einem Song auf Spotify, SoundCloud oder YouTube Music."
},
"playnext" : {
"query" : "Eine YouTube-Suchanfrage/URL, Playlist-URL oder ein Link zu einem Song auf Spotify, SoundCloud oder YouTube Music."
},
"remove" : {
"index" : "Die Position des Liedes in der Warteschlange. Die Position aller Lieder kann mit dem `list` Befehl aufgerufen werden."
},
"search" : {
"provider" : "Der Anbieter der Suchergebnisse (YouTube oder YouTube Music). Standard: YouTube Music",
"query" : "Der Such-Text, nach dem gesucht werden soll."
},
"settings" : {
"get" : {
"setting" : "Rufe den Wert einer bestimmten Einstellung ab."
},
"set" : {
"setting" : "Der Name der Einstellung, die bearbeitet werden soll.",
"value" : "Der neue Wert der Einstellung."
}
},
"volume" : {
"volume" : "Die neue Lautstärke in Prozent (z.B.: `30` oder `100`). Werte über 100 % können Qualitätsverluste verursachen."
}
},
"pagination" : {
"embed" : {
"sclosedContent" : "{{content}}\nSitzung geschlossen - Das Umblättern funktioniert ab jetzt **nicht mehr**.",
"sclosedTitle" : "Sitzung geschlossen"
},
"error" : {
"perms" : {
"messages" : "Ich kann keine Nachrichten in {{channel}} senden. Bitte wende dich an einen Serveradministrator und erteile mir die Berechtigung \"SendMessage\"",
"reactions" : "Ich brauche die Berechtigung, auf Nachrichten zu reagieren. Bitte wende dich an einen Serveradministrator, um dies zu klären."
}
}
},
"subcommands" : {
"settings" : {
"get" : "Rufe den Wert einer bestimmten Einstellung oder eine Liste der Einstellungen des gesamten Servers auf.",
"set" : "Lege den Wert einer bestimmten Einstellung fest."
}
},
"voice" : {
"join" : {
"cancelled" : "Abgebrochen!",
"error" : {
"dc" : "Es scheint, als wären wir nicht im selben Sprachkanal.",
"invalid" : "Ungültiger Sprachkanal. Bitte versuche es erneut und überprüfe deine Eingabe auf Groß- und Kleinschreibung! (`x` zum Abbrechen)",
"perms" : "Etwas ist schiefgelaufen. Ich kann {{channel}} nicht betreten. Habe ich die nötigen Berechtigungen?"
},
"warning" : {
"nc" : "Es scheint, als wärst du nicht mit {{channel}} verbunden. Hast du vergessen, dort beizutreten?"
}
}
}
}
+118
View File
@@ -0,0 +1,118 @@
{
"cmdBuilder" : {
"requirement" : {
"permission" : "You don't have the needed permissions to run this command!"
},
"subcommand" : {
"invalid" : "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`"
}
},
"cmdHandler" : {
"command" : {
"invalid" : "Unknown command {{command}}!",
"suggestion" : "Did you mean {{command}}? (Type {{acceptCommand}} to run this)"
},
"help" : {
"pageStructure" : "Available Commands (page $currPage/$maxPage): \n\n$content\n\nRun `$prefix$helpCmd <command>` to learn more about it. You can also include subcommands.\nFor example: `$prefix$helpCmd settings get`\n\nTip: Use the arrows beneath this message to turn pages, or specify the required page by using `$prefix$helpCmd <page number>`"
},
"invalidFlag" : "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`",
"page" : {
"invalid" : "{{number}} is not a valid page number!"
},
"permissions" : {
"message" : "Please grant me the {{permission}} permission in {{channel}} or contact a server administrator. I am unable to operate without this."
}
},
"commands" : {
"clear" : "Remove all songs from the queue.",
"join" : "Make the bot join a specific voice channel.",
"leave" : "Make the bot leave your current voice channel",
"list" : "List the songs in the queue of your current voice channel.",
"login" : "Confirm the login of your account on the website",
"loop" : "Toggle the looping of your queue/song.",
"lyrics" : "Fetch the lyrics of the current song. Please note that the lyrics might differ from the actual ones, as Genius doesn't always find the right song.",
"np" : "Request the name and url of the currently playing song.",
"pause" : "Pause the playback in your voice channel",
"ping" : "My prefix in this server is: {{prefix}}\n\nUse {{helpCmd}} to get started!",
"play" : "Play a youtube video from url/query or a playlist by url. Other services are supported as well.\nSearches will be done on `Youtube Music` by default.\nIf you want to search on `YouTube` you will have to specify that with `-u yt` explicitly.",
"player" : "Create an emoji player control for your voice channel",
"playnext" : "Same as %play. The result will be added to the top of the queue.",
"remove" : "Remove a specific song from the queue.",
"resume" : "Resume the playback in your voice channel",
"search" : "Display the search results for a given query",
"settings" : "Change/Get settings in the current server.",
"shuffle" : "Re-orders the queue randomly.",
"skip" : "Skip the current playing song.",
"stats" : "Display stats about the bot like the uptime.",
"support" : "The support server for Remix. Feel free to ask help, report bugs or just chat :)",
"thumbnail" : "Request the thumbnail of the currently playing song.",
"volume" : "Change the current volume."
},
"options" : {
"join" : {
"channel" : "Specify the channel, the bot should join. This is necessary due to (current) Revolt limitations."
},
"login" : {
"id" : "The id you got from logging in at the dashboard."
},
"loop" : {
"type" : "Specifies what loop should be toggled."
},
"play" : {
"query" : "A YouTube query/url, playlist url, or a link to a Spotify, SoundCloud, or YouTube Music song."
},
"playnext" : {
"query" : "A YouTube query/url, playlist url, or a link to a Spotify, SoundCloud, or YouTube Music song."
},
"remove" : {
"index" : "The position of the song in the queue. You can view the indices with the 'list' command"
},
"search" : {
"provider" : "The search result provider (YouTube or YouTube Music). Default: Youtube Music",
"query" : "The query to search for."
},
"settings" : {
"get" : {
"setting" : "Get the current value of a setting."
},
"set" : {
"setting" : "The name of the setting you want to set.",
"value" : "The new value."
}
},
"volume" : {
"volume" : "The new volume in percentages (e.g. `30` or `100`). If you go above 100% there might be quality loss."
}
},
"pagination" : {
"embed" : {
"sclosedContent" : "{{content}}\nSession closed - Changing pages **won't work** from here.",
"sclosedTitle" : "Session Closed"
},
"error" : {
"perms" : {
"messages" : "I am unable to send messages in {{channel}}. Please contact a server administrator and grant me the \"SendMessage\" permission.",
"reactions" : "I need reaction permissions to work. Please contact a server administrator to address this."
}
}
},
"subcommands" : {
"settings" : {
"get" : "Get the value of a specific setting or the settings of the server.",
"set" : "Set the value of a specific setting."
}
},
"voice" : {
"join" : {
"cancelled" : "Cancelled!",
"error" : {
"dc" : "It doesn't look like we're in the same voice channel.",
"invalid" : "Invalid voice channel. Please try again and check capitalization! (`x` to cancel)",
"perms" : "Something went wrong. Unable to join {{channel}}. Do I have the needed permissions?"
},
"warning" : {
"nc" : "You don't seem to be connected to {{channel}}. Did you forget to join?"
}
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"cmdBuilder" : {
"requirement" : {
"permission" : "Você não tem as permissões necessárias para executar este comando!"
}
},
"cmdHandler" : {
"command" : {
"invalid" : "Comando desconhecido {{command}}!"
},
"page" : {
"invalid" : "{{number}} não é um n"
}
},
"commands" : {
"clear" : "Remover todas m"
}
}
+12
View File
@@ -0,0 +1,12 @@
[
{
"name": "wb-dashboard",
"index": "./dashboard/index.js",
"enabled": false
},
{
"name": "rbl-stats",
"index": "./rbl.js",
"enabled": false
}
]
+4
View File
@@ -0,0 +1,4 @@
{
"playlists": 30,
"songs": 600
}