73 lines
3.6 KiB
Python
73 lines
3.6 KiB
Python
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": "1"}},
|
||
)
|
||
|
||
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:
|
||
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()
|