UNPKG

@dookdiks/discord-bot-builder

Version:
74 lines (73 loc) โ€ข 2.63 kB
import { Client, REST, Routes, Events, GatewayIntentBits, } from "discord.js"; import { CreateInteractionEvent } from "./events"; export class BotBuilder { token; clientId; guildId; rest; client; slashCommands = []; constructor({ token, clientId, guildId, intents = [], ...clientOptions }) { this.token = token; this.clientId = clientId; this.guildId = guildId; this.rest = new REST({ version: "10" }).setToken(this.token); this.client = new Client({ intents: BotBuilder.resolveIntents(intents), ...clientOptions, }); } /** Utility to convert string intent keys to actual bitfield values */ static resolveIntents(keys) { return keys.map((key) => GatewayIntentBits[key]); } /** Dynamically determine correct API route for slash commands */ getCommandsRoute() { return this.guildId ? Routes.applicationGuildCommands(this.clientId, this.guildId) : Routes.applicationCommands(this.clientId); } /** Register all slash commands via Discord REST API */ async registerSlashCommands() { try { const route = this.getCommandsRoute(); await this.rest.put(route, { body: this.slashCommands }); console.log(`๐Ÿ“ก Slash commands registered (${this.slashCommands.length})`); } catch (error) { console.error("โŒ Failed to register slash commands:", error); } } /** Clear all slash commands (useful for cleanup/testing) */ async deleteSlashCommands() { try { const route = this.getCommandsRoute(); await this.rest.delete(route); console.log("๐Ÿงน Slash commands deleted"); } catch (error) { console.error("โŒ Failed to delete slash commands:", error); } } /** Start the Discord bot and register commands on ready */ login() { this.client.once(Events.ClientReady, () => { console.log(`โœ… Logged in as ${this.client.user?.tag}`); this.registerSlashCommands().then(); }); console.log("๐Ÿš€ Logging in..."); return this.client.login(this.token); } /** * Attach an event handler. * If it's a slash command handler, queue its command for registration. */ use(handler) { handler.setClient(this.client); handler.register(); if (handler instanceof CreateInteractionEvent) { this.slashCommands.push(handler.getSlashCommand().toJSON()); } return this; } }