GPTcord/scripts/pushCommands.ts
Wroclaw 63cb52e7f4 Command: Add integration and context types
While discord api supports that, discord api types, which discord.js depends on does not.
2024-04-23 20:56:55 +02:00

66 lines
2.4 KiB
TypeScript

// https://discordjs.guide/creating-your-bot/command-deployment.html#guild-commands
import { REST, RESTGetAPIOAuth2CurrentApplicationResult, RESTPostAPIApplicationCommandsJSONBody, Routes } from "discord.js";
import { config } from "../src/index";
import requireDirectory from "require-directory";
import
Command
, {
ApplicationIntegrationType
, InteractionContextTypes
, InteractionTypeMap
} from "../src/command";
const post: RESTPostAPIApplicationCommandsJSONBody[] = [];
const guildId = process.argv.slice(2)[0];
const importedCommands = requireDirectory(module, "../src/commands");
function isGuildCommand(command: Command<keyof InteractionTypeMap>): boolean {
// guild Commmand is when it's a guild install and context is guild (and these are defaults if not provided)
return (command.integration_types?.includes(ApplicationIntegrationType.Guild_Install) ?? true)
&& (command.contexts?.includes(InteractionContextTypes.Guild) ?? true);
}
for (const obj in importedCommands) {
try {
const allExports = importedCommands[obj] as {default: unknown};
const defaultExport = allExports.default;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
const constructedExport = new defaultExport() as unknown;
if (!(constructedExport instanceof Command)) throw new Error(`${obj}'s default does not extends Command`);
if (guildId && guildId !== "" && isGuildCommand(constructedExport as Command<keyof InteractionTypeMap>)) {
console.log(`Skipping ${obj} because it's not a guild command`);
continue;
}
post.push(constructedExport.toRESTPostApplicationCommands());
} catch (e) {
console.error(e);
}
}
const rest = new REST().setToken(config.tokens.Discord);
(async () => {
const me = await rest.get(Routes.oauth2CurrentApplication()) as RESTGetAPIOAuth2CurrentApplicationResult;
if (guildId && guildId !== "") {
console.log(`Started refreshing ${post.length} application guild (${guildId}) commands.`);
await rest.put(
Routes.applicationGuildCommands(me.id, guildId),
{ body: post },
);
} else {
console.log(`Started refreshing ${post.length} application global commands.`);
await rest.put(
Routes.applicationCommands(me.id),
{ body: post },
);
}
console.log("Refreshed successfully");
process.exit(0);
})().catch( e => {
console.error(e);
process.exit(1);
});