Добавил /variant и дедлайны к заданиям

This commit is contained in:
faridik 2021-09-09 13:25:45 +03:00
parent 2d975df4b1
commit f74b970c2b
5 changed files with 70 additions and 10 deletions

View File

@ -96,6 +96,13 @@ def fingerprint():
) )
) )
@app.route("/student")
@availability
def student():
"""Возвращает оценки по id пользователя из телеграма."""
tg_id = flask.request.args.get("tg_id")
student = app.db.get_student_by_tg_id(tg_id)
return flask.jsonify(dict(student=student))
@app.route("/students") @app.route("/students")
@availability @availability

View File

@ -29,6 +29,8 @@ ASSIGNMENT_RANGES = 5
ASSIGNMENT_ALLOWS = 6 ASSIGNMENT_ALLOWS = 6
ASSIGNMENT_HOW_TO_DISPLAY = 7 ASSIGNMENT_HOW_TO_DISPLAY = 7
ASSIGNMENT_NOTES_RANGES = 8 ASSIGNMENT_NOTES_RANGES = 8
ASSIGNMENT_DEADLINE = 9
TOKEN_FILE = pathlib.Path() / ".secrets" / "token.json" TOKEN_FILE = pathlib.Path() / ".secrets" / "token.json"
CLIENT_SECRET_FILE = pathlib.Path() / ".secrets" / "client_secret.json" CLIENT_SECRET_FILE = pathlib.Path() / ".secrets" / "client_secret.json"
NON_CACHED_RANGES = ("StudentList",) NON_CACHED_RANGES = ("StudentList",)
@ -254,10 +256,8 @@ class Manager:
assignment_value = list(map(toFloat, assignment_values[student.number - 1])) assignment_value = list(map(toFloat, assignment_values[student.number - 1]))
notes_range, n_row = row[ASSIGNMENT_NOTES_RANGES].split(",") notes_range, n_row = row[ASSIGNMENT_NOTES_RANGES].split(",")
note = self.get_values(notes_range)[student.number - 1][int(n_row)] note = self.get_values(notes_range)[student.number - 1][int(n_row)]
if note == "-": note = "Замечаний по работе нет." if note == "-" \
note = "Замечаний по работе нет." else f"Замечания:\n{note}"
else:
note = f"Замечания:\n {note}"
student.add_assignment( student.add_assignment(
Assignment( Assignment(
name=row[ASSIGNMENT_NAMES], name=row[ASSIGNMENT_NAMES],
@ -267,6 +267,7 @@ class Manager:
allow_to_display=bool(int(row[ASSIGNMENT_ALLOWS])), allow_to_display=bool(int(row[ASSIGNMENT_ALLOWS])),
how_to_display=row[ASSIGNMENT_HOW_TO_DISPLAY], how_to_display=row[ASSIGNMENT_HOW_TO_DISPLAY],
notes=note, notes=note,
deadline=row[ASSIGNMENT_DEADLINE],
) )
) )

View File

@ -12,8 +12,9 @@ class Assignment(dict):
weight: float = 1, weight: float = 1,
subject: str = None, subject: str = None,
allow_to_display: bool = False, allow_to_display: bool = False,
how_to_display: str = "z,1,1", how_to_display: str = "z,10,1",
notes: str = "Замечаний по работе нет.", notes: str = "Замечаний по работе нет.",
deadline: str = "-",
): ):
self.name = name self.name = name
self.subject = subject self.subject = subject
@ -22,6 +23,7 @@ class Assignment(dict):
self.allow_to_display = allow_to_display self.allow_to_display = allow_to_display
self.how_to_display = how_to_display self.how_to_display = how_to_display
self.notes = notes self.notes = notes
self.deadline = deadline
self.uuid = uuid.uuid3(uuid.NAMESPACE_DNS, f"{name}{subject}") self.uuid = uuid.uuid3(uuid.NAMESPACE_DNS, f"{name}{subject}")
dict.__init__( dict.__init__(
self, self,
@ -33,6 +35,7 @@ class Assignment(dict):
allow_to_display=self.allow_to_display, allow_to_display=self.allow_to_display,
how_to_display=self.how_to_display, how_to_display=self.how_to_display,
notes=self.notes, notes=self.notes,
deadline=self.deadline,
uuid=self.uuid, uuid=self.uuid,
) )

View File

