如何制作多线程和异步 Python discord 机器人

How to make a multithreaded and async Python discord bot


我正在制作一个不和谐的机器人,它使用一些大数据 (500-900Mb)。
我的问题是我需要每分钟刷新一次(从 API 获取)数据,同时还要响应命令。

为此,我使用了 discord 模块 discordpy 及其 discord.ext.tasks.loop 对象,但正如您所想象的那样,它不是多线程的,并且机器人在从 API.[=16 获取数据时非常滞后=]

为了修复它,我尝试将 asyncio.to_thread()asyncio.gather() 一起使用,但它不起作用,我的错误是:

RuntimeError: Cannot run the event loop while another loop is running.
我坚持这个

我的代码有问题:

def q():
    asyncio.run(getting_API_data)

async def main():
    print("starting gather")
    await asyncio.gather(
        asyncio.to_thread(q),
        client.run(TOKEN)
    )
asyncio.run(main())

注意getting_API_data是一个异步函数

如果 get_API_data 是完全异步的,那么在同一个线程中 运行 机器人和函数应该不会有问题。尽管如此,您还是可以使用 asyncio.run_coroutine_threadsafe and run that in another thread. Another issue is that you cannot use client.run here since it's a blocking function, use client.start combined with client.close

import asyncio

loop = asyncio.get_event_loop()

async def run_bot():
    try:
        await client.start()
    except Exception:
        await client.close()


def run_in_thread():
    fut = asyncio.run_coroutine_threadsafe(getting_API_data(), loop)
    fut.result()  # wait for the result


async def main():
    print("Starting gather")
    await asyncio.gather(
        asyncio.to_thread(run_in_thread),
        run_bot()
    )


loop.run_until_complete(main())