繁体   English   中英

如何检查用户是否在不和谐中具有特定角色

[英]how do I check if a user has a specific role in discord

这应该检查特定的人是否有或没有静音角色

    @bot.command(pass_context=True)
    @commands.has_role("Admin")
    async def unmute(ctx, user: discord.Member):
        role = discord.utils.find(lambda r: r.name == 'Member', 
    ctx.message.server.roles)
        if user.has_role(role):
            await bot.say("{} is not muted".format(user))
        else:
            await bot.add_roles(user, role)

抛出这个错误

命令引发异常:AttributeError: 'Member' object has no attribute 'has_role'

我不知道该怎么做所以我真的很感激我能得到的每一个帮助

成员没有.has_role()方法,但是您可以使用.roles获取他们所有角色的列表。

要查看用户是否具有给定的角色,我们可以role in user.roles使用role in user.roles

    @bot.command(pass_context=True)
    @commands.has_role("Admin")
    async def unmute(ctx, user: discord.Member):
        role = discord.utils.find(lambda r: r.name == 'Member', ctx.message.guild.roles)
        if role in user.roles:
            await bot.say("{} is not muted".format(user))
        else:
            await bot.add_roles(user, role)

参考文档: https : //discordpy.readthedocs.io/en/latest/api.html#member

注意: ctx.message.guild.roles以前是ctx.message.server.roles 由于 API 更改而更新。

如果有人在重写后看到这个,语法已经改变了一点,这是更新的代码。

要查看成员是否具有指定的角色,我们可以role in member.roles使用role in member.roles

@bot.command()
@commands.has_role("Admin")
async def unmute(ctx, member: discord.Member):
    role = discord.utils.get(ctx.guild.roles, name="Member")
    if role in member.roles:
        await ctx.send(f"{member} is not muted")
    else:
        await member.add_roles(role)

文档供参考:

成员:discord.Member: https ://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#converters

has_role:

https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role

用户角色: https ://discordpy.readthedocs.io/en/latest/api.html#discord.Member.roles

member.add_roles: https ://discordpy.readthedocs.io/en/latest/api.html#discord.Member.add_roles

我个人使用这个:

@bot.command(pass_context=True)
@commands.has_role("Admin")
async def unmute (ctx,user:discord.Member):
  role = discord.utils.get(ctx.guild.roles, name="Muted")

  if role in user.roles:
    await user.remove_roles(role)

    await user.add_roles(role)
    embed = discord.Embed(title="Unmuute Members", description=f"{user.mention} has been unmuted" , color = discord.Color.blue())


    embed.add_field(name='Unmuted by:' , value = f"{ctx.author.mention}")


    await user.remove_roles(role)

    await ctx.send(embed=embed)

  else:
    await ctx.send("Invalid Argumnets or The user is not muted.")

所以如你所见

role = discord.utils.get(ctx.guild.roles, name="Muted")这个变量在服务器中定位Muted角色

if role in user.roles:
    await user.remove_roles(role)

这将从用户中删除角色

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM