提问者:小点点

discord.js“TypeError:无法读取未定义的属性'execute'”


所以,我试图用discord.js创建一个bot,但遇到了一个我不知道如何解决的错误,我已经找了几个小时也找不到答案,当我运行bot时,它成功地登录了,但是当你运行一个命令时,powershell控制台抛出一个错误“typeerror:不能读取undefined的property'execute'”

这是我的主要代码

const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
const { prefix, token } = require('./config.json');
const ms = require('ms');
const fs = require('fs');

client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

client.once('ready', async () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const commandName = args.shift().toLowerCase();

    const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

    try {
        command.execute(message, args);
    } catch (error) {
        console.error(error);
        message.reply('This command has an issue.')
    }
    // other commands...
});

client.login(token);

这是一个command.js文件,该命令旨在清除500-2范围内的x ammount消息

module.exports = {
    name: "purge",
    description: "Deletes input amout of messages.",
    async execute(message, args) {
        if (message.member.hasPermission(MANAGE_MESSAGES)) {
            const deleteCount = parseInt(args[0], 10);
            const deleteMessage = `Deleted ${deleteCount} messages.`;

            if (!deleteCount || deleteCount > 500 || deleteCount < 2) return message.reply(`${message.author} please input a number between 2 - 500.`);

            const fetched = await message.channel.fetchMessages({
                limit: deleteCount
            });
            
            message.channel.bulkDelete(fetched)
                .catch(err => console.log(`Cannot delete message because of ${err}`))
                .then(message.reply(deleteMessage))
                .catch(err => {
                    console.log(err);
                })
        } else {
            message.reply('You do not have permissions to purge.')
        }
    }

}

错误消息为:

TypeError: Cannot read property 'execute' of undefined
    at Client.<anonymous> (C:\Users\ryssu\source\repos\SCP\079\app.js:24:11)
    at Client.emit (events.js:315:20)
    at MessageCreateAction.handle (C:\Users\ryssu\source\repos\SCP\079\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\ryssu\source\repos\SCP\079\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.j
s:4:32)
    at WebSocketManager.handlePacket (C:\Users\ryssu\source\repos\SCP\079\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (C:\Users\ryssu\source\repos\SCP\079\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (C:\Users\ryssu\source\repos\SCP\079\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (C:\Users\ryssu\source\repos\SCP\079\node_modules\ws\lib\event-target.js:125:16)
    at WebSocket.emit (events.js:315:20)
    at Receiver.receiverOnMessage (C:\Users\ryssu\source\repos\SCP\079\node_modules\ws\lib\websocket.js:797:20)

如果有人能帮我的话我会非常感激的。


共1个答案

匿名用户

实际上,您并没有在commands集合中设置任何命令,因此任何获取命令的尝试都将返回未定义的命令。

// create the collection
client.commands = new Discord.Collection();

// get an array of every file in the commands folder
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

// iterate a function through every file
for (file of commandFiles) {
 const command = require(`./commands/${file}`);
 
 // map the command to the collection with the key as the command name, 
 // and the value as the whole exported object
 client.commands.set(command.name, command);
};