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

如何在使用bot.run()运行Discord机器人时处理网络连接错误?

解决discord.ext.commands机器人网络断开后自动重启的问题

commands.Bot.run()内部封装了事件循环的启动与关闭逻辑,一旦因网络错误退出,事件循环会被直接关闭,无法直接放入循环重复调用。要实现自动重连,推荐使用bot.start()替代bot.run(),自己控制异步循环和异常处理:

实现代码

import asyncio
from discord.ext import commands
from discord import ConnectionClosed

token = "my_token"

def create_bot_instance():
    intents = discord.Intents.default()
    intents.message_content = True
    return commands.Bot(command_prefix='%', intents=intents)

async def run_bot():
    while True:
        bot = create_bot_instance()
        try:
            # 使用start()而非run(),避免内部关闭事件循环
            await bot.start(token)
        except ConnectionClosed as e:
            print(f"连接异常关闭 - 代码: {e.code}, 原因: {e.reason}")
        except Exception as e:
            print(f"机器人运行出错: {str(e)}")
        finally:
            # 确保关闭bot的所有连接资源
            await bot.close()
            print("等待5秒后尝试重新连接...")
            await asyncio.sleep(5)

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

关键说明

  • bot.start()是异步协程方法,不会像bot.run()那样在退出时关闭事件循环,因此可以在while循环中重复调用
  • 每次重连都创建新的Bot实例,避免旧实例残留的连接状态导致异常
  • 捕获ConnectionClosed可以针对性处理网络断开的情况,同时保留通用异常捕获覆盖其他错误
  • 重试前添加等待时间,避免短时间内频繁重试导致被平台限制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:22:05