I already know how to grab the last message sent. However, it keeps grabbing the message sent to execute the command. For example, if initiating the comment is by writing in the channel !test then the last message sent would be !test. I need the actual last message sent, which is the one before it.
Code:
let last = "";
let lastMessage = await message.channel.messages.fetch({ limit: 2 });
lastMessage.each((msg) => {
last = msg.content;
})
I've tried setting the limit to 2 in hopes that it would grab both the command sent to initiate the function and the previous message sent itself. However, I do not know how to differentiate between the two to grab the actual previous message as msg.content just returns the command !test.
If you use the limit option to fetch the last two messages in a channel, it returns a collection. These messages are sorted in descending order, based on the date they were posted. It means, the first item in the returned collection is the last message sent (the one with the command), the second item is the second last message (the last one before the command).
Collections have methods like first() and last() that return the first and last items respectively.
let lastMessages = await message.channel.messages.fetch({ limit: 2 });
// this is the last message sent before this command
let previousMessage = lastMessages.last();
message.reply(`The last message was _"${previousMessage.content}"_`);
message.reply(
`Is the first fetched message (i.e. \`lastMessages.first()\`) the same as this message?\n ${
message.id === lastMessages.first().id ? '✅ yes' : '❌ no'
}`,
);