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

Posted

技术标签:

【中文标题】Discord.js - 无法读取 execute() 方法中未定义的属性【英文标题】:Discord.js - Cannot read property of undefined inside execute() method 【发布时间】:2021-04-20 17:22:11 【问题描述】:

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

"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】:

确保两个文件中的参数顺序相同。如果您像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) 
        ...
    

【讨论】:

以上是关于Discord.js - 无法读取 execute() 方法中未定义的属性的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript、Discord.js、Node.js 类型错误:无法读取未定义的属性“执行”

错误:无法读取未定义的属性“执行”

Discord.js 无法执行

Discord.js 的欢迎消息 - “无法读取未定义的属性 'get'”

无法读取未定义的属性“发送”(Discord.js)

Discord.js 无法读取未定义的属性“获取”