首页 > 解决方案 > 获取用户在频道中提及的次数

问题描述

我正在尝试计算用户在频道中被提及的次数。我的代码是:

message.channel.messages.fetch()
    .then(messages => console.log(`${messages.filter(m => m.mentions.users[1] === 'msg.author').size} messages`))
    .catch(console.error);

当我在一个频道中运行此程序时,我在该频道的历史记录中有 27 次提及。这回来了0 messages

我该如何做到这一点?

标签: discord.js

解决方案


错误在于您的过滤器,

m.mentions.users是由用户 id 映射的集合,当您执行 [1] 时,它会检查 id 为 1 的用户,然后将其检查到字符串msg.author

message.channel.messages.fetch()
 .then(messages => {
   //.has() checks if the collection includes the key
   const size = messages.filter(m => m.mentions.users.has(message.author.id)).size;
   console.log(size, "messages");
});
 .catch(console.error);

推荐阅读