Skip to content
Snippets Groups Projects
registerCommands.js 1.55 KiB
Newer Older
const {REST} = require('@discordjs/rest');
const {Routes} = require('discord-api-types/v9');
const {Client, Intents} = require('discord.js');
const fs = require('fs');
const botConfig = {
    token: process.env.DISCORD_API_TOKEN,
    applicationID: process.env.DISCORD_APP_ID
};

// Loading discord client to get all guild IDs
const client = new Client({intents: [Intents.FLAGS.GUILDS]});

client.on('ready', () => {
    // Getting all command Javascript files from the commands folder
    commands = []
    const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

    for (const file of commandFiles) {
        const command = require(`./commands/${file}`);
        commands.push(command);
    }

    const rest = new REST({version: '9'}).setToken(botConfig.token);

    (async () => {
        try {
            console.log('Started refreshing application (/) commands.');

            const guildIDs = await client.guilds.cache.map(guild => guild.id);
            console.log(guildIDs)
            //Going through all guildIDs and registering the commands with each one.
            await Promise.all(guildIDs.map(async (guildID) => {
                console.log(guildID);
                await rest.put(
                    Routes.applicationGuildCommands(botConfig.applicationID, guildID),
                    {body: commands},
                );
            }));

            console.log('Successfully reloaded application (/) commands.');
        } catch (error) {
            console.error(error);
        }
    })();
});
client.login(botConfig.token);