Charbel Im
Charbel Im

Reputation: 1

Get second last message with Discord.Js

I'm trying to get the second last message sent in the same channel where it was sent, but when i use .fetchMessages with limit of two messages and try to get the second one, it doesn't work.

I tried with this

channel.fetchMessages({limit:2}).then(res =>{
 let lm = res[1]
 console.log(lm)
})

But it doesn't works

Upvotes: 0

Views: 1913

Answers (2)

Purukitto
Purukitto

Reputation: 307

In v12, channel.fetchMessages does not work anymore instead it's channel.messages.fetch

^ Reference

So updating tintin9999's answer the two solutions will be:

1. Using .last()

channel.messages.fetch({limit: 2}).then(res => {
let lm = res.last()
console.log(lm)
})

2. Using .array()

channel.messages.fetch({limit: 2}).then(res => {
 let lm = res.array()[1]
 console.log(lm)
})

Upvotes: 1

tintin9999
tintin9999

Reputation: 41

channel.fetchMessages() returns a Collection of messages, which is an extended class of Map. They can not be iterated over like res[1], instead you can do one of the two things.

1.Using .last() - ref

This will get you the last element from the collection, which is the 2nd last message.

channel.fetchMessages({limit: 2}).then(res => {
 let lm = res.last()
 console.log(lm)
})

2.Using .array() - ref

This will convert the Collection to an array which can be iterated over.

channel.fetchMessages({limit: 2}).then(res => {
 let lm = res.array()[1]
 console.log(lm)
})

Upvotes: 4

Related Questions