ruz-bot/helpers/alice.py
emmatveev 17c9b1b693
All checks were successful
Deploy Dev / Build (pull_request) Successful in 4s
Deploy Dev / Push (pull_request) Successful in 8s
Deploy Dev / Deploy dev (pull_request) Successful in 17s
fix
2024-11-17 23:07:37 +03:00

98 lines
4.6 KiB
Python
Raw Permalink 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 logging
from typing import Optional
from helpers import now
from helpers.mongo import mongo
from utils import queues
def try_parse(message: str) -> Optional[int]:
letters = {
"ноль": 0,
"один": 1,
"два": 2,
"три": 3,
"четыре": 4,
"пять": 5,
"шесть": 6,
"семь": 7,
"восемь": 8,
"девять": 9
}
final = 0
for word in message.split():
try:
final = final * 10 + letters[word]
except KeyError:
return None
return final
class Processor:
def __init__(self, data: dict):
self.data = data
if 'user' in data['session']:
self.user_id = data['session']['user']['user_id']
else:
self.user_id = None
self.message = data['request']['original_utterance'].lower()
def get_lesson_for_user(self, chat_id: int):
user = mongo.users_collection.find_one({"chat_id": chat_id})
t = now(user)
for lesson in mongo.lessons_collection.find({"user_email": user['email'], "begin": {"$gte": t}}).sort([("begin", 1)]):
return lesson
return None
def process(self) -> dict:
logging.info("user %s is saying\"%s\"", self.user_id, self.message)
if "что ты умеешь" in self.message or "помощь" in self.message:
return {
"text": "Я буду тебе подсказывать расписание занятий из РУЗа. Чтобы подключить меня к своему расписанию, зайди в бота, нажми на кнопку \"Подключение Алисы\" и назови мне фразу из сообщения."
}
if self.data['session']['new']:
if self.user_id is None:
return {"text": "Пингуй дальше"}
else:
user = mongo.users_collection.find_one({"yandex_id": self.user_id})
if user is None:
return {
"text": "Привет! Я буду тебе подсказывать расписание занятий из РУЗа. Чтобы подключить меня к своему расписанию, зайди в бота, нажми на кнопку \"Подключение Алисы\" и назови мне код из сообщения."
}
else:
lesson = self.get_lesson_for_user(user['chat_id'])
if lesson is None:
return {
"text": f"В ближайшее время у тебя нет пар",
"end_session": True
}
return {
"text": f'Твое ближайшее занятие в {lesson["begin"].strftime("%A %d %B %H:%M")}: {lesson["discipline"].replace("(рус)", "").replace("(анг)", "")}',
"end_session": True
}
else:
code = self.message
try:
user = mongo.users_collection.find_one({"yandex_code": code})
except ValueError:
return {
"text": "Извини, не могу разобрать код, назови его еще раз"
}
if user is None:
return {
"text": "Извини, не могу разобрать код, назови его еще раз"
}
else:
mongo.users_collection.update_one({"yandex_code": code}, {"$set": {"yandex_id": self.user_id, "yandex_code": None}})
queues.set_task('ruz_bot_mailbox', {'text': "Алиса успешно подключена!", 'chat_id': user["chat_id"]}, 1)
lesson = self.get_lesson_for_user(user['chat_id'])
if lesson is None:
return {
"text": f"Отлично, теперь я могу подсказывать тебе расписание. В ближайшее время у тебя нет пар",
"end_session": True
}
return {
"text": f'Отлично, теперь я могу подсказывать тебе расписание. Твое ближайшее занятие в {lesson["begin"].strftime("%A %d %B %H:%M")}: {lesson["discipline"].replace("(рус)", "").replace("(анг)", "")}',
"end_session": True
}