Reputation: 126
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
Upvotes: 1
Views: 10569
Reputation: 103
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
You have to implement a custom solution to track this information manually.
Upvotes: 2
Reputation: 6620
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);
}
}
}
Upvotes: 3