You need to enable JavaScript to run this app. Discord机器人接入Google API后@bot.event外指令无响应问题
优惠活动
大模型
产品
解决方案
定价
更多

Discord机器人接入Google API后@bot.event外指令无响应问题

接入Google毒性分析API后Discord Bot全功能异常修复

核心故障原因

  • 同步API调用阻塞事件循环
    代码在async def on_message异步协程里直接运行Google API的同步阻塞方法.execute(),会卡死discord.py的事件循环调度器。事件循环被占满后,所有其他bot功能(命令响应、事件回调、定时任务)都没法获得执行机会,表现为只有当前写的这段消息处理逻辑能跑,其余功能完全无响应。
  • 重写on_message后丢失原有流程
    用commands.Bot创建bot实例时,重写on_message事件必须手动补上await bot.process_commands(msg)调用,否则bot内置的所有命令解析逻辑会被覆盖,完全没法响应常规指令。
  • 无异常捕获导致协程崩溃
    代码没有给Google API请求、权限操作加异常捕获,只要出现网络超时、API限流、鉴权失败、返回格式错误、bot权限不足的情况,on_message协程会直接抛出异常终止,后续消息处理会彻底错乱。
  • 缺失消息来源过滤
    代码没判断消息发送者是不是bot自己,会导致bot发的踢人提示、发言提醒也被on_message捕获,重复调用Google API,甚至形成无限循环的接口请求,被Google侧限流。

修复后可正常运行的代码

import asyncio

@bot.event
async def on_message(msg):
    # 优先过滤bot自身消息,避免API调用死循环
    if msg.author.bot:
        return
    # 恢复原有bot命令的处理流程
    await bot.process_commands(msg)

    try:
        analyze_request = {
            'comment': { 'text': msg.content },
            'requestedAttributes': {'TOXICITY': {}}
        }
        # 把同步API请求扔到线程池跑,不阻塞事件循环
        response = await asyncio.to_thread(
            lambda: service.comments().analyze(body=analyze_request).execute()
        )
        toxicity_value = response['attributeScores']['TOXICITY']['spanScores'][0]['score']['value'] * 100
        print(toxicity_value)

        if toxicity_value > 95:
            await msg.author.kick(reason="Toxic messages")
            await msg.author.send('You were kicked because you sent toxic message(s)')
            await msg.channel.send(f"{msg.author.mention} 因发送有害消息被踢出服务器")
        elif 70 < toxicity_value < 94:
            await msg.channel.send(f"{msg.author.mention} 请注意文明发言")
    except Exception as e:
        # 捕获全流程异常,避免协程崩溃拖垮整个bot
        print(f"消息处理异常: {e}")

额外优化建议

  • 给Google API请求设置超时时间,避免网络异常时长时间占用线程资源
  • 高频服务器场景下可以给消息处理加简单的频率限制,避免短时间内大量请求触发Google侧的调用配额限制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.06 04:54:07