import json from django.conf import settings from telegram import Update from telegram.ext import Application, CommandHandler from asgiref.sync import async_to_sync from rest_framework import viewsets from rest_framework.response import Response from .models import Item from .serializers import ItemSerializer import logging logger = logging.getLogger("root") @async_to_sync async def init_tg(): ptb_application = ( Application.builder().token(settings.TGBOT["token"]).updater(None).build() ) logger.info( { "app": ptb_application, "bot": ptb_application.bot, "handlers": ptb_application.handlers, } ) return ptb_application class ItemViewSet(viewsets.ViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer def __init__(self, **kwargs) -> None: self.ptb_application = init_tg() super().__init__(**kwargs) @async_to_sync async def create(self, request): req = json.loads(request.body) await self.ptb_application.bot.send_message(chat_id=req["message"]["from"]["id"], text='123') return Response({"test": "create"})