I'm trying to fetch the last 2 messages someone sent but I couldn't find how. I tried:
console.log(user.lastMessage) // to get the last one since i was desperate, i also tried lastMessageId
and
message.channel.messages.fetch({ author: message.author}).then(async (messages) => {
console.log(messages.first(2)[1].content)
})
The first method would return undefined. The second method also returned messages from other users.
This is for my ranking system, I want to add a 15 seconds cooldown between each messages added to the database.
By using message.channel.messages.fetch() you are getting a Collection with all the messages in the channel up to a certain point. But the thing is that, the Collection is in reverse which means that the newest messages are in the first while the older ones are at the end. So you just have to perform a .find() function to see the first message where the author was a specific person. An example would look like this =>
const messages = await message.channel.messages.fetch()
const userLastMessage = messages.find(msg => msg.author.id === message.author.id)
Fetching is absolutely not the way to do what you want to do, since you would fetch messages every single time someone sends a message. On top of that, there is actually no way to fetch messages from only one member (not user, users aren't members). The question then is: what happens if someone did not send a message in past 100 messages? Do you fetch another 100? What if they didn't speak in this channel yet or even never sent a message in the server before?
The correct way to do this is to store a timestamp of when someone sent a message, and when they send another message, compare it to your stored value to check if enough time has passed since the previous message.