You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py机器人unban命令报错:async_generator无法用于await表达式

修复discord.py Unban命令的错误

错误原因

ctx.guild.bans() 返回的是异步生成器(AsyncGenerator),不能直接用 await 关键字获取结果,这是触发TypeError的核心原因。同时原代码的循环逻辑存在问题:判断语句在循环外部,只会检查最后一个封禁用户,无法正确匹配目标用户。

修复后的代码

@client.command()
@commands.has_permissions(ban_members=True)
async def unban(ctx, *, member):
    # 处理用户输入格式
    try:
        member_name, member_discriminator = member.split('#')
    except ValueError:
        await ctx.send("格式错误,请输入 `用户名#四位数字` 格式的内容")
        return

    # 异步遍历所有封禁记录
    async for ban_entry in ctx.guild.bans():
        user = ban_entry.user
        if (user.name, user.discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(f'**Unbanned** {user.mention}')
            return
    
    # 未找到目标用户时的提示
    await ctx.send("未找到该封禁用户")

关键修复点

  • 替换错误的await ctx.guild.bans()为async for循环,直接遍历异步生成器,这是discord.py中处理异步迭代内容的标准方式。
  • 将用户匹配逻辑移入循环内部,确保每一条封禁记录都会被检查,避免遗漏目标用户。
  • 增加输入格式校验,防止用户输入不符合要求的内容导致命令崩溃。
  • 添加未找到用户的反馈,提升命令的使用体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:42:23