簡體   English   中英

如何制作多線程和異步 Python Discord 機器人

[英]How to make a multithreaded and async Python discord bot


我正在制作一個不和諧的機器人,它使用一些大數據(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是一個異步函數

如果get_API_data是完全異步的,則在同一線程中運行機器人和函數應該不會出現問題。 盡管如此,您可以使用asyncio.run_coroutine_threadsafe並在另一個線程中運行它。 另一個問題是你不能在這里使用client.run因為它是一個阻塞函數,使用client.startclient.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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM