Why telegram-bot on Python with Webhooks can't process messages from many users simultaneously unlike a bot with Long Polling?

Question:

I use aiogram. Logic of my bot is very simple – he receive messages from user and send echo-message after 10 seconds. This is a test bot, but in general, I want to make a bot for buying movies with very big database of users. So, my bot must be able to process messages from many users simultaneously and must receive messages using Webhooks. Here are two python scripts:

Telegram-bot on Long 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 on Webhooks:

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
    )

In the first case, if two users send messages simultaneously, both of messages are processed also simultaneously(acynchrony) – 10 seconds. In the second case messages are processed linearly(not asynchrony) – one of two users must wait 20 seconds. Why telegram-bot on Python with Webhooks can’t process messages from many users simultaneously unlike a bot with Long Polling?

Asked By: Tomas Angelo

||

Answers:

Actually telegram-bot on Python with Webhooks can process messages from many users simultaneously. You need just to put @dp.async_task after handler

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