summaryrefslogtreecommitdiff
path: root/states.py
blob: 94f4fef2c2ed7f1f1c9d5514a23e56632dc27854 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove

from keyboards import (
    MenuKeyboard, TasksKeyboard, TaskChosenKeyboard, ContinueKeyboard,
    AnsweringKeyboard, AdminKeyboard, PublishTasksKeyboard
)
from utils import *
import backend_api

# Typing
from telegram import Update, User, Bot


def save_state(func):
    def wrapper(bot: Bot, update: Update, user_data: dict, *args, **kwargs):
        last_state = func(bot, update, user_data, *args, **kwargs)
        backend_api.save_state(last_state, update.message.from_user.id, user_data)
        return last_state

    return wrapper


class States:
    @staticmethod
    @save_state
    def wait_for_username(bot: Bot, update: Update, user_data: dict):
        update.message.reply_text(
            "По правилам квиза ты не можешь участвовать, если у тебя не указано "
            "имя пользователя, поэтому укажи его и возвращайся как только это сделаешь!",
            reply_markup=ReplyKeyboardMarkup([['Я указал имя пользователя']])
        )
        return WAIT_FOR_USERNAME

    @staticmethod
    @save_state
    def main_menu(bot: Bot, update: Update, user_data: dict):
        user_data["chosen_task"] = None

        status_code, response = backend_api.get_attempts(
            tg_id=update.message.from_user.id,
            task_title=user_data["chosen_task"]
        )

        menu_text = [

        ]

        if status_code == 200:
            if len(response) != 0:
                menu_text.append("Твои решенные задачи:")
                for attempt in response:
                    menu_text.append(
                        f"_{attempt['task']['title']}_ "
                        f"({attempt['task']['base_score']})"
                    )
            else:
                menu_text.append("У тебя еще нет решенных задач")
        else:
            menu_text.append(
                "К сожалению, не удалось получить данные о твоих попытках =(\n"
                "Попробуй обратиться к боту чуть позже."
            )

        menu_text.append("\n*Итоговый счет*: 0\n*Место в топе*: 0")

        update.message.reply_text("\n".join(menu_text), parse_mode="Markdown")

        update.message.reply_text(
            "Выбери следующее действие...",
            reply_markup=ReplyKeyboardMarkup(MenuKeyboard.get_keyboard(update.message.from_user.id))
        )

        return MAIN_MENU

    @staticmethod
    @save_state
    def choose_task(bot: Bot, update: Update, user_data: dict):
        user_data["chosen_task"] = None

        status, published = backend_api.get_published_tasks()
        if len(published) == 0:
            update.message.reply_text(
                "Пока что не опубликовано ни одной задачи =(",
                reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
            )

            # okay this is epic (pile of shit)
            return ANSWER_RIGHT
        else:
            update.message.reply_text(
                "Какую задачу ты хочешь сдать?",
                reply_markup=ReplyKeyboardMarkup(TasksKeyboard.get_keyboard())
            )
            return TASK_CHOOSING

    @staticmethod
    @save_state
    def top_10(bot: Bot, update: Update, user_data: dict):
        update.message.reply_text("какая то хуйня")
        return MAIN_MENU

    @staticmethod
    @save_state
    def rules(bot: Bot, update: Update, user_data: dict):
        update.message.reply_text("какая то хуйня")
        return MAIN_MENU

    @staticmethod
    @save_state
    def show_task(bot: Bot, update: Update, user_data: dict):
        if "chosen_task" in user_data and user_data["chosen_task"] is not None:
            task_title = user_data["chosen_task"]
        else:
            task_title = update.message.text
            user_data["chosen_task"] = task_title

        status_code, tasks_response = backend_api.get_published_tasks()
        if status_code != 200:
            update.message.reply_text(
                "Произошла ошибка в работе квиза. Мы уже работаем над её устранением!",
                reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
            )

            return MAIN_MENU

        titles = {task.get("title"): task for task in tasks_response}

        if task_title not in titles.keys():
            update.message.reply_text(
                "Такой задачи не найдено, попробуй ввести другое название!",
                reply_markup=ReplyKeyboardMarkup(TasksKeyboard.get_keyboard())
            )

            return TASK_CHOOSING

        # status_code, task = backend_api.get_task(task_title)
        task = titles[task_title]

        message = '\n'.join([
            f"*{task['title']}*",
            f"{task['statement']}",
            "",
            f"_Теги: {task['tags']}_",
        ])
        keyboard = TaskChosenKeyboard.get_keyboard()

        update.message.reply_text(
            message, parse_mode="Markdown",
            reply_markup=ReplyKeyboardMarkup(keyboard)
        )

        return TASK_SHOWN

    @staticmethod
    @save_state
    def type_answer(bot: Bot, update: Update, user_data: dict):
        status_code, response = backend_api.get_attempts(
            tg_id=update.message.from_user.id,
            task_title=user_data["chosen_task"]
        )
        if len(response) != 0:
            update.message.reply_text(
                "Ты уже решил эту задачу! Выбери другую.",
                reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
            )

            return TASK_CHOOSING

        else:
            update.message.reply_text(
                "Вводи свой ответ, я его проверю.",
                reply_markup=ReplyKeyboardMarkup(AnsweringKeyboard.get_keyboard())
            )
            return ANSWERING

    @staticmethod
    @save_state
    def accept_answer(bot: Bot, update: Update, user_data: dict):
        answer = update.message.text
        status_code, task = backend_api.get_task(user_data["chosen_task"])
        if status_code == 200:
            backend_api.create_attempt(update.message.from_user.id, user_data["chosen_task"], answer)

            if answer == task["answer"]:
                update.message.reply_text(
                    "Ты ввел правильный ответ! Возвращайся к другим задачам",
                    reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
                )

                return ANSWER_RIGHT
            else:
                update.message.reply_text(
                    "К сожалению, твой ответ неверный =(",
                    reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
                )

                return ANSWER_WRONG

        else:
            update.message.reply_text(
                "Произошла ошибка в работе квиза. Мы уже работаем над её устранением!",
                reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
            )

            return ANSWER_RIGHT


