首页 > 解决方案 > 查找最活跃的用户(每天)

问题描述

我正在尝试向我的不和谐机器人添加一个命令,以查找当天最活跃的用户。我可以保存聊天记录并通过它们进行搜索,但我很确定有一种更简单的方法。

标签: javascriptdiscord.js

解决方案


假设每条消息都被缓存,您可以使用Collection.prototype.reduce()

const object = guild.members.cache.reduce(
  (acc, member) => (
    // add up the sum of messages sent in each channel by this member and add it to the object
    (acc[member.id] = guild.channels.cache.reduce((acc, channel) =>
      // filter only messages sent by the current member
      acc + channel.messages.cache.filter(
       (message) =>
        message.author === member &&
        // make sure the message was sent within the last day
        message.createdTimestamp > new Date(new Date().getDate() - 1)
      ).size, 0
    )),
    acc
  ),
  {}
);

// sort the object and return the ID of the most active member
const mostActive = Object.entries(object).sort(([, a], [, b]) => b - a)[0][0]

推荐阅读