Skip to main content

Introduction

  • This article guides you through changing python-telegram-bot httpx to aiohttp. httpx and aiohttp are libraries used to make http requests.
  • Before we get start, make sure you have Python and python-telegram-bot library installed on your environment. Check the python-telegram-bot instalation command below.
pip install python-telegram-bot

Changing libraries

Installing

  • First, you will need to install a library that offers an class to handle the requests maded to Telegram. Let’s install ptbcontrib, use the command below:
pip install git+https://github.com/python-telegram-bot/ptbcontrib.git@main

Changing httpx to aiohttp

  • Next, we need to import AiohttpRequest in the file where we will instantiate our bot client.
from ptbcontrib.aiohttp_request import AiohttpRequest
  • This class will handle all requests to telegram instead of default httpx.
  • AiohttpRequest will be used in the PTB client instance like in the example below:
import asyncio
import telegram
from ptbcontrib.aiohttp_request import AiohttpRequest


async def main():
    bot = telegram.Bot("TOKEN", request=AiohttpRequest(), get_updates_request=AiohttpRequest())
    async with bot:
        print(await bot.get_me())


if __name__ == '__main__':
    asyncio.run(main())

Why do this change?

  • Changing the library httpx to aiohttp brings some benefits with it.
  1. Performance: aiohttp is faster than httpx.
  2. Mitigating Errors: The httpx will raise too much network errors like ReadError and other NetworkErrors due to it’s configurations and performance.

Did you like this article?

  • We created this content with great care to offer the best help possible. If this article helped you in any way, support our work! Leave your review! it helps us understand what matters most to you.