Online User count from a Discord Role

笑着哭i 提交于 2020-11-29 21:24:35

问题


I want my Discord Bot to display the Number of Online Users of a Role as an Activity.
I can't seem to figure it out and i can't find anything on the Web.
Can someone give me example code or explain it to me?


回答1:


You can use Guild.members.forEach() to loop through every member of the guild, then if they have that role (you can use GuildMember.roles.has(Role.id) to check that) increase a counter. When you have finished your loop through the members, use the counter in your Client.user.setActivity().
That is what you need in order to get what you want.

Try this stuff, if you still have problems post a MCVE and we'll help you, but first you need to try yourself.




回答2:


You can also use filter:

// Discord.js v12 (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('...')

To get a guild by its ID, use this:

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


来源:https://stackoverflow.com/questions/51584028/online-user-count-from-a-discord-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!