all repos — stealth-developers @ 4ba5deca0873ed7cfa5763ae4c64f6fa4db2b996

src/handlers/interactions.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
import type { ApplicationCommandData, Client, Snowflake } from "discord.js";
import { Collection, REST, Routes } from "discord.js";

import cfg from "../config.ts";
import type { ICommand } from "../types.ts";
import { Logger } from "../utils/logging.ts";
import { crawlDirectory, getHandlerPath } from "./common.ts";

const logger = new Logger("interactions");
export const commands = new Collection<string, ICommand>();

async function getCommands(): Promise<ICommand[]> {
	const processFile = async (fileUrl: string) => {
		const { default: interaction } = await import(fileUrl);
		if (!interaction.data) {
			logger.info(`${fileUrl} does not have a data property, skipping`);
			return;
		}
		commands.set(interaction.data.name, interaction);
		return interaction;
	};

	return await crawlDirectory<ICommand>(
		getHandlerPath("interactions"),
		processFile,
	);
}

async function registerInteractions(
	client: Client,
	interactions: ApplicationCommandData[],
) {
	if (!client.user) return logger.error("client user is not available");
	if (!client.application)
		return logger.error("client application is not available");
	if (interactions.length === 0) return;

	logger.info("registering interactions...");
	const rest = new REST({ version: "9" }).setToken(cfg.data.discord.token);

	try {
		logger.info("registering commands...");
		await rest.put(Routes.applicationCommands(<Snowflake>client.user.id), {
			body: interactions,
		});
		logger.info(`registered ${interactions.length} commands`);
	} catch (error) {
		logger.error("failed to register commands", error);
	}
}

async function registerCommands(client: Client) {
	const commands = await getCommands();
	if (commands.length === 0) return logger.warn("no commands found");

	const interactions = commands.map((command) => command.data);
	await registerInteractions(client, interactions);
}

export default registerCommands;