Get last message sent to channel
Recently I believe they've changed from channel.fetchMessages()
to channel.messages.fetch()
channel.messages.fetch({ limit: 1 }).then(messages => {
let lastMessage = messages.first();
// do what you need with lastMessage below
})
.catch(console.error);
If you already have the specific channel stored in a variable, it's quite easy. You can call the MessageManager#fetch()
method on that specific channel and get the latest message.
Example:
let channel // <-- your pre-filled channel variable
channel.messages.fetch({ limit: 1 }).then(messages => {
let lastMessage = messages.first();
if (!lastMessage.author.bot) {
// The author of the last message wasn't a bot
}
})
.catch(console.error);
However if you don't have the complete channel object saved in a variable but only the channel ID, you'll need to fetch the correct channel first by doing:
let channel = bot.channels.get("ID of the channel here");