最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get last message from text channel with discord.js - Stack Overflow

programmeradmin0浏览0评论

I feel like all my research on this topic lead me only to outdated solutions.

With my Discord.js bot, I have a mand. For it to work I need to get the last message in a channel right before the mand. 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 mand 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. ...

I feel like all my research on this topic lead me only to outdated solutions.

With my Discord.js bot, I have a mand. For it to work I need to get the last message in a channel right before the mand. 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 mand 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. ...

Share Improve this question edited Jan 30, 2021 at 13:01 Zsolt Meszaros 23.2k19 gold badges58 silver badges69 bronze badges asked Jan 30, 2021 at 12:43 pragmatrickpragmatrick 6452 gold badges11 silver badges25 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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 mand, the last message will be the one with that mand.

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 mand (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 :)

发布评论

评论列表(0)

  1. 暂无评论