Files
blitzkit/src/behaviors/interactionCreate.ts
T

75 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-04-20 13:37:10 +00:00
import {
CacheType,
Collection,
Interaction,
REST,
RESTPostAPIChatInputApplicationCommandsJSONBody,
Routes,
SlashCommandBuilder,
} from 'discord.js';
import { readdirSync } from 'fs';
2023-04-20 14:09:22 +00:00
import discord from '../../discord.json' assert { type: 'json' };
2023-04-21 23:45:13 +00:00
import getClientId from '../utilities/getClientId.js';
2023-04-22 19:32:49 +00:00
import isDev from '../utilities/isDev.js';
2023-04-20 14:09:22 +00:00
2023-04-20 13:37:10 +00:00
export interface CommandRegistry {
2023-04-22 19:32:49 +00:00
inDev?: boolean;
2023-04-20 13:37:10 +00:00
data: SlashCommandBuilder;
execute: (interaction: Interaction) => void;
}
const commandCollection = new Collection<string, CommandRegistry>();
const commands: RESTPostAPIChatInputApplicationCommandsJSONBody[] = [];
const commandFolders = readdirSync('src/commands/');
2023-04-20 14:09:22 +00:00
const rest = new REST().setToken(process.env.DISCORD_TOKEN!);
2023-04-20 13:37:10 +00:00
for (const file of commandFolders) {
const command = (await import(`../commands/${file}`)) as CommandRegistry;
2023-04-21 23:45:13 +00:00
2023-04-22 19:32:49 +00:00
if (isDev() ? command.inDev ?? false : true) {
2023-04-21 23:45:13 +00:00
commands.push(command.data.toJSON());
commandCollection.set(command.data.name, command);
}
2023-04-20 13:37:10 +00:00
}
try {
console.log(`Started refreshing ${commands.length} command(s).`);
const data = (await rest.put(
2023-04-21 23:45:13 +00:00
Routes.applicationGuildCommands(getClientId(), discord.guild_id),
2023-04-20 13:37:10 +00:00
{ body: commands },
)) as { length: number };
console.log(`Successfully reloaded ${data.length} command(s).`);
} catch (error) {
console.error(error);
}
export default async function interactionCreate(
interaction: Interaction<CacheType>,
) {
if (!interaction.isChatInputCommand()) return;
const command = commandCollection.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({
content: 'There was an error while executing this command!',
ephemeral: true,
});
} else {
await interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true,
});
}
}
}