首页 > 解决方案 > Discord.py:如何查看成员是否具有在使用 cmd 时必须 ping 自己的角色

问题描述

我试过的代码:确实运行了,但它总是说你没有烫发,即使我确实有这个角色。

@client.command(pass_context=True, aliases = ['4v4 ping'])
async def ping4v4(author):
    channel = client.get_channel(870969338679660591)
    guild = client.get_guild(870969337945669722)
    role = guild.get_role(870969337958240260)
    if author in role.members:
        await channel.send(f" 4v4 ping hehe ")
    else:
        await channel.send(f" You don't have perms! ")

还有其他方法可以查看成员是否具有角色或角色是否具有成员?

标签: pythondiscorddiscord.py

解决方案


正如已经提到的,您应该始终添加ctx为“参数”,这实际上是标准的,并且可以让您在这里更轻松地完成许多事情。您不需要author作为参数并且可以缩短代码。

通过以下方式查询公会/角色非常简单ctx.guild.get_role- 在这里检查角色是否在执行命令的服务器上可用。

要检查消息的作者是否具有此角色,我们必须反过来检查,而不是检查是否author在 中role,松散翻译。所以这个片段将被修改如下:if role in ctx.author.roles:

修改后的代码:

@client.command(pass_context=True, aliases = ['4v4 ping'])
async def ping4v4(ctx): # Only ctx as an "argument"
    channel = client.get_channel(ChannelID)
    role = ctx.guild.get_role(RoleID) # Get the guild via ctx.guild
    if role in ctx.author.roles: # Check if the ctx.author has the role
        await channel.send("4v4 ping hehe") # No f-strings needed
    else:
        await channel.send("You don't have perms!")

推荐阅读