【问题标题】:How to make a multithreaded and async Python discord bot如何制作多线程和异步 Python discord 机器人
【发布时间】:2021-07-18 19:27:06
【问题描述】:


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

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

为了解决这个问题,我尝试将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 是一个异步函数

【问题讨论】:

    标签: python multithreading discord.py python-asyncio


    【解决方案1】:

    如果get_API_data 是完全异步的,那么在同一线程中运行机器人和函数应该不会有问题。尽管如此,您可以使用asyncio.run_coroutine_threadsafe 并在另一个线程中运行它。另一个问题是你不能在这里使用client.run,因为它是一个阻塞函数,使用client.start结合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())
    

    【讨论】:

    • 如果有帮助,请随时接受答案:)
    • 我猜完成了 :)
    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 2020-12-04
    • 1970-01-01
    • 2019-01-14
    • 2020-10-11
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    相关资源
    最近更新 更多