如何同时 运行 多个 Discord 客户端
How to run multiple Discord clients simultaneously
我已经使用 discord.py 库创建了一些机器人,现在我想构建一个 'dispatcher' 来读取配置文件并启动它们。我的每个机器人都是从抽象机器人 class 扩展而来的 class。但是,我被困在 运行 同时处理它们。这些是我尝试过的一些东西:
- 使用线程。例如:
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
等会阻塞,直到子进程结束(即机器人被杀死)。我也不想使用这种方法,因为它是一个 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
的方法,但我还没有找到任何方法来做到这一点。
最简单的方法是使用 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
)
它将在后台启动所有文件。
我已经使用 discord.py 库创建了一些机器人,现在我想构建一个 'dispatcher' 来读取配置文件并启动它们。我的每个机器人都是从抽象机器人 class 扩展而来的 class。但是,我被困在 运行 同时处理它们。这些是我尝试过的一些东西:
- 使用线程。例如:
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
等会阻塞,直到子进程结束(即机器人被杀死)。我也不想使用这种方法,因为它是一个 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
的方法,但我还没有找到任何方法来做到这一点。
最简单的方法是使用 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
)
它将在后台启动所有文件。