Search code examples
pythonbotspython-asynciotelegrampython-telegram-bot

Convert functions to async with python-telegram-bot library


I'm trying to make a Telegram bot that parses GTFS data and returns the user the status of subway trains. I'm using the python-telegram-bot library and, so far, the bot I created work as intended.

However, I wrote some very pandas rich functions that process pandas dataframes to obtain the train schedule. I've only just realized that these functions work normally if you have a single user request, otherwise, since they are not async, they are serialized and block subsequent requests (correct me if I'm wrong).

I've read that asyncio might be apt to it, but I can't make it work. What can I do in practice to async those functions?


Solution

  • You can wrap the sync function into an async function. Something like:

    from functools import wraps
    
    def make_async(sync_func):
        @wraps(sync_func)
        async def async_func(*args, **kwargs):
            return sync_func(*args, **kwargs)
        return async_func
    

    This function takes as parameter a sync function and returns a corresponding async function.