> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Cómo cambiar httpx de PTB por aiohttp

> Este tutorial te guía sobre cómo cambiar httpx de python-telegram-bot por aiohttp.

## Introducción

* Este artículo te guía a través del cambio de `httpx` por `aiohttp` en `python-telegram-bot`. `httpx` y `aiohttp` son bibliotecas usadas para realizar peticiones http.
* Antes de empezar, asegúrate de tener Python y la biblioteca python-telegram-bot instalados en tu entorno. Consulta el comando de instalación de python-telegram-bot a continuación.

```bash theme={null}
pip install python-telegram-bot
```

## Cambiando las bibliotecas

### Instalación

* Primero, necesitarás instalar una biblioteca que ofrezca una clase para manejar las peticiones realizadas a Telegram. Instalemos `ptbcontrib`, usa el siguiente comando:

```bash theme={null}
pip install git+https://github.com/python-telegram-bot/ptbcontrib.git@main
```

### Cambiando httpx por aiohttp

* A continuación, necesitamos importar `AiohttpRequest` en el archivo donde instanciaremos nuestro cliente del bot.

```python theme={null}
from ptbcontrib.aiohttp_request import AiohttpRequest
```

* Esta clase manejará todas las peticiones a Telegram en lugar del `httpx` predeterminado.
* `AiohttpRequest` se usará en la instancia del cliente de PTB como en el ejemplo a continuación:

<CodeGroup>
  ```python Bot theme={null}
  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())
  ```

  ```python ApplicationBuilder theme={null}
  import logging
  from telegram import Update
  from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler
  from ptbcontrib.aiohttp_request import AiohttpRequest

  logging.basicConfig(
      format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
      level=logging.INFO
  )

  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
      await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")

  if __name__ == '__main__':
      application = ApplicationBuilder().request(AiohttpRequest(connection_pool_size=256)).get_updates_request(AiohttpRequest()).token('TOKEN').build()
      
      start_handler = CommandHandler('start', start)
      application.add_handler(start_handler)
      
      application.run_polling()
  ```
</CodeGroup>

## ¿Por qué hacer este cambio?

* Cambiar la biblioteca httpx por aiohttp trae consigo algunos beneficios.

1. **Rendimiento**: aiohttp es más rápido que httpx.
2. **Mitigación de errores**: httpx generará demasiados errores de red como ReadError y otros NetworkErrors debido a sus configuraciones y rendimiento.

## ¿Te gustó este artículo?

* Creamos este contenido con mucho cuidado para ofrecer la mejor ayuda posible.
  Si este artículo te ayudó de alguna manera, ¡apoya nuestro trabajo! ¡Deja tu reseña! nos ayuda a entender qué es lo que más te importa.

<CardGroup cols={2}>
  <Card title="Google Reviews" icon="google" href="https://g.page/r/CYZenpQcDgTzEAI/review">
    Deja tu reseña en Google Reviews.
  </Card>

  <Card title="Trustpilot" icon="star" href="https://www.trustpilot.com/review/squarecloud.app">
    Deja tu reseña en Trustpilot.
  </Card>
</CardGroup>
