File size: 2,271 Bytes
5c1d00c
 
 
b6e0562
 
 
0c21b8b
 
b6e0562
 
 
 
 
 
 
 
 
 
e361d7d
5c1d00c
 
 
 
 
 
 
 
 
 
e361d7d
 
 
5c1d00c
e361d7d
 
 
 
5c1d00c
e361d7d
 
 
5c1d00c
e361d7d
 
 
 
 
 
 
 
5c1d00c
 
b6e0562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e361d7d
 
b6e0562
 
9c741c7
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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()