vision-career/backend/bot.py
2025-10-21 20:21:02 +03:00

77 lines
3.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import sys
sys.path.append(".")
import os
import io
import traceback
from telegram import Update, ReplyKeyboardMarkup
from telegram.ext import filters, ApplicationBuilder, MessageHandler, CommandHandler, ContextTypes
from backend.agent import agent, redis
from pypdf import PdfReader
VACANCIES = "👥 Вакансии"
RESUME = "📄 Резюме"
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = "Привет! Я карьерный копилот: помогу с работой, интервью и расскажу новости по рынку, специально для тебя. С чего начнем?"
reply_markup = ReplyKeyboardMarkup([[VACANCIES, RESUME]], resize_keyboard=True, one_time_keyboard=False)
await context.bot.send_message(chat_id=update.effective_chat.id, text=text, reply_markup=reply_markup)
async def prompt(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.message.text == RESUME:
resume = await redis.get(update.effective_user.id)
text = "Пришли мне файл с твоим резюме, чтобы я смог найти подходящие вакансии на основе твоих компетенций!"
if resume:
text = "Я уже получил твое резюме. Если хочешь его обновить, пришли мне новый файл!"
await context.bot.send_message(update.effective_chat.id, text)
return
user_prompt = update.message.text
if update.message.text == VACANCIES:
user_prompt = "Пришли мне актуальные вакансии на основе моего резюме"
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{user_prompt}"}]},
config={"configurable": {"thread_id": update.effective_user.id}},
)
await context.bot.editMessageText(response['messages'][-1].content, update.effective_chat.id, message.id)
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
traceback.print_exception(context.error)
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()