来自不和谐角色的在线用户计数



我希望我的 Discord 机器人将角色的在线用户数显示为活动。
我似乎想不通,在网上也找不到任何东西。
有人可以给我示例代码或向我解释吗?

你可以使用Guild.members.forEach()遍历公会的每个成员,然后如果他们有这个角色(你可以使用GuildMember.roles.has(Role.id)来检查),增加一个计数器。完成成员循环后,使用Client.user.setActivity()中的计数器。
这就是你需要的,以便得到你想要的。

试试这些东西,如果你在MCVE后仍然有问题,我们会帮助你,但首先你需要自己尝试。

您也可以使用filter

// Discord.js v12/v13 (latest version):
const count = guild.members.cache.filter(m =>
// If the member has the role
m.roles.cache.has('role id') &&
// and the member is online
m.presence.status === 'online'
).size
// Discord.js v11:
const count = guild.members.filter(m =>
// If the member has the role
m.roles.has('role id') &&
// and the member is online
m.presence.status === 'online'
).size
// Use count here:
client.user.setActivity('...')

要通过公会的ID获取公会,请使用以下命令:

// v12/v13
const guild = client.guilds.cache.get('id')
// v11
const guild = client.guilds.get('id')

最新更新