【问题标题】:how do I check if a user has a specific role in discord如何检查用户是否在不和谐中具有特定角色
【发布时间】:2019-02-23 20:27:28
【问题描述】:

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

    @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'

我不知道该怎么做,所以我非常感谢我能得到的每一个帮助

【问题讨论】:

  • @Tristo 从我所理解的链接问题来看,如果询问调用命令的用户是否具有角色,而不是传递给函数的用户。

标签: python python-3.x discord.py


【解决方案1】:

成员没有.has_role() 方法,但是您可以使用.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 更改而更新。

【讨论】:

  • ctx.guild.roles 会更短并且也可以使用
【解决方案2】:

我个人使用这个:

@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")此变量定位服务器中的静音角色

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

这将从用户

中删除角色

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 2010-12-22
    • 2019-06-16
    • 2016-05-02
    • 2018-11-06
    • 2021-10-25
    • 2020-03-14
    相关资源
    最近更新 更多