Search code examples
javascriptdiscorddiscord.js

Fetch 2 last messages from a specific user discord.js


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.


Solution

  • 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)
    

    To get the second last item in the Collection, you would have to change the code a little bit since the .find() function returns the first one which matches the criteria. So you can change that to the .filter() function. Then you can use .last() and then pass the number '2' into it. This will get you the two last items in the Collection. Then you can just get the second element in the array. An example =>

    const messages = await message.channel.messages.fetch()
    const allMessagesPostedByUser = messages.filter(msg => msg.author.id === message.author.id)
    const lastTwoMessages = allMessagesPostedByUser.last(2)
    const secondLastMessage = allMessagesPostedByUser.last(2)[1]