Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid webhook response given with handle_in_background=False #1457

Open
2 tasks done
unintended opened this issue Apr 11, 2024 · 0 comments
Open
2 tasks done

Invalid webhook response given with handle_in_background=False #1457

unintended opened this issue Apr 11, 2024 · 0 comments
Labels
bug Something is wrong with the framework

Comments

@unintended
Copy link
Contributor

Checklist

  • I am sure the error is coming from aiogram code
  • I have searched in the issue tracker for similar bug reports, including closed ones

Operating system

mac os x

Python version

3.12.2

aiogram version

3.4.1

Expected behavior

Bot handles incoming requests and replies with a proper status (200 on success)

Current behavior

Bot handles requests successfully but do not reply properly

Steps to reproduce

  1. create SimpleRequestHandler

    SimpleRequestHandler(
    dispatcher,
    bot,
    handle_in_background=False
    ).register(app, path=WEBHOOK_PATH)

  2. Create an empty command handler

    @router.message(CommandStart())
    async def message_handler(message: types.Message, state: FSMContext):
    pass

  3. Run

Code example

import logging
import os

import aiohttp.web_app
from aiogram import Dispatcher, Bot, types
from aiogram.client.default import DefaultBotProperties
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.client.telegram import TelegramAPIServer
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
from aiogram.fsm.context import FSMContext
from aiogram.webhook.aiohttp_server import setup_application, SimpleRequestHandler
from aiohttp import web

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger()

BOT_TOKEN = os.environ["BOT_TOKEN"]

BOT_API_BASE_URL = os.getenv('BOT_API_BASE_URL')

WEBAPP_HOST = os.getenv('WEBAPP_HOST', 'localhost')
WEBAPP_PORT = int(os.getenv('WEBAPP_PORT', 8080))

BASE_WEBHOOK_URL = os.getenv('BASE_WEBHOOK_URL', f"http://{WEBAPP_HOST}:{WEBAPP_PORT}")
WEBHOOK_PATH = os.getenv('WEBHOOK_PATH', '/webhook')


async def on_startup(bot: Bot) -> None:
    logger.info("Setting main bot webhook")
    await bot.set_webhook(f"{BASE_WEBHOOK_URL}{WEBHOOK_PATH}")


async def on_shutdown(bot: Bot) -> None:
    logger.info("Deleting main bot webhook")
    await bot.delete_webhook()


def main():
    logger.info('BOT_API_BASE_URL=%s', BOT_API_BASE_URL)
    logger.info('WEBAPP_HOST=%s', WEBAPP_HOST)
    logger.info('WEBAPP_PORT=%s', WEBAPP_PORT)
    logger.info('BASE_WEBHOOK_URL=%s', BASE_WEBHOOK_URL)
    logger.info('WEBHOOK_PATH=%s', WEBHOOK_PATH)

    if BOT_API_BASE_URL is not None:
        session = AiohttpSession(
            api=TelegramAPIServer.from_base(BOT_API_BASE_URL)
        )
    else:
        session = None

    bot = Bot(
        token=BOT_TOKEN, session=session,
        default=DefaultBotProperties(
            parse_mode=ParseMode.MARKDOWN_V2,
            link_preview_is_disabled=True
        )
    )

    app = aiohttp.web_app.Application()

    dispatcher = Dispatcher()
    dispatcher['bot'] = bot
    dispatcher['bot_api_session'] = session
    dispatcher.startup.register(on_startup)
    dispatcher.shutdown.register(on_shutdown)

    @dispatcher.message(CommandStart())
    async def message_handler(message: types.Message, state: FSMContext):
        pass

    SimpleRequestHandler(
        dispatcher,
        bot,
        handle_in_background=False
    ).register(app, path=WEBHOOK_PATH)

    setup_application(app, dispatcher)

    # Start web-application.
    web.run_app(app, host=WEBAPP_HOST, port=WEBAPP_PORT)


if __name__ == '__main__':
    main()

Logs

2024-04-11 09:28:12,870 - aiogram.event - INFO - Update id=209665694 is handled. Duration 0 ms by bot id=7052315372
2024-04-11 09:28:12,871 - aiohttp.access - INFO - 127.0.0.1 [11/Apr/2024:09:28:08 +0300] "POST /webhook HTTP/1.1" 200 237 "-" "-"
2024-04-11 09:28:12,872 - aiohttp.server - ERROR - Error handling request
Traceback (most recent call last):
  File "/Users/ignz/Library/Caches/pypoetry/virtualenvs/tg-feedback-bot-dfXuSdBg-py3.12/lib/python3.12/site-packages/aiohttp/web_protocol.py", line 350, in data_received
    messages, upgraded, tail = self._request_parser.feed_data(data)
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
  Invalid method encountered:
    b'HTTP/1.1 400 Bad Request'
       ^
2024-04-11 09:28:12,873 - aiohttp.access - INFO - 127.0.0.1 [11/Apr/2024:09:28:12 +0300] "UNKNOWN / HTTP/1.0" 400 0 "-" "-"

Additional information

No response

@unintended unintended added the bug Something is wrong with the framework label Apr 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something is wrong with the framework
Projects
None yet
Development

No branches or pull requests

1 participant