Memeloren
Memeloren

Reputation: 29

Discord.js - Cannot read property of undefined inside execute() method

I'm making a simple snipe command which views last deleted messages. The problem is I receive the following error when the command is used:

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

Command's code:

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

The message deleted event is in my main bot's file like this:

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

I pass "message" using:

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!');
    }
});

And "client" is:

const client = new Discord.Client();

Upvotes: 1

Views: 286

Answers (1)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23161

Make sure, the order of the arguments is the same in both files. If you pass them like command.execute(message, args, client), the method should use the same order: 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) {
        ...
    }
}

Upvotes: 1

Related Questions