You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用单个Python脚本运行多个Discord机器人

如何在discord.py中同时运行多个Discord机器人账号

嘿,我来帮你搞定这个多账号机器人运行的问题!你现在的瓶颈主要在于直接重复单个机器人的流程时,没有妥善处理多个discord.Client实例的异步运行逻辑——毕竟每个机器人都需要独立的事件循环来处理Discord的网关连接和事件。

核心思路

每个机器人账号都需要创建独立的discord.Client实例,然后借助Python的asyncio库来并发运行这些实例,让它们各自处理自己的连接和事件,互不干扰。

完整实现代码

import discord
import asyncio

# 存储你的多个机器人账号信息,替换成实际的账号密码
bot_accounts = [
    {"email": "bot1_email@example.com", "password": "bot1_password"},
    {"email": "bot2_email@example.com", "password": "bot2_password"},
    # 可以继续添加更多账号
]

async def run_single_bot(email, password):
    # 为每个账号创建独立的Client实例
    client = discord.Client()

    # 机器人就绪事件
    @client.event
    async def on_ready():
        print(f"✅ 成功连接 - {client.user.name}")
        print(f"登录身份:{client.user.name} (ID: {client.user.id})")
        print("-------------------------------")

    # 自定义消息处理事件(示例)
    @client.event
    async def on_message(message):
        # 忽略机器人自己发的消息
        if message.author == client.user:
            return
        
        # 不同机器人可以有不同的回复逻辑
        if client.user.name == "Bot1":
            await message.channel.send(f"👋 我是Bot1,收到你的消息啦!")
        elif client.user.name == "Bot2":
            await message.channel.send(f"🤖 我是Bot2,很高兴为你服务!")

    # 启动当前机器人
    await client.start(email, password)

async def main():
    # 为每个账号创建运行任务
    bot_tasks = [run_single_bot(account["email"], account["password"]) for account in bot_accounts]
    # 并发运行所有机器人任务
    await asyncio.gather(*bot_tasks)

if __name__ == "__main__":
    # 启动主异步函数
    asyncio.run(main())

注意事项

  • 独立实例:每个机器人必须拥有自己的discord.Client对象,这样它们的事件处理、网关连接都是独立的,不会互相冲突。
  • 异步并发:用asyncio.gather()来同时启动所有机器人的连接,这是处理多个异步任务的标准方式,能高效利用事件循环。
  • 速率限制:Discord对API请求有速率限制,多个机器人同时运行时要注意不要触发限制,避免账号被临时封禁。
  • 库的选择:需要提醒你,discord.py已经停止维护了,如果你打算长期开发,推荐使用它的活跃分支比如disnakepycord,这些库在多机器人支持和新特性上更完善,但上面的代码逻辑在这些库中同样适用。

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

火山引擎 最新活动