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

如何用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:33:02