palico-bot/index.js

91 lines
2.7 KiB
JavaScript

import { Client, Collection, GatewayIntentBits } from "discord.js";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { config } from "./src/config.js";
import { MusicQueue } from "./src/music/queue.js";
import { startWebServer } from "./src/web/server.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates],
});
client.commands = new Collection();
const foldersPath = path.join(__dirname, "src/commands");
const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) {
if (folder.indexOf("[disabled]") === -1 || config.environnement === "test") {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs
.readdirSync(commandsPath)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const commandFile = await import(filePath);
if ("data" in commandFile.command && "execute" in commandFile.command) {
client.commands.set(commandFile.command.data.name, commandFile);
} else {
console.log(
`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`
);
}
}
}
}
const eventsPath = path.join(__dirname, "src/events");
const eventFiles = fs
.readdirSync(eventsPath)
.filter((file) => file.endsWith(".js"));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const eventFile = await import(filePath);
if (eventFile.event.once) {
client.once(eventFile.event.name, (...args) =>
eventFile.event.execute(...args)
);
} else {
client.on(eventFile.event.name, (...args) =>
eventFile.event.execute(...args)
);
}
}
const musicQueue = new MusicQueue(client);
await client.login(config.token);
const { server } = startWebServer({ queue: musicQueue });
server.on("error", (error) => {
console.error("HTTP server error", error);
});
let shuttingDown = false;
async function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
console.log(`[${new Date().toLocaleString()}] Shutting down (${signal})`);
musicQueue.shutdown();
client.destroy();
const forceExit = setTimeout(() => process.exit(1), 10_000);
forceExit.unref();
server.close(() => {
clearTimeout(forceExit);
});
}
process.once("SIGTERM", () => void shutdown("SIGTERM"));
process.once("SIGINT", () => void shutdown("SIGINT"));
process.on("unhandledRejection", (error) => {
console.error("Unhandled promise rejection", error);
});
export { client, musicQueue };