setting async python-telegram-bot(ptb) webhooks using django

32 views Asked by At

setting async python-telegram-bot(ptb) webhooks using django I am using Django==5.0.3 and python-telegram-bot==21.0.1 I have developed several telegram bots using fastapi+uvicorn and ptb but I can't make django work with python telegram bot library. I get timeout error when I include this line: async with application: I am using postman to simulate a telegram request with a post request with a body like this:

{"update_id": 400838435, "message": {"message_id": 627, "from": {"id": 357686176, "is_bot": false, "first_name": "-----", "last_name": "---", "username": "----", "language_code": "en"}, "chat": {"id": 357686176, "first_name": "----", "last_name": "------", "username": "----", "type": "private"}, "date": 1711115302, "text": "hi"}}

Here is my code.

I have tested both uvicorn nameoftheproject.asgi:application and python manage.py runserver to run the project but the result is the same

from django.shortcuts import render, HttpResponse
from django.http import HttpRequest
from django.views.decorators.csrf import csrf_exempt
from . import botInstance
# from handlers.handler_mapping import set_handlers
from .handlers.handler_mapping import set_handlers
from telegram.ext import MessageHandler, filters, ContextTypes
from telegram import Update
import json
# Create your views here.
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await Update.message.reply_text(update.message.text)

@csrf_exempt
async def say_hello(request: HttpRequest):
    #print(request)
    # print(request.body)
    #print(request.GET)
    token = "-------A"
    application = botInstance.get(token)
    if request.method == 'POST':
        print(json.loads(request.body))
        async with application:
            pass
        #     await application.start()
        #     # set_handlers(application)
        #     application.add_handler(MessageHandler(filters.FORWARDED & filters.ChatType.PRIVATE, echo))
        #     await botInstance.process_update(application, json.loads(request.body))
            
        #     # return Response(status_code=HTTPStatus.OK)
            
        #     await application.stop()
        
 
    return HttpResponse('hello world1')

this is the error I face in terminal:

Traceback (most recent call last):
  File "/root/.local/share/virtualenvs/django-asgi-YxRERmLZ/lib/python3.10/site-packages/httpx/_transports/default.py", line 69, in map_httpcore_exceptions
    yield
  File "/root/.local/share/virtualenvs/django-asgi-YxRERmLZ/lib/python3.10/site-packages/httpx/_transports/default.py", line 373, in handle_async_request
    resp = await self._pool.handle_async_request(req)
  File "/root/.local/share/virtualenvs/django-asgi-YxRERmLZ/lib/python3.10/site-packages/httpcore/_async/connection_pool.py", line 216, in handle_async_request
    raise exc from None
  File "/root/.local/share/virtualenvs/django-asgi-YxRERmLZ/lib/python3.10/site-packages/httpcore/_async/connection_pool.py", line 196, in handle_async_request
    response = await connection.handle_async_request(
  File "/root/.local/share/virtualenvs/django-asgi-YxRERmLZ/lib/python3.10/site-packages/httpcore/_async/connection.py", line 99, in handle_async_request
    raise exc
  File "/root/.local/share/virtualenvs/django-asgi-YxRERmLZ/lib/python3.10/site-packages/httpcore/_async/connection.py", line 76, in handle_async_request
    stream = await self._connect(request)
  File "/root/.local/share/virtualenvs/django-asgi-YxRERmLZ/lib/python3.10/site-packages/httpcore/_async/connection.py", line 122, in _connect
    stream = await self._network_backend.connect_tcp(**kwargs)
  File "/root/.local/share/virtualenvs/django-asgi-YxRERmLZ/lib/python3.10/site-packages/httpcore/_backends/auto.py", line 30, in connect_tcp
    return await self._backend.connect_tcp(
  File "/root/.local/share/virtualenvs/django-asgi-YxRERmLZ/lib/python3.10/site-packages/httpcore/_backends/anyio.py", line 112, in connect_tcp
    with map_exceptions(exc_map):
  File "/usr/lib/python3.10/contextlib.py", line 153, in __exit__
    self.gen.throw(typ, value, traceback)
  File "/root/.local/share/virtualenvs/django-asgi-YxRERmLZ/lib/python3.10/site-packages/httpcore/_exceptions.py", line 14, in map_exceptions
    raise to_exc(exc) from exc
httpcore.ConnectTimeout

this is how I have successfully implemented it in fastapi

token = Config.BOT_TOKEN
application = botInstance.get(token)

@asynccontextmanager
async def lifespan(_: FastAPI):
    # await application.bot.setWebhook(Config.WEBHOOK_URL)
    async with application:
        await start_db()
        await application.start()
        set_handlers(application)

        yield

        await application.stop()
        await close_db()


app = FastAPI(lifespan=lifespan)

@app.post("/")
async def get_telegram_request(request: Request):
    await botInstance.process_update(application, request)
    return Response(status_code=HTTPStatus.OK)

0

There are 0 answers