61 lines
2.8 KiB
Python
61 lines
2.8 KiB
Python
import os
|
||
import re
|
||
import io
|
||
import traceback
|
||
from telegram import Update
|
||
from telegram.constants import ParseMode
|
||
from telegram.ext import filters, ApplicationBuilder, MessageHandler, CommandHandler, ContextTypes
|
||
from backend.agent import agent, redis
|
||
from pypdf import PdfReader
|
||
|
||
|
||
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
text = "Привет! Я карьерный копилот: помогу с работой, интервью и расскажу новости по рынку, специально для тебя. С чего начнем?"
|
||
await context.bot.send_message(chat_id=update.effective_chat.id, text=text)
|
||
|
||
|
||
async def prompt(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
message = await context.bot.send_message(update.effective_chat.id, "📝 Обрабатываю Ваш запрос. Пожалуйста, подождите...")
|
||
|
||
response = await agent.ainvoke(
|
||
input={"messages": [{"role": "user", "content": f"user_id = {update.effective_user.id}\n{update.message.text}"}]},
|
||
config={"configurable": {"thread_id": "1"}},
|
||
)
|
||
llm_message = re.sub(f'([{re.escape(r'_*[]()~`>#+-=|{}.!')}])', r'\\\1', response['messages'][-1].content)
|
||
|
||
await context.bot.editMessageText(llm_message, update.effective_chat.id, message.id, parse_mode=ParseMode.MARKDOWN_V2)
|
||
|
||
|
||
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||
print(traceback.format_exception(context.error)[-1])
|
||
await context.bot.send_message(chat_id=update.effective_chat.id, text="Произошла ошибка. Повтоите попытку позже.")
|
||
|
||
|
||
async def handle_document(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||
if not update.message.document:
|
||
await context.bot.send_message(chat_id=update.effective_chat.id, text="Не удалось прочитать информацию из файла! Попробуйте другой формат.")
|
||
return
|
||
|
||
buffer = io.BytesIO()
|
||
file = await update.message.document.get_file()
|
||
await file.download_to_memory(buffer)
|
||
reader = PdfReader(buffer)
|
||
resume = "\n".join(page.extract_text() for page in reader.pages)
|
||
await redis.set(update.effective_user.id, resume)
|
||
|
||
await context.bot.send_message(chat_id=update.effective_chat.id, text="Отлично! Запомнил Ваше резюме.")
|
||
|
||
|
||
def main():
|
||
application = ApplicationBuilder().token(os.environ["BOT_TOKEN"]).build()
|
||
start_handler = CommandHandler('start', start)
|
||
application.add_handler(start_handler)
|
||
application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), prompt))
|
||
application.add_handler(MessageHandler((filters.Document.ALL | filters.PHOTO) & (~filters.COMMAND), handle_document))
|
||
application.add_error_handler(error_handler)
|
||
application.run_polling()
|
||
|
||
|
||
if __name__ == '__main__':
|
||
main()
|