diff --git a/daemons/api.py b/daemons/api.py index 0f1f53c..3018591 100644 --- a/daemons/api.py +++ b/daemons/api.py @@ -1,6 +1,7 @@ -from flask import Flask +from flask import Flask, request import settings +from helpers.alice import Processor from helpers.mongo import mongo @@ -30,4 +31,18 @@ def api(): f"Пользователей из Санкт-Петербурга (регистрация): {mongo.users_collection.count_documents({'campus': 'Санкт-Петербург', 'hse_id': {'$ne': None}})}
" return text + @app.route('/alice', methods=['POST']) + def alice(): + req = request.json + processor = Processor(req) + response = { + "version": req['version'], + "session": req['session'], + "response": { + "end_session": False + } + } + response['response'].update(processor.process()) + return response + app.run(host="0.0.0.0", port=1238, debug=settings.DEBUG) diff --git a/helpers/alice.py b/helpers/alice.py new file mode 100644 index 0000000..4eb4be1 --- /dev/null +++ b/helpers/alice.py @@ -0,0 +1,59 @@ +from daemons.bot import bot +from helpers.mongo import mongo + + +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): + ... + + + def process(self) -> dict: + user = None + if self.data['session']['new']: + if self.user_id is not None: + return {} + 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']}: {lesson['discipline']}", + "end_session": True + } + else: + hse_id = self.message.replace(' ', '') + user = mongo.users_collection.find_one({"hse_id": int(hse_id)}) + if user is None: + return { + "text": "Извини, не могу разобрать код, назови его еще раз" + } + else: + mongo.users_collection.update_one({"hse_id": int(hse_id)}, {"$set": {"yandex_id": self.user_id}}) + bot.send_message(user['chat_id'], "Алиса успешно подключена!") + lesson = self.get_lesson_for_user(user['chat_id']) + if lesson is None: + return { + "text": f"Отлично, теперь я могу подсказывать тебе расписание. В ближайшее время у тебя нет пар", + "end_session": True + } + return { + "text": f"Отлично, теперь я могу подсказывать тебе расписание. Твое ближайшее занятие {lesson['begin']}: {lesson['discipline']}", + "end_session": True + } \ No newline at end of file diff --git a/helpers/answer.py b/helpers/answer.py index 1034608..bd5cce5 100644 --- a/helpers/answer.py +++ b/helpers/answer.py @@ -212,6 +212,11 @@ class Answer(BaseAnswer): bot.send_message(user.chat_id, "Ты уверен что хочешь сбросить все настройки и больше не получать уведомления?", reply_markup=yes_no_keyboard()) self.set_state(user, "reset") return + elif message.text == "Подключение Алисы": + if user.yandex_id is None: + text = "Для того, чтобы подключить Яндекс.Алису, вызови навык \"Расписание вышки\" и назови этот код: " + str(user.hse_id) + else: + text = "Янедкс.Алиса уже подключена. Чтобы узнать ближайшую пару, вызови навык \"Расписание вышки\"" else: text = "Я не понимаю такой команды, используй кнопки." bot.send_message( diff --git a/helpers/keyboards.py b/helpers/keyboards.py index a9825de..f0e5f80 100644 --- a/helpers/keyboards.py +++ b/helpers/keyboards.py @@ -7,6 +7,7 @@ def main_keyboard(): kb.row("Расписание на неделю") kb.row("Напоминания о парах") kb.row("Ежедневные уведомления") + kb.row("Подключение Алисы") kb.row("Сброс настроек") return kb diff --git a/helpers/models.py b/helpers/models.py index 905681b..9ff82cd 100644 --- a/helpers/models.py +++ b/helpers/models.py @@ -20,6 +20,7 @@ class User: campus: str = "Москва" daily_notify_today: bool = True first_lesson_notify: Optional[float] = None + yandex_id: Optional[str] = None class Meta: unknown = EXCLUDE