class AdminStates:
    @staticmethod
    @save_state
    def admin_panel(bot: Bot, update: Update, user_data: dict):
        status_code, data = backend_api.get_profile(update.message.from_user.id)
        if status_code != 200:
            update.message.reply_text(
                "Не удалось аутентифицировать пользователя. Доступ запрещен.",
                reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
            )

            return ADMIN_ACCESS_DENIED

        if not data["is_admin"]:
            update.message.reply_text(
                "Вы не являетесь администратором. Доступ запрещен.",
                reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
            )

            return ADMIN_ACCESS_DENIED

        update.message.reply_text(
            "Выберите действие",
            reply_markup=ReplyKeyboardMarkup(AdminKeyboard.get_keyboard())
        )

        return ADMIN_MENU

    @staticmethod
    @save_state
    def choose_task_hide(bot: Bot, update: Update, user_data: dict):
        update.message.reply_text(
            "Выберите задачу, которую хотите скрыть",
            reply_markup=ReplyKeyboardMarkup(PublishTasksKeyboard.get_keyboard())
        )

        return ADMIN_TASK_CHOOSE_HIDE

    @staticmethod
    @save_state
    def choose_task_publish(bot: Bot, update: Update, user_data: dict):
        update.message.reply_text(
            "Выберите задачу, которую хотите опубликовать",
            reply_markup=ReplyKeyboardMarkup(PublishTasksKeyboard.get_keyboard())
        )

        return ADMIN_TASK_CHOOSE_PUBLISH

    @staticmethod
    @save_state
    def hide_task(bot: Bot, update: Update, user_data: dict):
        title = update.message.text
        status, data = backend_api.hide_task(title)
        if status != 200:
            update.message.reply_text(
                "Не удалось скрыть задачу.",
                reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
            )
        else:
            update.message.reply_text(
                "Задача была скрыта.",
                reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
            )

        return ADMIN_TASK_PUBLISHED

    @staticmethod
    @save_state
    def publish_task(bot: Bot, update: Update, user_data: dict):
        title = update.message.text
        status, data = backend_api.publish_task(title)
        if status != 200:
            update.message.reply_text(
                "Не удалось опубликовать задачу.",
                reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
            )
        else:
            update.message.reply_text(
                "Задача была опубликована.",
                reply_markup=ReplyKeyboardMarkup(ContinueKeyboard.get_keyboard())
            )

        return ADMIN_TASK_PUBLISHED