如何用discord.py并发运行多个不同令牌的Discord机器人?
如何并发运行多个discord.py机器人
由于bot.run(token)是阻塞方法,无法直接顺序调用实现并发,我们可以利用asyncio结合discord.py提供的异步启动方法bot.start()来解决这个问题。以下是完整的实现示例:
修改后的完整代码
import discord from discord.ext import commands import asyncio intents = discord.Intents.default() BOT_TOKENS = ["token1", "token2", "token3", "token4", "token5"] # 定义所有机器人的事件处理器和命令 def create_bot(token): bot = commands.Bot(command_prefix=f"!", intents=intents) @bot.event async def on_ready(): print(f"{bot.user.name} 已连接到Discord!") return bot bots = [create_bot(token) for token in BOT_TOKENS] async def run_bots(): # 为每个机器人创建异步启动任务 tasks = [] for bot, token in zip(bots, BOT_TOKENS): # 使用非阻塞的bot.start()替代阻塞的bot.run() task = asyncio.create_task(bot.start(token)) tasks.append(task) # 等待所有机器人任务并发执行 await asyncio.gather(*tasks) if __name__ == "__main__": try: asyncio.run(run_bots()) except KeyboardInterrupt: # 捕获中断信号,确保机器人优雅退出 for bot in bots: asyncio.create_task(bot.close())
核心要点说明
- 选用
bot.start()而非bot.run():bot.start()是异步非阻塞方法,不会独占事件循环,适合并发场景;而bot.run()内部会自行创建事件循环并阻塞到程序结束。 - 利用
asyncio管理并发任务:asyncio.create_task将每个机器人的启动逻辑包装成异步任务,加入事件循环等待执行。asyncio.gather用于同时等待所有异步任务完成,实现真正的并发运行。
- 优雅退出处理:捕获
KeyboardInterrupt信号,调用bot.close()让机器人断开Discord连接,避免残留无效连接。
额外注意事项
- 确保Discord开发者平台中每个机器人的intents权限已正确开启,否则可能出现无法接收消息或事件的问题。
- 如果需要为不同机器人设置不同前缀或配置,可以修改
create_bot函数,将前缀等参数传入,比如:def create_bot(token, prefix): bot = commands.Bot(command_prefix=prefix, intents=intents) # ... 其余逻辑不变
内容的提问来源于stack exchange,提问作者Aviad Rozenhek
相关产品推荐
相关产品推荐

