Search code examples
javascriptnode.jsdiscorddiscord.js

How do I Get the Client User's Last Message?


How would you get the object for the a bot's last message? I tried doing something like:

if (message.content.split(' ')[0] === 'test') {
   message.channel.sendMessage('Test')
   console.log(client.user.lastMessage.content)
}

If I trigger the conditional, the console gives me an error: TypeError: Cannot read property 'content' of undefined


Solution

  • The reason the value of client.user.lastmessage is null is because you are just starting the bot, and it hasn't sent any messages before you are running your 'test' command.

    To circumnavigate this, I'd check if it's null (in case it isn't) and in the off-chance that it is, use a MessageCollector and wait for your message to be sent.

        if (client.user.lastMessage == null) {
            // Set the collector for the same channel
            // Ensure the id is the same
            var myID = client.user.id;
            // Create collector and wait for 5 seconds (overkill but you never know with bad internet/lots of traffic)
            const collector = new Discord.MessageCollector(msg.channel, m => m.author.id === myID, { time: 5000 });
            collector.on('collect', message => {
                console.log(message.content);
                collector.stop("Got my message");
            });
        } else {
            console.log(client.user.lastMessage.content);
        }
    

    Exact code Block I tested with:

        client.on('message', msg => {
            if (msg.content === '$ping') {
                msg.reply("Pong!")
                if (client.user.lastMessage == null) {
                    const collector = new Discord.MessageCollector(msg.channel, m => m.author.id === client.user.id, { time: 10000 });
                    collector.on('collect', message => {
                        console.log(message.content);
                        collector.stop("Got my message");
                    })
                } else {
                    console.log(client.user.lastMessage.content);
                }
            }
        }