pythonpython-3.xmultithreadingasynchronouspython-telegram-bot

How to run async function from another thread in python-telegram-bot (PTB)


We know that python-telegram-bot uses asyncio. but everything happens inside main Thread.
In this case I need to run an async function inside another Thread.
The main purpose of doing that is because of I'm using some calculation and fetching data that takes sometime. but during that the whole bot is waiting for task to be completed and will not give you any response on any request. so I have two options. the first is using an API to speed up the task. the second one is run calculations inside another thread. but it has to be async, and I don't know how to do that. I've been googling a little and found some methods such as

asyncio.run_coroutine_threadsafe(coro, loop)

How can I do that guys?

Part of my code =>

async def OptimizedSearch(context: ContextTypes.DEFAULT_TYPE) -> None:
    # Fetching Data and Some Calculations Here
    # It will take time (a few seconds or minutes)
    await context.bot.send_message(
        chat_id=context.job.chat_id,
        text=result
    )


async def run_script(update: Update, context: ContextTypes.DEFAULT_TYPE):
    job = context.job_queue.run_repeating(OptimizedSearch, 10*60, first=5, chat_id=chat_id, name="optimized_search")

Solution

  • You can fetch data asynchronously without creating additional threads by using async/await with asynchronous HTTP requests. This approach allows you to perform non-blocking operations.

    Here's an example of a GET request using httpx:

    async with httpx.AsyncClient() as client:
        result = await client.get('https://example.com')
    

    Or, If you want to run blocking code in another thread while using asyncio, you can utilize the run_in_executor method. This allows you to execute blocking operations in a separate thread, keeping your asyncio event loop unblocked Refer this.