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

Python使用asyncio.gather同时运行WebSocket与Discord Bot报错求解

错误原因

  • startWebSocketServer 函数内部手动调用了 asyncio.get_event_loop().run_forever(),会直接阻塞当前事件循环,导致gather无法调度其他异步任务
  • Discord Bot 的 bot.run() 是同步阻塞方法,内部会自行启动、管理甚至关闭事件循环,和外层 asyncio.run() 启动的事件循环产生冲突
  • main 函数里的 asyncio.gather() 没有加 await,任务还没调度就会直接向下执行,程序提前退出

修复方案

不需要改用多线程,调整异步写法即可让两个服务在同一个事件逻辑中正常运行,修改后代码如下:

修复后的WebSocket服务代码

import asyncio
import websockets

async def startWebSocketServer(ip= "localhost", port=5000):
    async def send(websocket, path):
        async for message in websocket:
            await websocket.send(message)     
    # 异步等待服务初始化完成,不手动操作事件循环
    await websockets.serve(send, ip, port) 
    print(f"Running websocket server at ip: {ip} and port: {port}")
    # 永久阻塞保持服务运行
    await asyncio.Future()

修复后的Discord Bot代码

async def runBot():
    loadExtentions()
    # 换用异步启动方法,避免内部自行管理事件循环
    await bot.start(TOKEN)

修复后的主入口代码

async def main():
    # 加await等待两个服务调度执行
    await asyncio.gather(startWebSocketServer(), runBot())
    print("Online!")

if __name__ == "__main__":
    asyncio.run(main())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:54:03