代码返回所有成员,而不是角色中的成员 [英] Code returns all members and not the members in the role

查看:31
本文介绍了代码返回所有成员,而不是角色中的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

let getMembers = message.guild.members.cache.filter(member => {
    return message.guild.roles.fetch('701142571623252018');
}).map(member => {
    return member.user.username;
});

它返回服务器中的所有成员,但不返回应该执行的特定角色中的成员.

It returns all members in the server, but not the members in the specific role, which it is supposed to do.

这是我的完整代码:

    const targetRole = message.guild.roles.cache.get('701142571623252018');
    if (!targetRole) return console.log('No role found')
    const members = message.guild.members.cache.filter((member) => !member.roles.cache.some((role) => role.id === targetRole.id)).map(m => m.user.username)

    const players = new Discord.MessageEmbed()
      .setColor('#6B238E')
      .setTitle("Players:")
      .setDescription(members);

    message.channel.send(players);
    //console.log(members);

推荐答案

这是因为您的筛选器函数没有返回该成员是否具有该角色:它返回的Promise应该分解为Role,这被解释为 true ,因此所有内容均通过了过滤器.

That's because your filter function is not returning whether the member has the role or not: it's returning a Promise which should resolve into a Role, which is interpreted as true and so everything passes the filter.

您实际上不需要获取角色,因为您只需要检查该ID是否是该成员的角色之一:为此,您可以使用

You don't actually need to fetch the role, since you only need to check if that ID is one of the roles from of the member: to do that you can use GuildMember.roles.cache.has(), which will return whether the roles collection has a role with that ID.

这是您的操作方式:

message.guild.members.cache.filter(member => member.roles.cache.has('701142571623252018'))
  .map(member => member.user.username)

这篇关于代码返回所有成员,而不是角色中的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