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

hmtdttj4  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(553)

我已经使用discord.py库创建了一些机器人程序,现在我想构建一个“dispatcher”,读取配置文件并启动它们。我的每个机器人都是从抽象机器人类扩展而来的一个类。然而,我一直坚持同时运行它们。以下是我尝试过的一些事情:
使用线程。如: threading.Thread(target=discord.Client('token').run)).start() . 不起作用,因为 Client.run() 尝试启动 asyncio 事件再次循环,导致错误( RuntimeError: Cannot close a running event loop ).
使用 os.system / multiprocessing / subprocess . 运行 .py 包含机器人程序的文件。不起作用,因为 os.system etc阻塞,直到子进程结束(即bot被终止)。我也不喜欢使用这种方法,因为它是bi
创建任务并将其放在单个 asyncio 循环(如下所示)。
我尝试的最后一种方法的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 ,但我还没有找到任何方法来做到这一点。

tuwxkamq

tuwxkamq1#

最简单的方法是使用 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
)

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

相关问题