所有找的题目都没有帮到我,所以我决定自己问。我需要并行启动两个不同的机器人,但只有第一个线程在运行。
这是我的代码:
threading.Thread(target=asyncio.run, args=(vkbot.run_forever(),)).start() #first bot
threading.Thread(target=asyncio.run, args=(bot.run(token=token),)).start() #second bot
我尝试使用
multiprocessing
但我遇到了同样的问题 - 只有第一个进程在运行。当我交换它们时,没有任何改变——只有第一个进程再次运行。有什么问题吗?
UPD:完整的简化代码:
from vkbottle.bot import Bot, Message
import threading, discord
from discord import commands
vkbot = Bot(token=vk_token)
bot = commands.Bot(command_prefix="+", intents=intents)
@vkbot.on.message()
async def main(message: Message):
if message.text.lower().startswith("+reg"):
await message.answer("something")
@bot.event
async def on_ready():
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
# Here are the methods I can't run in parallel
vkbot.run_forever()
bot.run(token=token)
你发现
asyncio.run()
和线程不混合。
相反,
asyncio.run()
一个 asyncio.gather()
将启动两个协程作为任务:
asyncio.run(
asyncio.gather(
vkbot.run_polling(), # The async coroutine vkbottle uses
bot.run(token=token),
)
)