Django Integration with Async Telegram Bot Library
I’m working on integrating a telegram bot with Django using async functionality but running into some issues. My setup includes Django 5.0.3 and python-telegram-bot 21.0.1.
I’ve successfully built telegram bots using FastAPI with uvicorn, but Django seems to behave differently. The main problem occurs when I try to use the async context manager. My application hangs and eventually times out.
Here’s what I’m trying to accomplish:
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from telegram import Update
from telegram.ext import ContextTypes, CommandHandler
import json
async def message_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(update.message.text)
@csrf_exempt
async def webhook_handler(request):
bot_token = "YOUR_BOT_TOKEN"
app_instance = get_bot_application(bot_token)
if request.method == 'POST':
update_data = json.loads(request.body)
async with app_instance:
# This line causes timeout issues
pass
return JsonResponse({'status': 'ok'})
The error I get is a connection timeout from httpcore. I’ve tried running the server with both python manage.py runserver and uvicorn project.asgi:application but get the same result.
For comparison, here’s how I handle this successfully in FastAPI:
from fastapi import FastAPI, Request
from contextlib import asynccontextmanager
@asynccontextmanager
async def app_lifespan(app: FastAPI):
async with bot_application:
await bot_application.start()
setup_bot_handlers(bot_application)
yield
await bot_application.stop()
api = FastAPI(lifespan=app_lifespan)
@api.post("/webhook")
async def receive_update(request: Request):
await process_telegram_update(bot_application, request)
return {"status": "success"}
What’s the correct way to handle async telegram bot applications in Django? Is there a different approach I should be taking?