Skip to content Skip to sidebar Skip to footer

How To Make A Multithreaded And Async Python Discord Bot

I'm making a discord bot, which uses some big data (500-900Mb). My issue is that I need to refresh (getting from API) the data every minute and at the same time still answering to

Solution 1:

If get_API_data is a completely asynchronous there shouldn't be an issue running both the bot and the function in the same thread. Nonetheless you can use 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())

Post a Comment for "How To Make A Multithreaded And Async Python Discord Bot"