繁体   English   中英

为什么带有 Webhook 的 Python 上的电报机器人不能像带有长轮询的机器人那样同时处理来自许多用户的消息?

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

我使用aiogram 我的机器人的逻辑非常简单——他从用户那里接收消息并在 10 秒后发送回显消息。 这是一个测试机器人,但总的来说,我想制作一个用于购买拥有大量用户数据库的电影的机器人。 因此,我的机器人必须能够同时处理来自许多用户的消息,并且必须使用 Webhook 接收消息。 这里有两个 python 脚本:

长轮询电报机器人:

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)

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
    )

在第一种情况下,如果两个用户同时发送消息,则两个消息也会同时处理(同步)- 10 秒。 在第二种情况下,消息是线性处理的(不是异步的)——两个用户之一必须等待 20 秒。 为什么带有 Webhook 的 Python 上的电报机器人不能像带有长轮询的机器人那样同时处理来自许多用户的消息?

实际上,带有 Webhook 的 Python 上的电报机器人可以同时处理来自许多用户的消息。 您只需要将@dp.async_task放在处理程序之后

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM