Search code examples
python-asyncioaiohttppython-telegram-bot

Using the ClientSession object from aiohttp in python-telegram-bot


I don't want to create sessions for every HTTP request in python-telegram-bot. I can create a ClientSession object in main(), even though a warning is issued against doing so. Also, I'm not closing this session anywhere. Please advise on the correct approach.

from aiohttp import ClientSession
from telegram.ext import Application, CommandHandler

app_storage = {}

if __name__ == '__main__':
    app_storage['session'] = ClientSession()
    application = Application.builder().token(some_token).build()
    application.add_handler(CommandHandler('start', wake_up))
    application.run_polling()

Solved (thanks CallMeStag)

from aiohttp import ClientSession
from telegram.ext import Application, CommandHandler


async def some_name(update, context):
    async with context.bot_data['client'].get(some_url) as response:
        data = await response.json()
        # Some other code


async def post_init(application: Application) -> None:
    application.bot_data['client'] = ClientSession()


async def post_shutdown(application: Application) -> None:
    await application.bot_data['client'].close()


if __name__ == '__main__':
    application = Application.builder().token(some_token).post_init(
        post_init).post_shutdown(post_shutdown).build()
    application.add_handler(CommandHandler('some_command', some_name))    
    application.run_polling()

Solution

  • You could store the object in Application.bot_data and access it in every callback via context.bot_data - see also this wiki page. You might also be interested in the customization of the context argument via ContextTypes. If you want to close the session on shutdown, you may want to use ApplicationBuilder.post_shutdown.


    Disclaimer: I'm currently the maintainer of python-telegram-bot.