You need to enable JavaScript to run this app. 精简Discord.py Bot代码时触发协程未await告警,排查缺失的关键实现环节
优惠活动
大模型
产品
解决方案
定价
更多

精简Discord.py Bot代码时触发协程未await告警,排查缺失的关键实现环节

问题成因与修复方法
  • 出现该告警的核心原因是异步调用链路出现了断点,没有按Python asyncio的规则完成协程创建->等待执行->返回结果的全流程调度,具体有两个关键遗漏:
    1. 外层公共函数logi_member_role_update是普通同步函数,不具备异步执行能力
      你在这个同步函数内部嵌套了异步函数logi_role_by,但同步函数本身无法驱动协程运行:哪怕你在同步函数里写了return logi_role_by(),最终返回给调用端的也只是一个创建完成但没有被调度的裸协程对象,根本不会执行内部遍历审计日志的逻辑。
    2. 全链路缺失await关键字
      Python 3.6中asyncio会自动追踪所有创建的协程,一旦协程在被垃圾回收时还没有被await调用,就会抛出对应RuntimeWarning,和你遇到的控制台输出、discord.client模块的告警逻辑完全匹配。异步函数从定义到调用的全流程,只要涉及协程传递,都必须通过await把执行权交回事件循环:从内层嵌套的logi_role_by,到外层的logi_member_role_update,再到事件回调on_member_update里的调用动作,只要有一个环节漏了await,就会导致协程被创建后直接丢弃,最终控制台直接打印出未被await的协程对象内存地址。

具体改造步骤

  • 给外层的公共封装函数logi_member_role_update加上async前缀,将其改造为异步函数
  • 在logi_member_role_update内部调用logi_role_by时,添加await关键字,等待审计日志遍历逻辑执行完成,拿到操作人ID后再向外返回
  • 在on_member_update事件回调里检测到角色变更、调用logi_member_role_update时,同样添加await关键字,等待整个公共逻辑执行完成后,再执行后续的打印操作

错误写法与修正对比

错误实现(简化还原):

def logi_member_role_update(guild, member):
    async def logi_role_by():
        async for log_entry in guild.audit_logs(action=discord.AuditLogAction.member_role_update):
            return log_entry.user.id
    # 同步函数返回裸协程,没有实际执行
    return logi_role_by()

@client.event
async def on_member_update(before, after):
    if before.roles == after.roles:
        return
    # 直接拿到裸协程,没有await,打印出协程地址
    print(logi_member_role_update(after.guild, after))

修正后的实现:

async def logi_member_role_update(guild, member):
    async def logi_role_by():
        async for log_entry in guild.audit_logs(action=discord.AuditLogAction.member_role_update):
            return log_entry.user.id
    # 内部调用协程添加await
    return await logi_role_by()

@client.event
async def on_member_update(before, after):
    if before.roles == after.roles:
        return
    # 外部调用异步函数添加await,拿到实际返回的操作人ID
    operator_id = await logi_member_role_update(after.guild, after)
    print(operator_id)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 14:06:04