to_inventory/back/tgbot/views.py

79 lines
2.5 KiB
Python

import json
from django.conf import settings
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters
from telegram.constants import ParseMode, ChatType
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 def start(update, context):
logger.info(update)
await update.message.reply_html(text="123")
class ItemViewSet(viewsets.ViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
@async_to_sync
async def create(self, request):
req = json.loads(request.body)
logger.info(f"que len before put {ptb_application.update_queue.qsize()}")
update_item = Update.de_json(data=req, bot=ptb_application.bot)
await ptb_application.update_queue.put(update_item)
logger.info(f"que len after put {ptb_application.update_queue.qsize()}")
# await self.ptb_application.bot.send_message(
# chat_id=req["message"]["from"]["id"],
# text=f'Вы прислали текст `{req["message"]["text"]}`',
# parse_mode=ParseMode.MARKDOWN_V2,
# reply_to_message_id=req["message"]["message_id"],
# )
# if req["message"]["chat"]["type"] != ChatType.PRIVATE:
# return Response()
# if req["message"]["text"] == "/add":
# await self.ptb_application.bot.send_message(
# chat_id=req["message"]["from"]["id"],
# text=f'Вы хотите создать новую инвентаризацию?',
# parse_mode=ParseMode.MARKDOWN_V2,
# reply_to_message_id=req["message"]["message_id"],
# )
return Response({"test": "create"})
async def init_tg():
ptb_application = (
Application.builder().token(settings.TGBOT["token"]).concurrent_updates(True).updater(None).build()
)
ptb_application.add_handler(CommandHandler("start", start))
ptb_application.add_handler(
MessageHandler(filters.ChatType.PRIVATE, callback=start)
)
logger.info(
{
"app": ptb_application,
"bot": ptb_application.bot,
"handlers": ptb_application.handlers,
}
)
await ptb_application.initialize()
await ptb_application.start()
return ptb_application
ptb_application = async_to_sync(init_tg)()