from contextlib import asynccontextmanager from http import HTTPStatus from fastapi import FastAPI, Request, Response import logging from telegram import Update from telegram.ext import filters, MessageHandler, ApplicationBuilder, CommandHandler, ContextTypes from utils.get_answer_local import get_answer # from utils.get_answer_hf_api import get_answer from config_data.config import Config, load_config config: Config = load_config() logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) tg_bot = ( ApplicationBuilder() .updater(None) .token(config.tg_bot.token) .read_timeout(7) .get_updates_read_timeout(42) .build() ) @asynccontextmanager async def lifespan(_: FastAPI): await tg_bot.bot.setWebhook('https://ekaterinatao-house_md_tg_bot.hf.space/') async with bot: await tg_bot.start() yield await tg_bot.stop() app = FastAPI(lifespan=lifespan) @app.get("/") def read_general(): return {"response": "Started"} @app.post("/") async def process_update(request: Request): print('enter') req = await request.json() print(req) update = Update.de_json(req, tg_bot.bot) await tg_bot.process_update(update) return Response(status_code=HTTPStatus.OK) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await context.bot.send_message( chat_id=update.effective_chat.id, text=f"Hi, {update.effective_user.first_name}! Write me anything you want!" ) async def respond_to_user(update: Update, context: ContextTypes.DEFAULT_TYPE): await context.bot.send_message( chat_id=update.effective_chat.id, reply_to_message_id=update.effective_message.id, text="Loadind the best answer...\nPlease wait couple of minutes :)" ) response_text = get_answer(update.message.text) await context.bot.send_message( chat_id=update.effective_chat.id, text=response_text ) start_handler = CommandHandler('start', start) respond_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), respond_to_user) tg_bot.add_handler(start_handler) tg_bot.add_handler(respond_handler) # if __name__ == '__main__': # tg_bot.run_polling()