跳转到主要内容

简介

  • 本文将引导你把 python-telegram-bothttpx 更换为 aiohttphttpxaiohttp 都是用于发起 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
  • 这个类将处理所有向 telegram 发起的请求,而不是默认的 httpx
  • 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 Reviews

在 Google Reviews 上留下你的评价。

Trustpilot

在 Trustpilot 上留下你的评价。