Reputation: 645
I feel like all my research on this topic lead me only to outdated solutions.
With my Discord.js bot, I have a command. For it to work I need to get the last message in a channel right before the command. I am struggling with all those fetches and partials and cache etc.
Sometimes it works when I post the message right after my bot started and use the command on it, but if I restart my bot it seems to get the wrong message. Also, what about messages that are older than 14 days?
I can't really provide code because it's just one line, like:
const message = msg.channel.messages. ...
Upvotes: 1
Views: 7185
Reputation: 23189
message.channel.messages
returns a manager of the messages sent to this channel. To get the last one, you can use its fetch()
method with the query option {limit: 1}
. It means, you can fetch the last message in a channel using message.channel.messages.fetch({ limit: 1 })
. However, if you run this fetch after you sent a command, the last message will be the one with that command.
To solve this, you can fetch the last two messages in the channel by increasing the limit: message.channel.messages.fetch({ limit: 2 })
. The fetched collection will contain the command (you used to fetch the last message) and the message right before that.
Discord collections have a .last()
method that obtains the last value, so you can now grab the last message by using this:
const messages = await message.channel.messages.fetch({ limit: 2 });
const lastMessage = messages.last();
console.log(lastMessage.content);
PS.: It has no problem with fetching messages older than 14 days.
Upvotes: 4
Reputation: 195
You might want to check out this and use messages#fetch to fetch non-cached messages!
Hope this helps :)
Upvotes: 1