Esempio n. 1
0
def send_welcome(msg):
    person = session.query(Person).filter(
        Person.telegram_id == msg.chat.id).first()
    if person:
        return tb.send_message(msg.chat.id,
                               f"Привіт {person.fullname} 😊")

    tb.send_message(msg.chat.id,
                    "Привіт, ким ти є?",
                    reply_markup=identity_markup)
Esempio n. 2
0
def user_identity_query_handler(call):
    tb.edit_message_text(
        f"Ви обрали: *{call.data.split('identity_markup=')[1]}*",
        call.message.chat.id,
        call.message.message_id,
        reply_markup=None,
        parse_mode='Markdown')

    tb.answer_callback_query(callback_query_id=call.id)
    tb.send_message(call.message.chat.id,
                    "Ваше ПІБ?",
                    reply_markup=ForceReply(selective=False))
Esempio n. 3
0
def head_command(msg):
    person = session.query(Person).filter(Person.telegram_id == msg.chat.id).first()
    if not person:
        return tb.send_message(msg.chat.id, "Ви не зареєстровані")

    if person.head:
        return tb.send_message(msg.chat.id, "Ви все про себе знаєте 😊")

    faculty = person.student.group.faculty
    tb.send_message(
        msg.chat.id,
        f"Керівником практики факультету *{faculty.short}* є"
        f"[{faculty.head.person.fullname}](https://t.me/user?id={faculty.head.person.telegram_id})",
        parse_mode='Markdown'
    )
Esempio n. 4
0
def dept_command(msg):
    person = session.query(Person).filter(Person.telegram_id == msg.chat.id).first()
    if not person:
        return tb.send_message(msg.chat.id, "Ви не зареєстровані")

    args = msg.text.split()[1:]
    if len(args) == 1:
        if args[0] == 'list':
            if not person.head:
                return tb.reply_to(msg, "У вас нема доступа до цієї команди")

            students_with_dept = session.query(Student).filter(Student.has_debt).all()

            if len(students_with_dept) > 0:
                return tb.send_message(
                    msg.chat.id,
                    "Студенти які мають борг:\n"
                    f"{os.linesep.join((f'{i + 1}. {student.person.fullname}' for (i, student) in enumerate(students_with_dept)))}",
                    parse_mode='Markdown'
                )
            else:
                return tb.send_message(msg.chat.id, "Немає студентів з боргом")
        else:
            return tb.send_message(msg.chat.id, "Незнайомий аргумент, доступні: <list>")

    if person.head:
        return tb.send_message(msg.chat.id, "У керівника не може бути боргу 😂")

    tb.send_message(
        msg.chat.id,
        "У вас є борг по практиці" if person.student.has_debt else 'У вас немає боргу по практиці'
    )
Esempio n. 5
0
def inform_command(msg):
    person = session.query(Person).filter(
        Person.telegram_id == msg.chat.id).first()
    if not person:
        return tb.send_message(msg.chat.id, "Ви не зареєстровані")

    if person.student:
        return tb.send_message(msg.chat.id,
                               "Ця команда для керівників практики!")

    not_informed_students = []
    informed_students = []
    args = msg.text.split()[1:]
    if len(args) > 1:
        inform_message = ' '.join(args)
        for group in person.faculty.groups:
            for student in group.students:
                if not student.person.telegram_id:
                    not_informed_students.append(student)
                    continue

                tb.send_message(student.person.telegram_id, inform_message)
                informed_students.append(student)

    tb.send_message(
        msg.chat.id, f"Інформованих студентів: {len(informed_students)}\n"
        "Не отримали повідомленя: \n"
        f"{os.linesep.join((f'{i + 1}. {student.person.fullname}' for (i, student) in enumerate(not_informed_students)))}",
        parse_mode='Markdown')
