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

# PTB の httpx を aiohttp に変更する方法

> このチュートリアルでは、python-telegram-bot の httpx を aiohttp に変更する方法を解説します。

## はじめに

* この記事では、`python-telegram-bot` の `httpx` を `aiohttp` に変更する手順を解説します。`httpx` と `aiohttp` は、HTTP リクエストを行うために使用されるライブラリです。
* 始める前に、環境に Python と python-telegram-bot ライブラリがインストールされていることを確認してください。python-telegram-bot のインストールコマンドは以下のとおりです。

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

## ライブラリの変更

### インストール

* まず、Telegram へ送信するリクエストを処理するクラスを提供するライブラリをインストールする必要があります。`ptbcontrib` をインストールしましょう。以下のコマンドを使用してください。

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

### httpx を aiohttp に変更する

* 次に、ボットクライアントをインスタンス化するファイルで `AiohttpRequest` をインポートする必要があります。

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

* このクラスは、デフォルトの `httpx` の代わりに Telegram へのすべてのリクエストを処理します。
* `AiohttpRequest` は、以下の例のように PTB クライアントのインスタンスで使用されます。

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

## なぜこの変更を行うのか？

* ライブラリを httpx から aiohttp に変更すると、いくつかのメリットがあります。

1. **パフォーマンス**: aiohttp は httpx よりも高速です。
2. **エラーの軽減**: httpx はその設定とパフォーマンスにより、ReadError やその他の NetworkError など、ネットワークエラーを多発させます。

## この記事は役に立ちましたか？

* 私たちは可能な限り最良のサポートを提供するため、細心の注意を払ってこのコンテンツを作成しました。
  この記事が少しでもお役に立ったなら、ぜひ私たちの活動を応援してください。レビューを残していただけると、あなたにとって何が最も重要かを理解する助けになります。

<CardGroup cols={2}>
  <Card title="Google レビュー" icon="google" href="https://g.page/r/CYZenpQcDgTzEAI/review">
    Google レビューにあなたのレビューを残してください。
  </Card>

  <Card title="Trustpilot" icon="star" href="https://www.trustpilot.com/review/squarecloud.app">
    Trustpilot にあなたのレビューを残してください。
  </Card>
</CardGroup>
