> ## 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.

# Fix python-telegram-bot NetworkError with aiohttp

> python-telegram-bot NetworkError fix: swap the default httpx backend for aiohttp with ptbcontrib's AiohttpRequest, with examples for Bot and ApplicationBuilder.

This guide changes the HTTP backend of `python-telegram-bot` (PTB) from `httpx`, the default, to `aiohttp`. Both are libraries that make HTTP requests. The default `httpx` backend can raise frequent `NetworkError` exceptions, such as `ReadError`, in bots that poll Telegram for long periods, and switching to `aiohttp` is a common way to make them stop. If your bot runs without these errors, you don't need this change.

## Install ptbcontrib

You need Python and the `python-telegram-bot` library:

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

Then install `ptbcontrib`, which offers a class to handle the requests made to Telegram. Its `aiohttp_request` extra also installs `aiohttp`:

```bash theme={"system"}
pip install "ptbcontrib[aiohttp_request] @ git+https://github.com/python-telegram-bot/ptbcontrib.git@main"
```

Add the same dependencies to your `requirements.txt`, so Square Cloud installs them during the deploy:

```txt requirements.txt theme={"system"}
python-telegram-bot
ptbcontrib[aiohttp_request] @ git+https://github.com/python-telegram-bot/ptbcontrib.git@main
```

## Switch from httpx to aiohttp

Import `AiohttpRequest` in the file where you create your bot client:

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

This class handles all requests to Telegram instead of the default `httpx`. Pass it to the PTB client like in the examples below. Both read the bot token from the `TELEGRAM_BOT_TOKEN` environment variable, so it never goes into your code:

<CodeGroup>
  ```python Bot theme={"system"}
  import asyncio
  import os

  import telegram
  from ptbcontrib.aiohttp_request import AiohttpRequest


  async def main():
      bot = telegram.Bot(
          os.environ["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={"system"}
  import logging
  import os

  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()
          .token(os.environ["TELEGRAM_BOT_TOKEN"])
          .request(AiohttpRequest(connection_pool_size=256))
          .get_updates_request(AiohttpRequest())
          .build()
      )

      start_handler = CommandHandler('start', start)
      application.add_handler(start_handler)

      application.run_polling()
  ```
</CodeGroup>

## Run it on Square Cloud

Create a `squarecloud.app` file at the root of your project. For a bot whose main file is `main.py`:

```systemd squarecloud.app theme={"system"}
DISPLAY_NAME=My Telegram Bot
MAIN=main.py
MEMORY=512
VERSION=recommended
AUTORESTART=true
```

Your ZIP holds `main.py`, `requirements.txt` and `squarecloud.app`, without the token.

Then set the token as the `TELEGRAM_BOT_TOKEN` environment variable: in the upload form's **Advanced configuration**, on the application's **Environment Variables** page (then restart the bot), or from the CLI:

```bash theme={"system"}
squarecloud app env set TELEGRAM_BOT_TOKEN=your_token_here
squarecloud app restart
```

See [Environment variables](/en/platform/environment-variables) for the details, and the [Telegram bot tutorial](/en/tutorials/bots/telegram) for the full deploy walkthrough.

## Next steps

<CardGroup cols={3}>
  <Card title="Telegram bot" icon="telegram" href="/en/tutorials/bots/telegram">
    Create, deploy and test a Telegram bot from scratch.
  </Card>

  <Card title="Environment variables" icon="key" href="/en/platform/environment-variables">
    Manage your bot's token and other secrets.
  </Card>

  <Card title="App won't start" icon="triangle-exclamation" href="/en/platform/troubleshooting/app-wont-start">
    Fix ModuleNotFoundError and other startup failures.
  </Card>
</CardGroup>

## 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! Developers have already rated Square Cloud **4.9/5 across 402 reviews** on Google and Trustpilot: leave yours too! It helps us understand what matters most to you.

<CardGroup cols={2}>
  <Card title="Google Reviews" icon="google" href="https://g.page/r/CYZenpQcDgTzEAI/review">
    Leave your review in Google Reviews.
  </Card>

  <Card title="Trustpilot" icon="star" href="https://www.trustpilot.com/review/squarecloud.app">
    Leave your review in Trustpilot.
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.