Esempio n. 6
0
def get_schedule_file(msg):
    person = session.query(Person).filter(
        func.lower(Person.fullname) == func.lower(msg.text)).first()

    if not person:
        return tb.send_message(
            msg.chat.id,
            f"Такого ПІБ немає у базі, зв'яжіться з [адміністратором](https://t.me/Regis322)",
            parse_mode='Markdown')

    if person.telegram_id:
        return tb.send_message(
            msg.chat.id,
            "Людина за цим ПІБ вже зареэстрована, зв'яжіться з [адміністратором](https://t.me/Regis322)",
            parse_mode='Markdown')

    person.telegram_id = msg.chat.id
    session.add(person)
    session.commit()

    tb.send_message(msg.chat.id,
                    "Ваш ПІБ знайдено у базі, ваш телеграм під'єднано")
Esempio n. 7
0
def practice_terms():
    today = datetime.today()
    faculties = session.query(Faculty).all()
    for faculty in faculties:
        practice_term_start_date = faculty.practice_term.start_date.strptime(
            "%Y-%m-%d")
        practice_term_end_date = faculty.practice_term.start_date.strptime(
            "%Y-%m-%d")
        days_left_to_practice_start = (practice_term_start_date - today).days

        if 0 < days_left_to_practice_start <= 3:
            for group in faculty.groups:
                for student in group.students:
                    if student.person.telegram_id:
                        tb.send_message(
                            student.person.telegram_id,
                            f"Кількість днів до початку практики: {days_left_to_practice_start}\n\n"
                            f"*Дата початку практики*\n"
                            f"{practice_term_end_date}\n\n"
                            f"*Дата завершення практики*\n"
                            f"{practice_term_end_date}",
                            parse_mode='Markdown')
Esempio n. 8
0
def get_person_fullname(msg):
    person = session.query(Person).filter(
        Person.telegram_id == msg.chat.id).first()

    if not msg.text.isdigit():
        return tb.send_message(
            msg.chat.id,
            "Введіть порядковий номер місця практики зі списку доступних місць"
        )

    place = session.query(PlaceOfPractice).filter(
        PlaceOfPractice.id == int(msg.text)).first()

    if not place:
        return tb.send_message(
            msg.chat.id, "Не знайдено жодного місця практики за цим номером")

    person.student.place_of_practice = place
    session.commit()

    tb.send_message(msg.chat.id,
                    f"Ви успішно вибрали _{place.name}_ місцем практики",
                    parse_mode='Markdown')
Esempio n. 9
0
def places_command(msg):
    person = session.query(Person).filter(
        Person.telegram_id == msg.chat.id).first()
    if not person:
        return tb.send_message(msg.chat.id, "Ви не зареєстровані")

    args = msg.text.split()[1:]
    if len(args) == 1:
        if args[0] == 'list':
            places = session.query(PlaceOfPractice).all()

            return tb.send_message(
                msg.chat.id, "Доступні місця практики:\n"
                f"{os.linesep.join((f'{i + 1}. {place.name}' for (i, place) in enumerate(places)))}",
                parse_mode='Markdown')
        elif args[0] == 'take':
            if person.head:
                return tb.send_message(msg.chat.id,
                                       "Що, керівник, хочеш на практику?)")

            return tb.send_message(msg.chat.id,
                                   "Вкажіть номер практики:",
                                   reply_markup=ForceReply(selective=False))
        elif args[0] == 'taken':
            if person.student:
                return tb.send_message(
                    msg.chat.id, "В тебе немає доступу до цієї команди! 😡")

            determined_students = session.query(Student).filter(
                Student.place_of_practice).all()
            the_rest = session.query(Student).filter(
                not Student.place_of_practice).all()
            return tb.send_message(
                msg.chat.id,
                f"Вибрали місце практики: {len(determined_students)}\n"
                f"Не вибрали місце практики:\n"
                f"{os.linesep.join((f'{i + 1}. {student.person.fullname}' for (i, student) in enumerate(the_rest)))}",
                parse_mode='Markdown')

    return tb.send_message(
        msg.chat.id, "Незнайомий аргумент, доступні: <list>, <take>, <taken>")
