Something went wrong. Try again.
A Discord bot designed to entertain your server esmbot.net
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248import process from "node:process";import { detectRuntime, getEnv } from "#utils/runtime.js";
const runtimeInfo = detectRuntime();
if (runtimeInfo.type === "node" && runtimeInfo.version) { const [major, minor] = runtimeInfo.version.split(".").map(Number); if (major < 22 || (major === 22 && minor < 13) || (major === 23 && minor < 4)) { console.error(`You are currently running Node.js version ${runtimeInfo.version.split}.esmBot requires Node.js version 22.13.0/23.4.0 or above.Please refer to step 2 of the setup guide: https://docs.esmbot.net/setup/#2-install-nodejs`); process.exit(1); }}if (runtimeInfo.platform === "win32") { console.error( "\x1b[1m\x1b[31m\x1b[40m" + `WINDOWS IS NOT OFFICIALLY SUPPORTED!Although there's a (very) slim chance of it working, multiple aspects of esmBot are built with UNIX-like systems in mind and could break on Win32-based systems. If you want to run esmBot on Windows, using Windows Subsystem for Linux is highly recommended.esmBot will continue to run past this message in 5 seconds, but keep in mind that it could break at any time. Continue running at your own risk; alternatively, stop the bot using Ctrl+C and install WSL.` + "\x1b[0m", ); await new Promise((resolve) => setTimeout(resolve, 5000));}
const botToken = getEnv("TOKEN");if (!botToken) { console.error(`No token was provided!esmBot requires a valid Discord bot token to function. Generate a new token from the "Bot" tab in your Discord application settings and paste it into your .env file.`); process.exit(1);}
if (botToken.length < 59) { console.error(`Incorrect bot token length!You may have accidentally copied the OAuth2 client secret. Try generating a new token from the "Bot" tab in your Discord application settings.`); process.exit(1);}
import { glob, readFile } from "node:fs/promises";import { resolve } from "node:path";import { Client, type ClientEvents, Constants } from "oceanic.js";import commandConfig from "#config/commands.json" with { type: "json" };import { endBroadcast, startBroadcast } from "#utils/activity.js";import { locales, paths } from "#utils/collections.js";import { load } from "#utils/handler.js";import { createInteractionServer } from "#utils/httpInteractions.js";import logger from "#utils/logger.js";import { initMediaLib, reloadMediaConnections } from "#utils/media.js";import { exit, getVers, initLog } from "#utils/misc.js";import { connect, connected, reload } from "#utils/soundplayer.js";import { parseThreshold } from "#utils/tempimages.js";import { init as dbInit } from "./database.ts";import events from "./events/index.ts";
const intents = [Constants.Intents.GUILD_VOICE_STATES, Constants.Intents.DIRECT_MESSAGES, Constants.Intents.GUILDS];if (commandConfig.types.classic) { intents.push(Constants.Intents.GUILD_MESSAGES); intents.push(Constants.Intents.MESSAGE_CONTENT);}
const runtime = detectRuntime();
await getVers();if (getEnv("CLUSTER_TYPE") !== "node") initLog();
if (!commandConfig.types.classic && !commandConfig.types.application) { logger.error( "Both classic and application commands are disabled! Please enable at least one command type in config/commands.json.", ); process.exit(1);}
const database = await dbInit();if (database) { // database handling const dbResult = await database.upgrade(); if (dbResult === 1) process.exit(1);}
// process the threshold into bytes earlyconst tempdir = getEnv("TEMPDIR");const threshold = getEnv("THRESHOLD");if (tempdir && threshold) { await parseThreshold(tempdir, threshold);}
// register localeslogger.log("info", "Attempting to load locale data...");for await (const localeFile of glob(resolve(import.meta.dirname, "..", "locales", "*.json"))) { logger.log("main", `Loading locales from ${localeFile}...`); try { const commandArray = localeFile.split("/"); const localeName = commandArray.at(-1)!.split(".")[0]; const data = await readFile(localeFile, { encoding: "utf8" }); locales.set(localeName, JSON.parse(data)); } catch (e) { logger.error(`Failed to register locales from ${localeFile}: ${e}`); }}logger.log("info", "Finished loading locale data.");
// register commands and their infologger.log("info", "Attempting to load commands...");for await (const commandFile of glob( resolve(import.meta.dirname, "..", "commands", "*", runtime.tsLoad ? "*.{js,ts}" : "*.js"),)) { try { await load(commandFile); } catch (e) { logger.error(`Failed to register command from ${commandFile}: ${e}`); }}logger.log("info", "Finished loading commands.");
if (database) { await database.setup();}if (getEnv("API_TYPE") === "ws") await reloadMediaConnections();else await initMediaLib();
const shards = getEnv("SHARDS");const shardArray = shards ? JSON.parse(shards) : null;
// create the oceanic clientconst client = new Client({ auth: `Bot ${botToken}`, allowedMentions: { everyone: false, roles: false, users: true, repliedUser: true, }, gateway: { concurrency: "auto", maxShards: "auto", shardIDs: shardArray, presence: { status: "idle", activities: [ { type: 0, name: "Starting esmBot...", }, ], }, intents, }, rest: { baseURL: getEnv("REST_PROXY") || undefined, requestTimeout: Number(getEnv("REST_TIMEOUT_MS")) || 15000, }, collectionLimits: { messages: 50, channels: !commandConfig.types.classic ? 0 : Number.POSITIVE_INFINITY, guildThreads: !commandConfig.types.classic ? 0 : Number.POSITIVE_INFINITY, emojis: 0, },});
// register eventslogger.log("info", "Registering events...");for (const [name, event] of Object.entries(events)) { logger.log("main", `Registering ${name} event...`); client.on(name as keyof ClientEvents, (event as Function).bind(null, { client, database }));}logger.log("info", "Registered events.");
// Cluster-specific handlingif (getEnv("CLUSTER_TYPE") === "node") { process.on("message", async (packet: { data?: { type: string; from?: string; message: string } }) => { const pm_id = getEnv("pm_id"); if (packet.data?.from === pm_id) return; switch (packet.data?.type) { case "reload": { const cmdPath = paths.get(packet.data.message); if (cmdPath) await load(cmdPath); break; } case "soundreload": await reload(client); break; case "mediareload": await reloadMediaConnections(); break; case "broadcastStart": startBroadcast(client, packet.data.message); break; case "broadcastEnd": endBroadcast(client); break; case "eval": // oxlint-disable-next-line no-eval eval(packet.data.message); break; case "serverCounts": process.send?.({ data: { type: "serverCounts", guilds: client.guilds.size, shards: client.shards.map((v) => { return { id: v.id, procId: Number.parseInt(pm_id as string), latency: v.latency, status: v.status, }; }), mem: process.memoryUsage().heapUsed, }, }); break; } });}
// connect to lavalinkif (!connected) connect(client);
process.on("SIGINT", async () => { logger.info("SIGINT detected, shutting down..."); await exit(client, database);});
process.on("SIGTERM", async () => { logger.info("SIGTERM detected, shutting down..."); await exit(client, database);});
const publicKey = getEnv("PUBLIC_KEY");const interactionsPort = getEnv("INTERACTIONS_PORT");if (publicKey && interactionsPort && !Number.isNaN(interactionsPort)) { const pubKey = await crypto.subtle.importKey("raw", Buffer.from(publicKey, "hex"), "Ed25519", false, ["verify"]); const interactServer = createInteractionServer(client, pubKey, database); interactServer.listen(Number(interactionsPort)); interactServer.on("listening", () => { logger.info(`Started HTTP interactions server on port ${interactionsPort}`); });}
try { await client.connect();} catch (e) { logger.error("esmBot failed to connect to Discord!"); logger.error(e); logger.error("The bot is unable to start, stopping now..."); process.exit(1);}