Files
commands
utils
.gitignore
config.json
deploy-commands.js
index.js
package.json
README.md
Code
16 891
index.js
import "dotenv/config";
import { Client, Collection, GatewayIntentBits } from "discord.js";
import { LavalinkManager } from "lavalink-client";
import { readdir } from "node:fs/promises";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { sendNowPlaying } from "./utils/music.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const config = JSON.parse(
readFileSync(join(__dirname, "config.json"), "utf8")
);
const token = process.env.DISCORD_TOKEN;
if (!token) {
throw new Error("DISCORD_TOKEN is missing from the environment.");
}
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildVoiceStates
]
});
client.commands = new Collection();
client.twentyFourSeven = new Map();
const configuredNodes = config.lavalink.nodes.map((node, index) => {
const isPrimaryNode = index === 0;
return {
id: node.id,
host: isPrimaryNode && process.env.LAVALINK_HOST
? process.env.LAVALINK_HOST
: node.host,
port: isPrimaryNode && process.env.LAVALINK_PORT
? Number(process.env.LAVALINK_PORT)
: node.port,
authorization: isPrimaryNode && process.env.LAVALINK_PASSWORD
? process.env.LAVALINK_PASSWORD
: node.password,
secure: isPrimaryNode && process.env.LAVALINK_SECURE
? process.env.LAVALINK_SECURE === "true"
: node.secure
};
});
client.lavalink = new LavalinkManager({
nodes: configuredNodes,
reconnectInterval: config.lavalink.reconnectInterval,
reconnectAttempts: config.lavalink.reconnectAttempts,
sendToShard: (guildId, payload) => {
const guild = client.guilds.cache.get(guildId);
if (guild?.shard) {
return guild.shard.send(payload);
}
return client.ws.broadcast(payload);
}
});
async function loadCommands() {
const commandsPath = join(__dirname, "commands");
const commandFiles = (await readdir(commandsPath))
.filter((file) => file.endsWith(".js"))
.sort();
for (const file of commandFiles) {
const commandUrl = pathToFileURL(join(commandsPath, file)).href;
const commandModule = await import(commandUrl);
const command = commandModule.default;
if (!command?.data?.name || typeof command.execute !== "function") {
console.warn(`Skipping invalid command module: ${file}`);
continue;
}
client.commands.set(command.data.name, command);
}
}
client.once("ready", async () => {
await client.lavalink.init({
id: client.user.id,
username: client.user.username
});
console.log(`Logged in as ${client.user.tag}`);
console.log(`Loaded ${client.commands.size} slash commands.`);
});
client.on("raw", (packet) => {
client.lavalink.sendRawData(packet);
});
client.on("interactionCreate", async (interaction) => {
if (!interaction.isChatInputCommand()) {
return;
}
const command = client.commands.get(interaction.commandName);
if (!command) {
await interaction.reply({
content: "This command is not currently available.",
ephemeral: true
});
return;
}
try {
await command.execute(interaction, client, config);
} catch (error) {
console.error(`Command error in /${interaction.commandName}:`, error);
const response = {
content: "An unexpected error occurred while processing this command.",
ephemeral: true
};
if (interaction.deferred || interaction.replied) {
await interaction.editReply(response).catch(() => {});
} else {
await interaction.reply(response).catch(() => {});
}
}
});
client.lavalink.on("trackStart", async (player, track) => {
console.log(
`Track started in ${player.guildId}: ${track?.info?.title ?? "Unknown track"}`
);
await sendNowPlaying(client, player, track).catch((error) => {
console.error("Unable to send the now-playing embed:", error);
});
});
client.lavalink.on("trackEnd", (player, track) => {
console.log(
`Track ended in ${player.guildId}: ${track?.info?.title ?? "Unknown track"}`
);
});
client.lavalink.on("queueEnd", async (player) => {
const is247Enabled = client.twentyFourSeven.get(player.guildId) === true;
console.log(
`Queue ended in ${player.guildId}. 24/7 mode: ${is247Enabled ? "enabled" : "disabled"}`
);
if (is247Enabled) {
return;
}
await player.destroy().catch((error) => {
console.error(`Unable to destroy player in ${player.guildId}:`, error);
});
});
client.lavalink.on("trackError", (player, track, payload) => {
console.error(
`Track error in ${player.guildId} for ${track?.info?.title ?? "Unknown track"}:`,
payload
);
});
client.lavalink.on("nodeConnect", (node) => {
console.log(`Lavalink node connected: ${node.options?.id ?? node.id}`);
});
client.lavalink.on("nodeDisconnect", (node, reason) => {
console.warn(
`Lavalink node disconnected: ${node.options?.id ?? node.id}`,
reason ?? ""
);
});
client.lavalink.on("nodeError", (node, error) => {
console.error(
`Lavalink node error: ${node.options?.id ?? node.id}`,
error
);
});
client.lavalink.on("socketClosed", (player, payload) => {
console.warn(
`Lavalink voice socket closed in ${player.guildId}:`,
payload
);
});
process.on("unhandledRejection", (error) => {
console.error("Unhandled promise rejection:", error);
});