yaejunyang/packages/bot/index.ts
2026-02-09 18:31:56 +00:00

66 lines
2.1 KiB
TypeScript

import { Client, Events, GatewayIntentBits, REST, Routes } from "discord.js";
import { commandMap, DiscordCommand } from "./command";
import { eventMap } from "./event";
import { OutputHandler } from "../utils/outputHandler";
import { APPLICATION_ID, GUILD_ID } from "../env";
export class DiscordBot {
rest: REST;
client: Client;
constructor(token: string) {
this.client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.MessageContent,
],
});
this.rest = new REST({ version: "10" }).setToken(token);
}
private async putCommands(commands: DiscordCommand[]): Promise<void> {
if (!this.client.isReady())
throw new Error("Client is not ready");
await this.rest.put(
Routes.applicationGuildCommands(this.client.application.id, GUILD_ID),
{
body: commands.map((command) => command.data.toJSON()),
}
);
}
public async registerCommands(): Promise<void> {
try {
if (!this.client.isReady()) {
await this.client.once(Events.ClientReady, () => this.putCommands(commandMap));
} else {
await this.putCommands(commandMap);
}
} catch(err) {
OutputHandler.errorLog("[Command Register Error]", err);
}
}
public async deleteCommand(commandId: string): Promise<void> {
if (!this.client.isReady())
throw new Error("Client is not ready");
await this.rest.delete(
Routes.applicationCommand(this.client.application.id, commandId)
);
}
public registerEvents() {
try {
for (let index = 0; index < eventMap.length; index++) {
const event = eventMap[index];
this.client.on(event.event, event.callback);
}
} catch(err) {
OutputHandler.errorLog("[Event Register Error]", err);
}
}
}