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

Discord机器人抛出RuntimeError:asyncio.run()无法在运行事件循环中调用

解决Discord机器人RuntimeError问题

核心排查方向与修复

  • 禁止重复调用run()方法
    client.run()或bot.run()会启动并阻塞Discord机器人的事件循环,同一脚本中多次调用必然触发RuntimeError。检查代码分支、函数调用,确保只执行一次run()。

  • 同步IO操作阻塞事件循环
    获取MC服务器IP的逻辑如果是同步阻塞(比如用requests库的同步请求),会打断discord.py的异步事件循环,引发错误。两种修复方式:

    1. 改用异步HTTP库(如aiohttp):
      import aiohttp
      
      async def get_mc_public_ip():
          async with aiohttp.ClientSession() as session:
              async with session.get("https://api.ipify.org") as resp:
                  return await resp.text()
      
    2. 用asyncio.to_thread()包装同步代码:
      import asyncio
      import requests
      
      async def get_mc_public_ip():
          return await asyncio.to_thread(requests.get, "https://api.ipify.org").text
      
  • run()后不要执行客户端操作
    run()是阻塞函数,机器人运行期间不会执行其后的代码;如果强行在run()后调用客户端方法(如发送消息),会触发循环已关闭的RuntimeError。所有Discord交互逻辑必须放在事件回调(如on_ready)或命令函数中:

    @client.event
    async def on_ready():
        mc_ip = await get_mc_public_ip()
        target_channel = client.get_channel(1234567890)  # 替换为你的频道ID
        await target_channel.send(f"当前MC服务器公网IP:{mc_ip}")
        print("机器人已完成IP推送")
    
  • 避免手动管理事件循环
    不要在代码中使用asyncio.run()手动创建循环,discord.py会自动处理事件循环。如果存在asyncio.run()与client.run()混用的情况,删除手动循环代码。

额外检查项

  • 确认Discord机器人TOKEN正确,且机器人已被邀请到目标服务器并拥有发送消息的权限。
  • 更新discord.py到最新稳定版,避免版本兼容问题:
    pip install --upgrade discord.py
    

如果问题仍存在,请提供完整代码及RuntimeError的详细报错信息,以便进一步定位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:01:01