@ -173,6 +173,7 @@ def grades_view(update: Update, context: CallbackContext):
assignment["points"], assignment["points"],
assignment["how_to_display"], assignment["how_to_display"],
assignment["notes"], assignment["notes"],
assignment["deadline"],
), ),
parse_mode=ParseMode.HTML, parse_mode=ParseMode.HTML,
reply_markup=reply_markup, reply_markup=reply_markup,
@ -249,7 +250,7 @@ def cancel(update: Update, context: CallbackContext):
def sub(update: Update, context: CallbackContext): def sub(update: Update, context: CallbackContext):
"""Стартовое сообщение (к команде /start)""" """Подписка на обновление оценок"""
user_id = update.message.from_user.id user_id = update.message.from_user.id
username = update.message.from_user.username username = update.message.from_user.username
@ -279,7 +280,7 @@ def sub(update: Update, context: CallbackContext):
def unsub(update: Update, context: CallbackContext): def unsub(update: Update, context: CallbackContext):
"""Стартовое сообщение (к команде /start)""" """Отписка от обновления оценок"""
user_id = update.message.from_user.id user_id = update.message.from_user.id
username = update.message.from_user.username username = update.message.from_user.username
@ -309,6 +310,34 @@ def unsub(update: Update, context: CallbackContext):
msg.edit_text(text=MESSAGES.Unsub.UNSUBBED) msg.edit_text(text=MESSAGES.Unsub.UNSUBBED)
def variant(update: Update, context: CallbackContext):
"""Проверка своего варианта внутри группы"""
user_id = update.message.from_user.id
username = update.message.from_user.username
# Длинная операция, сообщим о запущенном процессе.
msg = update.message.reply_text(text=MESSAGES.Variant.START)
try:
req = requests.get(
f"{HOST}/student",
params={"tg_id": user_id},
)
data = req.json()
except requests.exceptions.RequestException:
LOG.exception("@{user_id} вызвал: Ошибка подключения к сервису Spreadsheets.")
update.message.reply_sticker(MESSAGES.Stickers.DEAD)
return
if req.status_code != 200:
LOG.error(f"Ошибка выяснения варианта, у пользователя @{username} {data}")
err = data.get("error", "")
update.message.reply_text(text=MESSAGES.Variant.failure(err))
update.message.reply_sticker(MESSAGES.Stickers.bad())
return
msg.edit_text(text=MESSAGES.Variant.get(data["student"]["number"]))
# ======================================================================= SCHED # ======================================================================= SCHED
@ -388,12 +417,14 @@ def main() -> None:
sub_handler = CommandHandler("sub", sub) sub_handler = CommandHandler("sub", sub)
unsub_handler = CommandHandler("unsub", unsub) unsub_handler = CommandHandler("unsub", unsub)
variant_handler = CommandHandler("variant", variant)
dispatcher.add_handler(start_handler) dispatcher.add_handler(start_handler)
dispatcher.add_handler(grades_handler) dispatcher.add_handler(grades_handler)
dispatcher.add_handler(broadcast_handler) dispatcher.add_handler(broadcast_handler)
dispatcher.add_handler(sub_handler) dispatcher.add_handler(sub_handler)
dispatcher.add_handler(unsub_handler) dispatcher.add_handler(unsub_handler)
dispatcher.add_handler(variant_handler)
# Начало работы бота # Начало работы бота
updater.start_polling() updater.start_polling()

View File

@ -29,7 +29,8 @@ class Messages:
TIMEOUT = "🕛 Время запроса вышло" TIMEOUT = "🕛 Время запроса вышло"
@staticmethod @staticmethod
def get(name: str, assignment: list, how_to_display: str, notes: str): def get(name: str, assignment: list, how_to_display: str,
notes: str, deadline: str):
is_float, n_cols, n_rows = how_to_display.split(",") is_float, n_cols, n_rows = how_to_display.split(",")
n_cols, n_rows = int(n_cols), int(n_rows) n_cols, n_rows = int(n_cols), int(n_rows)
summary = f"<b>{name}</b>:\n" summary = f"<b>{name}</b>:\n"
@ -48,7 +49,9 @@ class Messages:
+ "\n" + "\n"
) )
summary += f"Σ: {to_str(sum(assignment))}\n" summary += f"Σ: {to_str(sum(assignment))}\n"
summary += f"\n{notes}" if deadline != "-":
summary += f"\n🕚 Дедлайн: {deadline}\n"
summary += f"\n📝 {notes}"
return summary return summary
@staticmethod @staticmethod
@ -78,12 +81,27 @@ class Messages:
@staticmethod @staticmethod
def failure(err: str): def failure(err: str):
cases = { cases = {
"StudentNotFound": "⛔ Для отпидски от уведомлений нужно зарегистрироваться." "StudentNotFound": "⛔ Для отписки от уведомлений нужно зарегистрироваться."
+ "Команда /start поможет с регистрацией", + "Команда /start поможет с регистрацией",
"StudentAlreadyUnsubbed": "💁‍♀️ Подписка на уведомления не была оформлена или уже отменена", "StudentAlreadyUnsubbed": "💁‍♀️ Подписка на уведомления не была оформлена или уже отменена",
} }
return cases.get(err, "😟 Возникли неполадки") return cases.get(err, "😟 Возникли неполадки")
class Variant:
START = "👀 Узнаю вариант..."
@staticmethod
def get(number: int):
return f"🔢 Твой вариант: {number}"
@staticmethod
def failure(err: str):
cases = {
"StudentNotFound": "⛔ Чтобы узнать свой вариант, нужно зарегистрироваться."
+ "Команда /start поможет с регистрацией",
}
return cases.get(err, "😟 Возникли неполадки")
class Spreadsheets: class Spreadsheets:
pass pass