admin管理员组文章数量:1391977
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. ...
2 Answers
Reset to default 4message.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 :)
本文标签: javascriptGet last message from text channel with discordjsStack Overflow
版权声明:本文标题:javascript - Get last message from text channel with discord.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744743308a2622739.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论