无法为每个服务器discord.py获取自定义管理员角色

2024-10-01 11:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试建立一个“系统”,人们可以在其中更改有权访问管理命令的角色,但是它给我带来了一个错误,我不明白这是怎么可能的

代码:

def get_prefix(client, message):
    with open("prefixes.json", 'r') as f:
        prefixes = json.load(f)
    return prefixes[str(message.guild.id)]


@bot.command(name="changeadminrole", help="Choose the role that can execute admin commands")
async def changeadmin(ctx, role: Role):
    with open("admins.json", 'r') as f:
        admins = json.load(f)

    admins[str(ctx.guild.id)] = role.name

    with open("admins.json", 'w') as f:
        json.dump(admins, f, indent=4)

    await ctx.send(f"Admin role changed to {role.mention}")

然后,要检查人员是否具有所需的角色,我只需执行以下操作:

@bot.command(name="kick", help="Kicks a member from the server")
@commands.has_role(get_adminrole)

即使我有这个角色,它也会让我犯这样的错误:

discord.ext.commands.errors.MissingRole: Role <function get_adminrole at 0x03977220> is required to run this command.

Idk为什么检索(<function get_adminrole at 0x03977220>)而不是admins.json文件中的角色名称:

{
    "506201000374435850": "Absolute Admin"
}

谢谢你的帮助


Tags: namejson角色getas错误withopen
1条回答
网友
1楼 · 发布于 2024-10-01 11:21:17

这是我用来做这件事的全部代码

我刚得到这个角色,你可以继续剩下的代码

@bot.command()
async def changeadmin(ctx, *, role: discord.Role):
    # Code here
    await ctx.send(f"Admin role changed to {role.mention}")

最好保存角色id而不是名称,这样就可以跳过role = ....而只return admins[str(message.guild.id)]

def get_adminrole(message):
    with open("admins.json", 'r') as f:
        admins = json.load(f)
    role = discord.utils.get(message.guild.roles, name=admins[str(message.guild.id)])
    return role.id

下面是一个如何使用kick命令的变通方法

@bot.command()
async def kick(ctx):
    admin_role_id = get_adminrole(ctx)
    if ctx.author not in ctx.guild.get_role(admin_role_id).members:
        await ctx.send("You are not an Admin")
        return

    # code here

相关问题 更多 >