为什么我的discord.js 机器人命令在启动时不会刷新?

问题描述 投票:0回答:1

我已经实现了一段代码,应该在启动时刷新机器人的所有命令,这是来自index.js的代码:

const token = require('./config.json')['token'];
const { Client, Collection, Events, GatewayIntentBits, GatewayVersion, REST, Routes } = require('discord.js');
const fs = require('node:fs');
const path = require('node:path');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.DirectMessages, GatewayIntentBits.DirectMessageTyping, GatewayIntentBits.DirectMessageReactions, GatewayIntentBits.AutoModerationExecution, GatewayIntentBits.AutoModerationConfiguration, GatewayIntentBits.MessageContent] });
const clientId = '1184598822593253477';
client.commands = new Collection();
//Grab all command folders
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
    const commandsPath = path.join(foldersPath, folder);
    const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
    for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        const command = require(filePath);
        if ('data' in command && 'execute' in command) {
            client.commands.set(command.data.name, command);
        } else {
            console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
        }
    }
}

const rest = new REST().setToken(token);

//On command, find the command in commands/utility folder, and run that command
client.on(Events.InteractionCreate, async interaction => {
    if (!interaction.isChatInputCommand()) return;

    const command = interaction.client.commands.get(interaction.commandName);

    if (!command) {
        console.error(`No command matching command named ${interaction.commandName} was found.`);
        return;
    }

    try {
        await 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 });
        }
    }
});

function reload_command(command_name) {
    const commandName = command_name;
    const command = client.commands.get(commandName);

    if (!command) {
        return console.log(`There is no command with name \`${commandName}\`!`);
    }
    delete require.cache[require.resolve(`./commands/utility/${command.data.name}.js`)];

    try {
        client.commands.delete(command.data.name);
        const newCommand = require(`./commands/utility/${command.data.name}.js`);
        client.commands.set(newCommand.data.name, newCommand);
        console.log(`Command \`${newCommand.data.name}\` was reloaded!`);
    } catch (error) {
        console.error(error);
        console.log(`There was an error while reloading a command \`${command.data.name}\`:\n\`${error.message}\``);
    }
}

//Once client is online...
client.once(Events.ClientReady, async readyClient => {
    reload_command('addkey');
    console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});



client.login(token); //Rebuilds the bot and logs in

这是来自 addkey.js 和 reload.js 的代码

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        //Command information
        .setName('addkey')
        .setDescription('Add a key.'),
    async execute(interaction) {
        await interaction.reply("Running add key");
    },
};
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('reload')
        .setDescription('Reloads a command.'),
    async execute(interaction) {
        const commandName = interaction.options.getString('command', true).toLowerCase();
        const command = interaction.client.commands.get(commandName);

        if (!command) {
            return interaction.reply(`There is no command with name \`${commandName}\`!`);
        }

        delete require.cache[require.resolve(`../${command.category}/${command.data.name}.js`)];

        try {
            interaction.client.commands.delete(command.data.name);
            const newCommand = require(`../${command.category}/${command.data.name}.js`);
            interaction.client.commands.set(newCommand.data.name, newCommand);
            await interaction.reply(`Command \`${newCommand.data.name}\` was reloaded!`);
        } catch (error) {
            console.error(error);
            await interaction.reply(`There was an error while reloading a command \`${command.data.name}\`:\n\`${error.message}\``);
        }
    },
};

我期待看到旧命令在不和谐中消失,新命令出现。我得到的只是我删除后的旧命令,以及自开始制作机器人以来一直存在的 addkey 命令。

javascript discord discord.js command
1个回答
0
投票

首先也是最重要的,你不应该永远让你的机器人在每次上线时更新它的斜线命令。您将来可能会更新您的机器人,或者发生崩溃,迫使您的机器人重新启动,这可能会导致启动时出现不必要的 API 请求,从而导致您的终端出现更多的停机时间,并对 Discord 的终端造成更大的压力(您甚至可能会受到速率限制) )。话虽如此,我建议创建一个单独的 JavaScript 文件,以便在您需要更新斜杠命令时运行。

其次,我注意到你的代码中没有包含

rest.put()
的行。这是更新斜杠命令的重要一步,因为它将命令数据发送到 Discord 的服务器。以下是从 Discord 注册斜线命令指南中提取的使用示例:

await rest.put(
    Routes.applicationCommands(clientId),
    { body: commands },
);
© www.soinside.com 2019 - 2024. All rights reserved.