メインコンテンツへスキップ

はじめに

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

ライブラリの変更

インストール

  • まず、Telegram へ送信するリクエストを処理するクラスを提供するライブラリをインストールする必要があります。ptbcontrib をインストールしましょう。以下のコマンドを使用してください。
pip install git+https://github.com/python-telegram-bot/ptbcontrib.git@main

httpx を aiohttp に変更する

  • 次に、ボットクライアントをインスタンス化するファイルで AiohttpRequest をインポートする必要があります。
from ptbcontrib.aiohttp_request import AiohttpRequest
  • このクラスは、デフォルトの httpx の代わりに Telegram へのすべてのリクエストを処理します。
  • AiohttpRequest は、以下の例のように PTB クライアントのインスタンスで使用されます。
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())
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()

なぜこの変更を行うのか?

  • ライブラリを httpx から aiohttp に変更すると、いくつかのメリットがあります。
  1. パフォーマンス: aiohttp は httpx よりも高速です。
  2. エラーの軽減: httpx はその設定とパフォーマンスにより、ReadError やその他の NetworkError など、ネットワークエラーを多発させます。

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

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

Google レビュー

Google レビューにあなたのレビューを残してください。

Trustpilot

Trustpilot にあなたのレビューを残してください。