Настройка асинхронных веб-крючков python-telegram-bot(ptb) с помощью django
Установка асинхронных веб-крючков python-telegram-bot(ptb) с помощью django
Я использую Django==5.0.3 и python-telegram-bot==21.0.1 Я разработал несколько ботов telegram, используя fastapi+uvicorn и ptb, но я не могу заставить django работать с библиотекой python telegram bot. Я получаю ошибку таймаута, когда включаю эту строку:
async with application:
Я использую postman, чтобы имитировать запрос telegram с помощью post-запроса с телом следующего вида:
{"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"}}
Вот мой код.
Я проверил оба варианта uvicorn nameoftheproject.asgi:application
и python manage.py runserver
для запуска проекта, но результат один и тот же
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')
вот с какой ошибкой я сталкиваюсь в терминале:
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
вот как я успешно реализовал это в 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)