Discord bot 无法使用斜杠命令发送消息

Discord bot cannot send messages with slash commands

我正在使用 slash 命令制作一个 Discord 机器人,我被困在了这一点上。这是我的index.js文件

的代码
const commands = []
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    commands.push(command.data.toJSON());
    
}
const rest = new REST({ version: '9' }).setToken(token);

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

        await rest.put(
            Routes.applicationGuildCommands(clientId, guildId),
            { body: commands },
        );

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


 client.on('ready' , () => {
     console.log('I am online')
     client.user.setActivity('MUSIC ', {type:'LISTENING'})
 })

   client.on('interactionCreate', async interaction => {
       if(!interaction.isCommand())return
       const command = interaction.commands.get(interaction.commandName); 
        if(!command)return
        try {
            await command.execute(interaction)
        } catch (err) {
            console.error(err)
            await interaction.reply('There was an error trying to execute that command!')
        }
    })

还有一个 ping.js 文件来发送简单的 PING-PONG 消息。

const { SlashCommandBuilder } = require('@discordjs/builders')

module.exports = {
    data: new SlashCommandBuilder()
        .setName("ping")
        .setDescription("PING-PONG"),
        
    async execute (interaction) {
        await interaction.reply("Pong!")
    }
}

错误是:


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

TypeError: Cannot read properties of undefined (reading 'get')
    at Client.<anonymous> (C:\vs\Adele music bot\index.js:52:42)
    at Client.emit (node:events:520:28)

一切都很好,它注册了斜杠命令,但是当我使用 /ping 时,它就显示上面的错误。

您似乎从不同地方复制粘贴了代码,只是希望它能起作用。错误意味着 interaction.commands 是未定义的,它是。

据我所知,您想要一个包含所有交互命令的 Discord.Collection。为此,我们将使用 client.commands.

代码示例

/* Create the collection */
client.commands = new Discord.Collection()

const commands = []
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

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

    /* Add data to the collection */
    client.commands.set(command.name, command);
}

...

/* Get the command */
const command = client.commands.get(interaction.commandName); 
const {Collection} = require('discord.js');

从 discord 包中导入集合。

然后在创建客户端后

   client.commands = new Collection();

使用上面的代码片段

然后

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

在错误发生的地方写下这一行。

基本上你首先需要为客户端创建一个新的命令集合。 然后您需要添加数据以将数据添加到集合中,但使用以下命令。

client.commands.set();

然后只有你可以使用 get 命令

client.commands.set();