为什么带有Webhooks的Python上的telegram-bot不能同时处理来自许多用户的消息,而不像具有Long Polling的机器人?



我使用图标。我的bot的逻辑非常简单-他接收来自用户的消息并在10秒后发送回声消息。这是一个测试机器人,但总的来说,我想做一个机器人购买电影与非常大的用户数据库。因此,我的bot必须能够同时处理来自多个用户的消息,并且必须使用Webhooks接收消息。下面是两个python脚本:

Telegram-bot onLong Polling:

import asyncio
import logging
from aiogram import Bot, Dispatcher, executor, types
from bot_files.config import *
# Configure logging
logging.basicConfig(level=logging.INFO)
# Initialize bot and dispatcher
bot = Bot(token=bot_token)
dp = Dispatcher(bot)
@dp.message_handler()
async def echo(message: types.Message):
await asyncio.sleep(10)
await message.answer(message.text)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)

Telegram-bot onWebhooks:

import asyncio
import logging
from aiogram import Bot, Dispatcher, executor, types
from bot_files.config import *
# Configure logging
logging.basicConfig(level=logging.INFO)
# Initialize bot and dispatcher
bot = Bot(token=bot_token)
dp = Dispatcher(bot)
WEBHOOK_HOST = f'https://7417-176-8-60-184.ngrok.io'
WEBHOOK_PATH = f'/webhook/{bot_token}'
WEBHOOK_URL = f'{WEBHOOK_HOST}{WEBHOOK_PATH}'
# webserver settings
WEBAPP_HOST = '0.0.0.0'
WEBAPP_PORT = os.getenv('PORT', default=5000)
async def on_startup(dispatcher):
await bot.set_webhook(WEBHOOK_URL, drop_pending_updates=True)
async def on_shutdown(dispatcher):
await bot.delete_webhook()
@dp.message_handler()
async def echo(message: types.Message):
await asyncio.sleep(10)
await message.answer(message.text)
if __name__ == '__main__':
executor.start_webhook(
dispatcher=dp,
webhook_path=WEBHOOK_PATH,
skip_updates=True,
on_startup=on_startup,
on_shutdown=on_shutdown,
host=WEBAPP_HOST,
port=WEBAPP_PORT
)

在第一种情况下,如果两个用户同时发送消息,则两个消息也同时被处理(异步)- 10秒。在第二种情况下,消息被线性处理(而不是异步处理)——两个用户中的一个必须等待20秒。为什么带有Webhooks的Python上的telegram-bot不能同时处理来自多个用户的消息,而不像带有长轮询的bot ?

实际上,使用Webhooks的Python telegram-bot可以同时处理来自多个用户的消息。您只需要将@dp.async_task放在处理程序之后

@dp.message_handler()
@dp.async_task
async def echo(message: types.Message):
await asyncio.sleep(10)
await message.answer(message.text)

最新更新