如何同时 运行 多个 Discord 客户端

How to run multiple Discord clients simultaneously

我已经使用 discord.py 库创建了一些机器人,现在我想构建一个 'dispatcher' 来读取配置文件并启动它们。我的每个机器人都是从抽象机器人 class 扩展而来的 class。但是,我被困在 运行 同时处理它们。这些是我尝试过的一些东西:

我试过的最后一种方法的MRE:

import discord
import asyncio

class Bot:
    client = discord.Client()

    def __init__(self, token):
        self.token = token

        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):
            print(message.content)
        
    async def run(self):
        print('Bot running')
        self.client.run(self.token)

if __name__ == '__main__':
    bot1 = Bot('bot token here')
    bot2 = Bot('bot token here')
    loop = asyncio.get_event_loop()
    loop.create_task(bot1.run())
    loop.create_task(bot2.run())
    loop.run_forever()

这根本不起作用 - 第一个机器人在 run 方法中冻结,甚至从未登录。为了测试,两个机器人都登录到同一个机器人帐户,但这与问题无关。

我认为理想的解决方案是一种异步 运行 和 discord.Client 的方法,但我还没有找到任何方法来做到这一点。

最简单的方法是使用 subprocess.Popen

import sys
import subprocess

files = ["bot1.py", "bot2.py", ...]

for f in files:
    subprocess.Popen(
         [sys.executable, f], stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )

它将在后台启动所有文件。