简体   繁体   中英

Get last message from text channel with discord.js

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. ...

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.

You might want to check out this and use messages#fetch to fetch non-cached messages!

Hope this helps:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM