简体   繁体   中英

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

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

You code snippet is obsolete now. From Discord.js v13 and thereafter the following properties have been removed (including lastMessage) because they are not provided by Discord and are not reliable

  • GuildMember# lastMessage
  • GuildMember#lastMessageId
  • GuildMember#lastMessageChannelId

You have to implement a custom solution to track this information manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM