import { Client, CommandInteraction, Events, GatewayIntentBits, REST, Routes, } from "discord.js"; import { buttonCommands, slashCommands } from "./commands.ts"; function requireEnv(key: string): string { let value = process.env[key]; if (!value) { throw new Error(`Missing ${key} environment variable.`); } return value; } let token = requireEnv("DISCORD_TOKEN"); let clientId = requireEnv("DISCORD_CLIENT_ID"); let guildId = requireEnv("DISCORD_GUILD_ID"); let client = new Client({ intents: [GatewayIntentBits.Guilds] }); let rest = new REST({ version: "10" }).setToken(token); async function registerSlashCommands() { await rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: slashCommands.map(command => command.slashCommand.toJSON()), }); } client.once(Events.ClientReady, (readyClient) => { console.log(`Logged in as ${readyClient.user.tag}`); }); client.on(Events.InteractionCreate, async (interaction) => { try { if (interaction.isChatInputCommand()) { for (let command of slashCommands) { if (interaction.commandName === command.slashCommand.name) { await command.handler(interaction); break; } } } else if (interaction.isButton()) { for (let button of Object.values(buttonCommands)) { if (interaction.customId.startsWith(button.prefix)) { let id = interaction.customId.slice(button.prefix.length); await button.handler(interaction, id); break; } } } } catch (error) { if (error === "done") return; if (interaction instanceof CommandInteraction) { console.error("Error while handling interaction", error); if (interaction.deferred || interaction.replied) { await interaction.followUp({ content: "Something went wrong! :(", flags: "Ephemeral", }); } else { await interaction.reply({ content: "Something went wrong! :(", flags: "Ephemeral", }); } } } }); try { await registerSlashCommands(); await client.login(token); } catch (error) { console.error("Discord bot failed to start", error); process.exit(1); }