Esempio n. 10
0
def schedule_command(msg):
    person = session.query(Person).filter(
        Person.telegram_id == msg.chat.id).first()
    if not person:
        return tb.send_message(msg.chat.id, "Ви не зареєстровані")

    args = msg.text.split()[1:]
    if len(args) == 1:
        if args[0] == 'change':
            if person.student:
                return tb.send_message(
                    msg.chat.id, "В тебе немає доступу до цієї команди! 😡")

            return tb.send_message(msg.chat.id,
                                   "Очікую файл розкладу",
                                   reply_markup=ForceReply(selective=False))
        elif args[0] == 'show':
            schedule = None

            if person.student:
                schedule = person.student.group.faculty.schedule
            elif person.head:
                schedule = person.head.faculty.schedule

            if not schedule:
                return tb.send_message(msg.chat.id, "Розкладу поки що немає 😢")

            return tb.send_message(
                msg.chat.id,
                f"Розклад консультацій від *{schedule.created_date.strftime('%Y-%m-%d')}*:\n\n"
                "\n".join(
                    (f"*Дата*\n"
                     f"{schedule_meeting.meeting.date}\n"
                     f"*Час початку*\n"
                     f"{schedule_meeting.meeting.start_time}\n"
                     f"*Час завершення*\n"
                     f"{schedule_meeting.meeting.end_time}\n"
                     f"*Місце проведення*\n"
                     f"{schedule_meeting.meeting.place}\n"
                     for schedule_meeting in schedule.schedule_meetings)),
                parse_mode='Markdown')

    return tb.send_message(msg.chat.id,
                           "Незнайомий аргумент, доступні: <change>, <show>")
Esempio n. 11
0
def get_schedule_file(msg):
    person = session.query(Person).filter(Person.telegram_id == msg.chat.id).first()

    # FILE SIZE CHECK
    if msg.document.file_size > 500000:
        return tb.send_message(msg.chat.id, "Файл великого розміру (0.5mb max)")

    # DOWNLOADING THE FILE
    tg_cloud_file = tb.get_file(msg.document.file_id)
    binary_data = tb.download_file(tg_cloud_file.file_path)

    # CREATING TEMPORARY FILE WRAPPER
    schedule_file = TemporaryFile()
    schedule_file.write(binary_data)

    # DELETING CURRENT SCHEDULE FROM DB
    if person.head.faculty.schedule:
        session.delete(person.head.faculty.schedule)
        session.commit()

    # PARSING TABLE WITH DAYS OF PRACTICE
    schedule = Schedule(faculty=person.head.faculty)
    try:
        schedule_sheet = openpyxl.load_workbook(schedule_file).active
        for row_idx in range(2, schedule_sheet.max_row + 1):
            schedule.schedule_meetings.append(
                ScheduleMeeting(
                    schedule=schedule,
                    meeting=Meeting(
                        date=schedule_sheet.cell(row_idx, 1).value.strftime("%Y-%m-%d"),
                        start_time=schedule_sheet.cell(row_idx, 2).value.strftime("%H:%M"),
                        end_time=schedule_sheet.cell(row_idx, 3).value.strftime("%H:%M"),
                        place=schedule_sheet.cell(row_idx, 4).value,
                    )
                )
            )
    except (ValueError, TypeError):
        tb.reply_to(msg, "Помилка у парсингу файла")
        schedule_file.close()
        return

    # INSERTING NEW SCHEDULE TO DB
    person.head.faculty.schedule = schedule
    session.commit()

    # NOTIFYING FOR SUCCESS AND CLEANING UP
    tb.reply_to(msg, "Успішно завантажено новий розклад!")
    schedule_file.close()

    # INFORMING THE STUDENTS WITH NEW SCHEDULE BY SENDING THE FILE
    not_informed_students = []
    informed_students = []
    for group in person.head.faculty.groups:
        for student in group.students:
            if not student.person.telegram_id:
                not_informed_students.append(student)
                continue

            tb.send_document(
                student.person.telegram_id,
                msg.document.file_id,
                caption="Шановний студент! Розклад консультацій змінено, лови актуальний"
            )
            informed_students.append(student)

    # NOTIFYING ABOUT THE RESULTS ABOUT STUDENTS INFORMATION
    tb.send_message(
        msg.chat.id,
        f"Інформованих студентів: {len(informed_students)}\n"
        "Не отримали повідомленя: \n"
        f"{os.linesep.join((f'{i + 1}. {student.person.fullname}' for (i, student) in enumerate(not_informed_students)))}",
        parse_mode='Markdown'
    )