【问题标题】:How can I get the name of a role with the role's ID in Discord.py?如何在 Discord.py 中获取具有角色 ID 的角色名称?
【发布时间】:2022-01-15 16:50:30
【问题描述】:

所以,我正在创建一个命令,允许我的服务器中的用户创建仅审美角色,并且我已经有一个命令来创建它们(他们只能指定颜色和名称)并添加/删除它们.但是,我仍然想添加一个功能,如果在创建时已经存在同名角色,它会搜索服务器中的所有角色。我从另一个问题中找到了这段代码来列出服务器中的所有角色(老实说,我不太明白那一行发生了什么,但它有效):

rolelist = (", ".join([str(r.id) for r in ctx.guild.roles]))

不幸的是,这段代码只返回角色的 ID,我找不到将 ID 转换为角色名称的方法,以便我可以实际使用它来检查创建的角色是否已经存在。我尝试将“.name”添加到“ctx.guild.roles”的末尾,但这不起作用并返回此错误:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'name'

总而言之,我需要一种方法来放入从前面提到的“rolelist”变量中提取的整数字符串,并将它们转换为角色的名称。任何帮助都非常感谢,我提前感谢您。

【问题讨论】:

    标签: discord discord.py


    【解决方案1】:

    您可以使用discord.utils.get() 函数。如果未找到具有指定属性的对象,则返回 None

    请看下面的例子:

    @bot.command()
    async def check_role(ctx, *, name: str):
        await ctx.send("Role with specified name found." if discord.utils.get(ctx.guild.roles, name=name) is None else "Role with specified name not found.")
    

    如果您知道角色 ID,您可以执行以下操作:

    role_id = 12345
    role = guild.get_role(role_id)  # get the role
    print(role.name)  # print role name
    

    【讨论】:

      猜你喜欢
      • 2019-07-11
      • 2020-10-30
      • 2021-05-27
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 2021-11-02
      • 2021-10-16
      • 2015-01-21
      相关资源
      最近更新 更多