You need to enable JavaScript to run this app. 如何同时运行多个Discord客户端 解决discord.py多Bot同时启动问题
优惠活动
大模型
产品
解决方案
定价
更多

如何同时运行多个Discord客户端 解决discord.py多Bot同时启动问题

解决方案

核心问题排查

你原有代码存在两个导致无法运行的核心错误:

  • discord.Client被定义为Bot类的类属性,所有Bot实例会共享同一个Client实例,会出现事件注册冲突、token覆盖等问题,必须改为每个实例独立持有自己的Client对象。
  • discord.Client.run()是同步阻塞方法,内部会自行接管asyncio事件循环的启动、运行、销毁逻辑,直接在异步任务中调用会完全阻塞整个事件循环,要自行管理事件循环必须使用异步启动方法Client.start()。

修正后可运行代码

import discord
import asyncio

# 建议显式声明需要的intents,新版discord API强制要求
intents = discord.Intents.default()
intents.message_content = True # 如果需要读取消息内容必须开启

class Bot:
    def __init__(self, token):
        self.token = token
        # 每个实例持有独立的Client
        self.client = discord.Client(intents=intents)

        print('Bot initiated')

        @self.client.event
        async def on_ready():
            print(f'Logged in as {self.client.user}')
        
        @self.client.event
        async def on_message(message):
            # 避免响应自己的消息
            if message.author == self.client.user:
                return
            print(f"来自{self.client.user}的接收消息:{message.content}")
        
    async def run(self):
        print('Bot running')
        # 调用异步启动方法,不要用run()
        await self.client.start(self.token)

async def main():
    # 替换为你实际的Bot token
    bot1 = Bot('bot1 token here')
    bot2 = Bot('bot2 token here')
    
    # 同时运行所有Bot的启动任务
    await asyncio.gather(
        bot1.run(),
        bot2.run()
    )

if __name__ == '__main__':
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        # 收到终止信号时优雅关闭
        pass

适配你现有架构的说明

如果你的Bot都是继承自抽象Bot类实现的,只需要做两处调整即可适配:

  1. 把抽象基类中定义的run方法改为异步方法
  2. 所有子类统一使用await self.client.start(token)替代原来的self.client.run(token)调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 15:27:01