You need to enable JavaScript to run this app. Discord.py遍历role.members时如何获取多职位成员且不中断循环
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py遍历role.members时如何获取多职位成员且不中断循环

Discord机器人roster命令修复方案

问题根因

  • 变量名不匹配:你初始化Embed实例时使用的变量是em,但在遍历成员添加字段时调用的是不存在的embed对象,这会直接触发NameError异常,导致循环强制中断。
  • 缺少管理身份组判断逻辑:你定义了三个管理身份组变量但没有在遍历中做归属判断,无法实现特殊职位用户的标记需求。
  • 原有代码存在两处逻辑遗漏:set_author()为空调用会触发参数异常,生成完Embed后没有执行发送操作。

修复后代码

@commands.Command()
async def roster(ctx, role: discord.Role=None):
    # 入参非空校验
    if not role:
        await ctx.send("请指定需要查询的队伍身份组")
        return
    em = discord.Embed(title=f"{role.name} 的当前队伍名单:", color=role.color)
    # 补全set_author必填参数
    em.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar.url)
    # 获取三个管理身份组
    fo = discord.utils.get(ctx.guild.roles, id=846618354478481409)
    gm = discord.utils.get(ctx.guild.roles, id=846618640957833259)
    hc = discord.utils.get(ctx.guild.roles, id=846618777213730837)
    
    # 遍历队伍成员
    for member in role.members:
        # 匹配成员持有的特殊身份组
        role_tags = []
        if fo in member.roles:
            role_tags.append("*Franchise Owner*")
        if gm in member.roles:
            role_tags.append("*General Manager*")
        if hc in member.roles:
            role_tags.append("*Head Coach*")
        # 拼接显示内容
        tag_str = f"({'/'.join(role_tags)})" if role_tags else ""
        em.add_field(name="\u200b",
                    value=f"{member.mention}{tag_str}\n"
                    f"`{member.name}#{member.discriminator}`"
        )
    # 发送生成好的Embed
    await ctx.send(embed=em)

内容的提问来源于stack exchange,提问作者augustincampagna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 08:54:01