Discord.js - 无法读取 execute() 方法中未定义的属性

时间:2021-01-15 16:49:03

标签: javascript node.js discord.js

我正在制作一个简单的 snipe 命令,用于查看上次删除的消息。问题是我在使用命令时收到以下错误:

"TypeError: Cannot read property 'get' of undefined"

命令代码:

const Discord = require('discord.js');

module.exports = {
    name: 'snipe',
    description: 'snipes the deleted message/image',
    execute(client, message) {
        const msg = client.snipes.get(message.channel.id)
        if(!msg) return message.channel.send("Didn't find any deleted messages.")
        const embed = new Discord.MessageEmbed()
        .setAuthor(msg.author, msg.member.user.displayAvaterURL())
        .setDescription(msg.content)
        .setTimestamp()
        if(msg.image)embed.setImage(msg.image)
        message.channel.send(embed)
    }
}

消息删除事件在我的主机器人文件中,如下所示:

client.snipes = new Map()
client.on('messageDelete', function(message, channel){
    client.snipes.set(message.channel.id, {
        content: message.content,
        author: message.author.tag,
        image:message.attachments.first() ? message.attachments.first().proxyURL : null
    })
})

我使用以下方法传递“消息”:

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));

    if (!command) return;

    if (command.guildOnly && message.channel.type === 'dm') {
        return message.reply('I can\'t execute that command inside DMs!');
    }

    if (command.args && !args.length) {
        let reply = `${message.author}, wrong usage`;

        if (command.usage) {
            reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
        }

        return message.channel.send(reply);
    }

    try {
        command.execute(message, args, client);
    } catch (error) {
        console.error(error);
        message.reply('there was an error trying to execute that command!');
    }
});

“客户”是:

const client = new Discord.Client();

1 个答案:

答案 0 :(得分:1)

确保两个文件中的参数顺序相同。如果您像 command.execute(message, args, client) 一样传递它们,则该方法应使用相同的顺序:execute(message, args, client) {...

try {
    command.execute(message, args, client);
} catch (error) {
    ...
module.exports = {
    name: 'snipe',
    description: 'snipes the deleted message/image',
    execute(message, args, client) {
        ...
    }
}