from django.shortcuts import render, redirect
import json
import telegram
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .core import TelegramBot
from colorama import init, Fore
from django.apps import apps
init(autoreset=True)
async def get_bot():
    if apps.ready:
        print(Fore.GREEN + 'get_bot')
        bot = TelegramBot()
        bot.app.updater=None
        bot.autodiscover()
        await bot.app.initialize()
        return bot
    return None

telegram_bot = None
@csrf_exempt
async def webhook(request, **kwargs):
    global telegram_bot
    if request.method == 'POST':
        try:
            if not telegram_bot:
                telegram_bot=await get_bot()
            update = telegram.Update.de_json(json.loads(request.body), telegram_bot.bot)
            await telegram_bot.app.process_update(update)
            return JsonResponse({"ok": True})
        except Exception as e:
            return JsonResponse({"ok": False, "error": str(e)})
    return JsonResponse({"ok": False})

