Django Webhook Integration with Aiogram

Overview

This project integrates a Telegram bot (using Aiogram) with a Django application via a webhook. However, when running python manage.py migrate, the following error occurs:

RuntimeError: Event loop is closed
Unclosed client session

Issue

  • The error suggests issues with the event loop being closed prematurely and an unclosed aiohttp client session.
  • The webhook handler processes updates from Telegram asynchronously using Aiogram, but the event loop is not managed properly in Django’s synchronous views.

Code

session = AiohttpSession()
bot = Bot(token=settings.BOT_TOKEN, session=session, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
dp = Dispatcher()

@csrf_exempt
def webhook(request):
    if request.method == "POST":
        try:
            update_data = json.loads(request.body)
            update = Update(**update_data)

            async def process_update():
                await dp.feed_update(bot=bot, update=update)

            loop = asyncio.get_event_loop()
            if loop.is_closed():
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
            loop.run_until_complete(process_update())

            return HttpResponse("OK")
        except Exception as e:
            logger.error(f"Error: {e}")
            return HttpResponse("Bad Request", status=400)
    return HttpResponse("Method not allowed", status=405)

ask for ChatGPT but without success.

Вернуться на верх