Ejemplo n.º 1
0
def registration(uid, key, data=""):
    if data == '':
        return 'Вы не указали где хотите зарегистрироваться'

    try:
        with ScheduleDB(app.config) as db:
            organizations = db.get_similar_organizations(data)

        if len(organizations) != 0:
            if organizations[0][2] > 0.8:
                message = 'Вы зарегистрированны в: {}'.format(
                    organizations[0][1])
            else:
                message = 'Вы зарегистрированны в наиболее совпадающей с запросом группе: {}\n-----\nДругие похожие:\n'.format(
                    organizations[0][1])
                for org in organizations:
                    message += "{}\n".format(org[1])

            with ScheduleDB(app.config) as db:
                user = db.find_user(uid)
                if user:
                    db.update_user(uid, " ", " ", organizations[0][0])
                else:
                    db.add_user(uid, " ", " ", organizations[0][0])
            message += '\n\n Напишите "помощь", чтобы узнать доступные команды'

            return message
        else:
            return 'Случилось что то странное, попробуйте ввести команду заново'
    except BaseException as e:
        return 'Случилось что то странное, попробуйте ввести команду заново'
Ejemplo n.º 2
0
def registration_alt(uid, key, data=''):
    # Статистика
    track(app.config['STATISTIC_TOKEN'], uid, data, 'registration_alt')

    if data == '':
        return registration_alt_help_message, '', ''
    try:
        with ScheduleDB(app.config) as db:
            organizations = db.get_similar_organizations(data)

        if len(organizations) != 0:
            message = registration_success_message
            if organizations[0][2] > 0.8:
                message += '\n\nВы зарегистрированны в: {}'.format(organizations[0][1])
            else:
                message += '\n\nВы зарегистрированны в наиболее совпадающей с запросом группе: {}\n' \
                          '-----\nДругие похожие:\n'.format(organizations[0][1])
                for org in organizations:
                    message += "{}\n".format(org[1])

            with ScheduleDB(app.config) as db:
                user = db.find_user(uid)
                if user:
                    db.update_user(uid, " ", " ", organizations[0][0])
                else:
                    db.add_user(uid, " ", " ", organizations[0][0])

            return message, '', ''
        else:
            return error_message, '', ''
    except BaseException as e:
        app.logger.warning('registration_alt: {}'.format(str(e)))
        return error_message, '', ''
Ejemplo n.º 3
0
    def get(self, organization, faculty, group):
        # Return the exams list
        try:
            with ScheduleDB(app.config) as db:
                db_data = db.get_group(organization, faculty, group)

            if db_data is None:
                return make_response(jsonify(self.error["unknownGroup"]), 400)

            tag = db_data[1]

            with ScheduleDB(app.config) as db:
                schedule = db.get_exams(tag)

            data = []
            for row in schedule:
                data.append({
                    'day': row[0],
                    'title': del_end_space(row[1]),
                    'classroom': del_end_space(row[2]),
                    'lecturer': del_end_space(row[3])
                })

            return make_response(jsonify(data), 200)
        except BaseException as e:
            app.logger.warning('ExamsApi get: {}'.format(str(e)))
            return make_response(jsonify(self.error["getFail_unknown"]), 400)
Ejemplo n.º 4
0
def auto_posting_off(uid, key, arg=""):
    # Если пользователя нет в базе, то ему выведет предложение зарегистрироваться
    try:
        with ScheduleDB(app.config) as db:
            user = db.find_user(uid)
        if not user or user[0] == '':
            message = "Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации:\n"
            message += 'Введите команду(без кавычек):\n\nрегистрация "название вуза" "факультет" "группа"\n\n'
            message += 'Если вы допустите ошибку, то просто наберите команду заново.\n'
            return message
    except BaseException as e:
        return 'Случилось что то странное, попробуйте ввести команду заново'

    try:
        with ScheduleDB(app.config) as db:
            user = db.find_user(uid)
            if user:
                if db.set_auto_post_time(uid, None, None):
                    return 'Автоматическая отправка расписания успешно отключена'
                else:
                    return 'Случилось что то странное, попробуйте ввести команду заново'
            else:
                return 'Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации'
    except BaseException as e:
        return 'Случилось что то странное, попробуйте ввести команду заново'
def auto_posting(current_time):
    today = datetime.now()
    week_type = (today.isocalendar()[1] + 1) % 2

    if datetime.weekday(today) == 6:
        today += timedelta(days=1)
        week_type = (week_type + 1) % 2

    day = [helpers.daysOfWeek[datetime.weekday(today)]]

    # Выборка пользователей из базы у которых установлена отправка расписния на текущий день
    with ScheduleDB(app.config) as db:
        users = db.find_users_where(auto_posting_time=current_time, is_today=True)

    if users is None:
        return None
    try:
        count = 0
        for user in users:
            uid = user[0]
            tag = user[1]

            schedule = create_schedule_text(tag, day[0], week_type)
            vkapi.send_message(uid, app.config['TOKEN'], schedule)
            count += 1
            if count > 20:
                sleep(1)

            # Логирование
    except BaseException as e:
        pass

    # Выборка пользователей из базы у которых установлена отправка расписния на завтрашний день,
    # если сегодня воскресенье, то расписание будет отправляться на понедельник.
    if datetime.weekday(datetime.now()) != 6:
        today += timedelta(days=1)

    day = [helpers.daysOfWeek[datetime.weekday(today)]]

    with ScheduleDB(app.config) as db:
        users = db.find_users_where(auto_posting_time=current_time, is_today=False)

    if users is None:
        return None
    try:
        count = 0
        for user in users:
            uid = user[0]
            tag = user[1]

            schedule = create_schedule_text(tag, day[0], week_type)
            vkapi.send_message(uid, app.config['TOKEN'], schedule)
            count += 1
            if count > 20:
                sleep(1)

            # Логирование
    except BaseException as e:
        pass
Ejemplo n.º 6
0
def auto_posting_on(uid, key, arg=""):
    # Если пользователя нет в базе, то ему выведет предложение зарегистрироваться
    try:
        with ScheduleDB(app.config) as db:
            user = db.find_user(uid)
        if not user or user[0] == '':
            message = "Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации:\n"
            message += 'Введите команду(без кавычек):\n\nрегистрация "название вуза" "факультет" "группа"\n\n'
            message += 'Если вы допустите ошибку, то просто наберите команду заново.\n'
            return message
    except BaseException as e:
        return 'Случилось что то странное, попробуйте ввести команду заново'

    data = arg.split(' ', maxsplit=1)
    time = data[0]
    type = ''

    if len(data) == 2:
        type = data[1]
    try:
        if re.match(time, r'\d{1,2}:\d\d'):
            raise BaseException
    except:
        return "Вы отправили пустую строку или строку неправильного формата. Правильный формат ЧЧ:ММ"

    try:
        with ScheduleDB(app.config) as db:
            user = db.find_user(uid)

            if user and user[0] != "":
                hour = ''.join(
                    filter(lambda x: x.isdigit(),
                           re.split(r':', time)[0]))
                minutes = ''.join(
                    filter(lambda x: x.isdigit(),
                           re.split(r':', time)[1]))

                if difflib.SequenceMatcher(None, type, 'сегодня').ratio() > \
                        difflib.SequenceMatcher(None, type, 'завтра').ratio() or type == '':
                    is_today = True
                else:
                    is_today = False

                # Проверка на соответствие введённых пользователем данных принятому формату
                if not hour.isdigit() or not minutes.isdigit():
                    return 'Вы отправили пустую строку или строку неправильного формата. Правильный формат ЧЧ:ММ'

                if db.set_auto_post_time(uid, (hour + ":" + minutes + ":" +
                                               "00").rjust(8, '0'), is_today):
                    return 'Время установлено'
                else:
                    return 'Случилось что то странное, попробуйте ввести команду заново'
            else:
                return 'Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации'
    except BaseException as e:
        return 'Случилось что то странное, попробуйте ввести команду заново'
Ejemplo n.º 7
0
    def post(self, organization, faculty, group):
        # Add schedule to DB
        try:
            with ScheduleDB(app.config) as db:
                db_data = db.get_group(organization, faculty, group)

            if db_data is None:
                return make_response(jsonify(self.error["unknownGroup"]), 400)

            tag = db_data[1]
            body = request.get_json().get('data', None)

            if body is None:
                return make_response(jsonify(self.error["postFail_empty"]),
                                     400)

            answer = {'failed': []}
            with ScheduleDB(app.config) as db:
                for lecture in body:
                    # Обязательные параметры запроса
                    day = lecture.get('day', None)
                    number = lecture.get('number', None)
                    week_type_text = lecture.get('week_type', None)
                    title = lecture.get('title', None)

                    if week_type_text == 'odd':
                        week_type = 0
                    elif week_type_text == 'even':
                        week_type = 1
                    elif week_type_text == 'all':
                        week_type = 2
                    else:
                        week_type = None

                    # Необязательные параметры
                    classroom = lecture.get('classroom', None)
                    time_start = lecture.get('time_start', None)
                    time_end = lecture.get('time_end', None)
                    lecturer = lecture.get('lecturer', None)

                    if day is None or number is None or week_type is None or title is None:
                        answer['failed'].append(lecture)
                        continue
                    else:
                        if not db.add_lesson(tag, day, number, week_type,
                                             time_start, time_end, title,
                                             classroom, lecturer):
                            answer['failed'].append(lecture)
            return make_response(jsonify(answer), 200)
        except BaseException as e:
            app.logger.warning('ScheduleApi post: {}'.format(str(e)))
            return make_response(jsonify(self.error["postFail"]), 400)
Ejemplo n.º 8
0
def exams(uid, key, data=""):
    # Статистика
    track(app.config['STATISTIC_TOKEN'], uid, key, 'exams')

    try:
        is_registered, message, user = registration_check(uid)
        if not is_registered:
            return message, '', ''

        with ScheduleDB(app.config) as db:
            exams_list = db.get_exams(user[0])

        message = ''
        for exam in exams_list:
            message += exam[0].strftime('%d.%m.%Y') + ":\n"

            title = ' '.join(str(exam[1]).split())
            lecturer = ' '.join(str(exam[2]).split())
            classroom = ' '.join(str(exam[3]).split())

            message += title + ' | ' + lecturer + ' | ' + classroom + "\n"
            message += "------------\n"
        if len(message) == 0:
            message = 'Похоже расписания экзаменов для вашей группы нет в базе'
    except BaseException as e:
        app.logger.warning('exams: {}'.format(str(e)))
        return error_message, '', ''
    return message, '', ''
Ejemplo n.º 9
0
    def delete(self, organization, faculty, group):
        # Delete the entire exams
        try:
            with ScheduleDB(app.config) as db:
                db_data = db.get_group(organization, faculty, group)

            if db_data is None:
                return make_response(jsonify(self.error["unknownGroup"]), 400)

            tag = db_data[1]

            with ScheduleDB(app.config) as db:
                db.delete_exams(tag)

            return make_response(jsonify({}), 200)
        except BaseException as e:
            app.logger.warning('ExamsApi delete: {}'.format(str(e)))
            return make_response(jsonify(self.error["deleteFail"]), 400)
Ejemplo n.º 10
0
def report(uid, key, arg=""):
    if arg != '':
        with ScheduleDB(app.config) as db:
            if db.add_report(uid, arg):
                return "Сообщение принято"
            else:
                return "Случилось что то странное, попробуйте ввести команду заново"
    else:
        return 'Вы отправили пустую строку. Пример: сообщение "ваше сообщение"'
Ejemplo n.º 11
0
 def delete(self, organization, faculty):
     # Delete the entire organizations
     try:
         with ScheduleDB(app.config) as db:
             db.delete_faculty(organization, faculty)
         return make_response(jsonify({}), 200)
     except BaseException as e:
         app.logger.warning('FacultyApi delete: {}'.format(str(e)))
         return make_response(jsonify(self.error["deleteFail"]), 400)
Ejemplo n.º 12
0
    def get(self, organization, faculty, group):
        # Return the schedule list
        try:
            with ScheduleDB(app.config) as db:
                db_data = db.get_group(organization, faculty, group)

            if db_data is None:
                return make_response(jsonify(self.error["unknownGroup"]), 400)

            tag = db_data[1]

            with ScheduleDB(app.config) as db:
                schedule = db.get_schedule(tag)

            data = []
            for row in schedule:
                week_type = row[3]
                if week_type == 0:
                    week_type_text = 'odd'
                elif week_type == 1:
                    week_type_text = 'even'
                elif week_type == 2:
                    week_type_text = 'all'
                else:
                    week_type_text = ''

                data.append({
                    'day': del_end_space(row[7]),
                    'number': row[0],
                    'week_type': week_type_text,
                    'title': del_end_space(row[1]),
                    'classroom': del_end_space(row[2]),
                    'lecturer': del_end_space(row[6]),
                    'time_start': str(row[4])[:5],
                    'time_end': str(row[5])[:5]
                })

            return make_response(jsonify(data), 200)
        except BaseException as e:
            app.logger.warning('ScheduleApi get: {}'.format(str(e)))
            return make_response(jsonify(self.error["getFail"]), 400)
Ejemplo n.º 13
0
def report(uid, key, arg=""):
    # Статистика
    track(app.config['STATISTIC_TOKEN'], uid, arg, 'report')

    if arg != '':
        with ScheduleDB(app.config) as db:
            if db.add_report(uid, arg):
                return report_ok_message, '', ''
            else:
                return error_message, '', ''
    else:
        return report_help_message, '', ''
Ejemplo n.º 14
0
def registration_check(uid):
    is_registered = True
    message = ''

    with ScheduleDB(app.config) as db:
        user = db.find_user(uid)
    if not user or user[0] is None:
        user = None
        is_registered = False
        message = registration_message

    return is_registered, message, user
Ejemplo n.º 15
0
    def post(self, organization, faculty, group):
        # Add exams to DB
        try:
            with ScheduleDB(app.config) as db:
                db_data = db.get_group(organization, faculty, group)

            if db_data is None:
                return make_response(jsonify(self.error["unknownGroup"]), 400)

            tag = db_data[1]
            body = request.get_json().get('data', None)

            if body is None:
                return make_response(jsonify(self.error["postFail_empty"]),
                                     400)

            answer = {'failed': []}
            with ScheduleDB(app.config) as db:
                for exam in body:
                    # Обязательные параметры запроса
                    day = exam.get('day', None)
                    title = exam.get('title', None)

                    # Необязательные параметры
                    classroom = exam.get('classroom', None)
                    lecturer = exam.get('lecturer', None)

                    if day is None or title is None:
                        answer['failed'].append(exam)
                        continue
                    else:
                        if not db.add_exam(tag, title, classroom, lecturer,
                                           day):
                            answer['failed'].append(exam)
            return make_response(jsonify(answer), 200)
        except BaseException as e:
            app.logger.warning('ExamsApi post: {}'.format(str(e)))
            return make_response(jsonify(self.error["postFail"]), 400)
Ejemplo n.º 16
0
    def get(self, organization, faculty, group):
        # Return the groups list
        try:
            with ScheduleDB(app.config) as db:
                db_data = db.get_group(organization, faculty, group)

            if db_data is None:
                return make_response(jsonify(self.error["getFail"]), 400)

            tag = db_data[1]
            return make_response(jsonify(tag), 200)
        except BaseException as e:
            app.logger.warning('GroupApi get: {}'.format(str(e)))
            return make_response(jsonify(self.error["getFail"]), 400)
Ejemplo n.º 17
0
def message_deny_handler(data):
    uid = data['user_id']

    # Статистика
    track(app.config['STATISTIC_TOKEN'], uid, 'message_deny', 'message_deny')

    try:
        is_registered, message, user = registration_check(uid)
        if not is_registered:
            return
        with ScheduleDB(app.config) as db:
            db.set_auto_post_time(uid, None, None)
    except BaseException as e:
        app.logger.warning('message_deny: {}'.format(str(e)))
Ejemplo n.º 18
0
def registration_stage_4(uid, key, data):
    # Статистика
    track(app.config['STATISTIC_TOKEN'], uid, data, 'registration-stage-4')

    try:
        with ScheduleDB(app.config) as db:
            row = db.get_group(key)

        if len(row) == 0:
            return error_message, ''

        message = registration_success_message

        with ScheduleDB(app.config) as db:
            user = db.find_user(uid)
            if user:
                db.update_user(uid, " ", " ", str(row[0][1]))
            else:
                db.add_user(uid, " ", " ", str(row[0][1]))

        return message, get_main_keyboard(is_registered=True)
    except BaseException as e:
        app.logger.warning('registration_stage_4: {}'.format(str(e)))
        return error_message, ''
Ejemplo n.º 19
0
def create_schedule_text(tag, day, week_type=-1):
    result = []
    schedule = ""
    is_empty = True
    try:
        with ScheduleDB(app.config) as db:
            data = db.get_schedule(tag, day, week_type)

        schedule += "🔎 | {}: {}\n\n".format(
            helpers.daysOfWeek_rus[day], print_week_type(week_type))
        index = 0
        while index < len(data):
            is_empty = False
            row = data[index]

            title = ' '.join(str(row[1]).split())
            classroom = ' '.join(str(row[2]).split())

            schedule += '⏳ | {} пара: '.format(str(row[0]))
            # Этот блок нужен для вывода тех занятий, где занятия по числителю и знамнателю различаются
            if index != len(data) - 1:
                # Сравнивается порядковый номер занятия данной и следующей строки и если они равны,
                # то они выводятся вместе
                if data[index + 1][0] == row[0]:
                    schedule += '{0} {1} {2}\n'.format(title, classroom, print_type(row[3], week_type))

                    index += 1
                    row = data[index]
                    title = ' '.join(str(row[1]).split())
                    classroom = ' '.join(str(row[2]).split())

                    schedule += '&#12288;&#10;&#12288;' \
                                '&#12288;&#10;&#12288;' \
                                '&#12288;&#10;{0} {1} {2}\n\n'.format(title, classroom, print_type(row[3], week_type))
                else:
                    schedule += '{0} {1} {2}\n\n'.format(title, classroom, print_type(row[3], week_type))
            else:
                schedule += '{0} {1} {2}\n\n'.format(title, classroom, print_type(row[3], week_type))

            index += 1
        result.append(schedule)
        result.append(is_empty)
    except BaseException as e:
        app.logger.warning('create_schedule_text: {}'.format(str(e)))
    finally:
        if len(result) != 2:
            result = ['', True]
        return result
Ejemplo n.º 20
0
def auto_posting_on(uid, key, arg=""):
    # Статистика
    track(app.config['STATISTIC_TOKEN'], uid, arg, 'auto_posting_on')

    data = arg.split(' ', maxsplit=1)
    time = data[0]
    type = ''

    if len(data) == 2:
        type = data[1]
    try:
        if re.match(time, r'\d{1,2}:\d\d'):
            raise BaseException
    except:
        return auto_posting_on_help_message, '', ''

    try:
        is_registered, message, user = registration_check(uid)
        if not is_registered:
            return message, '', ''

        with ScheduleDB(app.config) as db:
            hour = ''.join(
                filter(lambda x: x.isdigit(),
                       re.split(r':', time)[0]))
            minutes = ''.join(
                filter(lambda x: x.isdigit(),
                       re.split(r':', time)[1]))

            if difflib.SequenceMatcher(None, type, 'сегодня').ratio() > \
                    difflib.SequenceMatcher(None, type, 'завтра').ratio() or type == '':
                is_today = True
            else:
                is_today = False

            # Проверка на соответствие введённых пользователем данных принятому формату
            if not hour.isdigit() or not minutes.isdigit():
                return auto_posting_on_help_message, '', ''

            if db.set_auto_post_time(uid,
                                     (hour + ":" + minutes + ":" + "00").rjust(
                                         8, '0'), is_today):
                return 'Время установлено', '', ''
            else:
                return error_message, '', ''
    except BaseException as e:
        app.logger.warning('auto_posting_on: {}'.format(str(e)))
        return error_message, '', ''
Ejemplo n.º 21
0
def auto_posting_off(uid, key, arg=""):
    # Статистика
    track(app.config['STATISTIC_TOKEN'], uid, arg, 'auto_posting_off')

    try:
        is_registered, message, user = registration_check(uid)
        if not is_registered:
            return message, '', ''

        with ScheduleDB(app.config) as db:
            if db.set_auto_post_time(uid, None, None):
                return auto_posting_off_message, '', ''
            else:
                return error_message, '', ''
    except BaseException as e:
        app.logger.warning('auto_posting_off: {}'.format(str(e)))
        return error_message, '', ''
def registration_stage_2(uid, key, data):
    # Статистика
    track(app.config['STATISTIC_TOKEN'], uid, data, 'registration-stage-2')

    try:
        with ScheduleDB(app.config) as db:
            result = db.get_faculty(key)

        if len(result) == 0:
            return error_message, ''

        if len(result) > 8:
            buttons_in_row = 3
        else:
            buttons_in_row = 2

        buttons = []
        for i in range(len(result)):
            row = result[i]
            if (i % buttons_in_row) == 0:
                buttons.append([])
            buttons[int(i / buttons_in_row)].append({
                "action": {
                    "type": "text",
                    "label": str(row[0]),
                    "payload": {
                        "registration":
                        "reg:stage 3:{0}".format(
                            str(row[1])[:organization_field_length +
                                        faculty_field_length])
                    }
                },
                "color": "default"
            })
        buttons.append([
            create_button_negative('Назад', {'registration': 'reg:stage 1:'})
        ])

        return 'Выберите курс:', json.dumps(
            {
                "one_time": False,
                "buttons": buttons
            }, ensure_ascii=False)
    except BaseException as e:
        app.logger.warning('registration_stage_2: {}'.format(str(e)))
        return error_message, ''
Ejemplo n.º 23
0
    def get(self, organization, faculty):
        # Return the groups list
        try:
            with ScheduleDB(app.config) as db:
                db_data = db.get_group_list(organization, faculty)

            if db_data is None:
                return make_response(jsonify(self.error["getFail"]), 400)

            data = []
            for row in db_data:
                data.append(del_end_space(row[0]))

            return make_response(jsonify(data), 200)
        except BaseException as e:
            app.logger.warning('FacultyApi get: {}'.format(str(e)))
            return make_response(jsonify(self.error["getFail"]), 400)
Ejemplo n.º 24
0
    def post(self, organization, faculty, group):
        # Return the groups list
        try:
            with ScheduleDB(app.config) as db:
                db_data = db.get_group(organization, faculty, group)

                if db_data is not None:
                    return make_response(jsonify(self.error["postFail_exist"]), 400)

                tag = db.add_organization(organization, faculty, group)

            if tag is not None:
                return make_response(jsonify(tag), 200)
            else:
                return make_response(jsonify(self.error["postFail_unknown"]), 400)
        except BaseException as e:
            app.logger.warning('GroupApi post: {}'.format(str(e)))
            return make_response(jsonify(self.error["postFail_unknown"]), 400)
Ejemplo n.º 25
0
def user_info(uid, key, data=""):
    # Статистика
    track(app.config['STATISTIC_TOKEN'], uid, key, 'user_info')

    # Если пользователя нет в базе, то ему выведет предложение зарегистрироваться
    try:
        is_registered, message, user = registration_check(uid)

        if not is_registered:
            return user_info_title_message, '', get_user_info_keyboard(
                is_registered=False)
        else:
            with ScheduleDB(app.config) as db:
                info = db.get_user_info(uid)

            if info is None:
                faculty = 'Пусто'
                group = 'Пусто'
                ap_time = 'Не установлено'
                ap_type = 'Не установлено'
            else:
                faculty = ' '.join(str(
                    info[1]).split()) if len(info) >= 2 else 'Пусто'
                group = ' '.join(str(
                    info[2]).split()) if len(info) >= 3 else 'Пусто'

                if len(info) >= 5 and info[3] is not None:
                    ap_time = str(
                        info[3]) if info[3] is not None else 'Не установлено'
                    ap_type = 'На сегодня' if info[4] else 'На завтра'
                else:
                    ap_time = 'Не установлено'
                    ap_type = 'Не установлено'

            message = '{}\n{}: {}\n{}: {}\n{}: {}\n{}: {}'.format(
                user_info_title_message, user_info_faculty_message, faculty,
                user_info_group_message, group, user_info_ap_time_message,
                ap_time, user_info_ap_type_message, ap_type)
            return message, '', get_user_info_keyboard(is_registered=True)
    except BaseException as e:
        app.logger.warning('user_info: {}'.format(str(e)))
        return error_message, '', ''
Ejemplo n.º 26
0
def create_schedule_text(tag, day, week_type=-1):
    result = []
    schedule = ""
    try:
        with ScheduleDB(app.config) as db:
            data = db.get_schedule(tag, day, week_type)

        schedule += ">{0}:\n".format(helpers.daysOfWeek_rus[day])
        index = 0
        while index < len(data):
            row = data[index]

            schedule += str(row[0]) + " пара:\n"
            # Этот блок нужен для вывода тех занятий, где занятия по числителю и знамнателю различаются
            if index != len(data) - 1:
                # Сравнивается порядковый номер занятия данной и следующей строки и если они равны,
                # то они выводятся вместе
                if data[index + 1][0] == row[0]:
                    schedule += '{0} {1} {2}\n'.format(
                        str(row[1]), str(row[2]),
                        print_type(row[3], week_type))
                    index += 1
                    row = data[index]
                    schedule += '{0} {1} {2}\n'.format(
                        str(row[1]), str(row[2]),
                        print_type(row[3], week_type))
                else:
                    schedule += '{0} {1} {2}\n'.format(
                        str(row[1]), str(row[2]),
                        print_type(row[3], week_type))
            else:
                schedule += '{0} {1} {2}\n'.format(
                    str(row[1]), str(row[2]), print_type(row[3], week_type))

            schedule += "------------\n"
            index += 1
        result.append(schedule)
    except:
        pass
    finally:
        return result
def registration_stage_1(uid, key, data):
    # Статистика
    track(app.config['STATISTIC_TOKEN'], uid, data, 'registration-stage-1')

    try:
        with ScheduleDB(app.config) as db:
            result = db.get_organizations()
        if len(result) == 0:
            return error_message, ''

        buttons = []

        for row in result:
            buttons.append(
                [
                    {
                        "action": {
                            "type": "text",
                            "label": str(row[0]),
                            "payload": {
                                "registration": "reg:stage 2:{0}".format(str(row[1])[:organization_field_length])
                            }
                        },
                        "color": "default"
                    }
                ])
        buttons.append([create_button_negative('Назад')])

        return 'Выберите организацию:', json.dumps(
            {
                "one_time": False,
                "buttons": buttons
            }
            , ensure_ascii=False)
    except BaseException as e:
        app.logger.warning('registration_stage_1: {}'.format(str(e)))
        return error_message, ''
Ejemplo n.º 28
0
    def put(self, organization, faculty, group):
        # Update the group
        try:
            if not request.is_json:
                return make_response(jsonify(self.error["putFail_missing_json"]), 400)

            new_organization = request.json.get('new_organization', None)
            new_faculty = request.json.get('new_faculty', None)
            new_group = request.json.get('new_group', None)

            if not new_organization:
                return make_response(jsonify(self.error["putFail_missing_organization"]), 400)
            if not new_faculty:
                return make_response(jsonify(self.error["putFail_missing_faculty"]), 400)
            if not new_group:
                return make_response(jsonify(self.error["putFail_missing_group"]), 400)

            with ScheduleDB(app.config) as db:
                db_data = db.get_group(organization, faculty, group)

                if db_data is None:
                    return make_response(jsonify(self.error["putFail_unknown"]), 400)

                old_tag = db_data[1]

                if old_tag is not None:
                    new_tag = db.update_organization(new_organization, new_faculty, new_group, old_tag)

                    if new_tag is not None:
                        return make_response(jsonify(new_tag), 200)
                    else:
                        return make_response(jsonify(self.error["putFail_unknown"]), 400)
                else:
                    return make_response(jsonify(self.error["putFail_unknown"]), 400)
        except BaseException as e:
            app.logger.warning('GroupApi put: {}'.format(str(e)))
            return make_response(jsonify(self.error["putFail_unknown"]), 400)
Ejemplo n.º 29
0
def schedule(uid, key, data=""):
    # Статистика
    track(app.config['STATISTIC_TOKEN'], uid, key, 'schedule')

    try:
        is_registered, message, user = registration_check(uid)
        if not is_registered:
            return message, '', get_main_keyboard(is_registered=False)
    except BaseException as e:
        app.logger.warning('schedule: {}'.format(str(e)))
        return error_message, '', ''

    try:
        week_type = -1
        message = ''

        if key == 'неделя' or key == 'расписание':
            days = helpers.ScheduleType['неделя']
        elif key == 'вчера':
            yesterday = datetime.now()
            yesterday -= timedelta(days=1)

            week_type = (yesterday.isocalendar()[1] +
                         app.config['WEEK_TYPE']) % 2

            days = [helpers.daysOfWeek[datetime.weekday(yesterday)]]
        elif key == 'сегодня':
            today = datetime.now()
            # Если запрашивается расписание на сегодняшний день,
            # то week_type равен остатку от деления на 2 номера недели в году, т.е он определяет чётная она или нечётная
            week_type = (today.isocalendar()[1] + app.config['WEEK_TYPE']) % 2

            # Если время больше чем 21:30, то показываем расписание на следующий день
            #if today.time() >= time(21, 30):
            #   today += timedelta(days=1)
            # Если сегодня воскресенье, то показывается расписание на понедельник следующей недели
            # Также в этом случае, как week_type используется тип следующей недели
            if datetime.weekday(today) == 6:
                today += timedelta(days=1)
                week_type = (week_type + 1) % 2

            days = [helpers.daysOfWeek[datetime.weekday(today)]]
        elif key == 'завтра':
            tomorrow = datetime.now()
            tomorrow += timedelta(days=1)
            # Если запрашивается расписание на завтрашний день,
            # то week_type равен остатку от деления на 2 номера недели в году, т.е он определяет чётная она или нечётная
            week_type = (tomorrow.isocalendar()[1] +
                         app.config['WEEK_TYPE']) % 2

            # Если сегодня воскресенье, то показывается расписание на понедельник следующей недели
            # Также в этом случае, как week_type используется тип следующей недели
            #if datetime.weekday(tomorrow) == 6:
            #   tomorrow += timedelta(days=1)
            #   week_type = (week_type + 1) % 2

            days = [helpers.daysOfWeek[datetime.weekday(tomorrow)]]
        elif key == 'послезавтра':
            day_after_tomorrow = datetime.now()
            day_after_tomorrow += timedelta(days=2)
            # Если запрашивается расписание на завтрашний день,
            # то week_type равен остатку от деления на 2 номера недели в году, т.е он определяет чётная она или нечётная
            week_type = (day_after_tomorrow.isocalendar()[1] +
                         app.config['WEEK_TYPE']) % 2

            # Если сегодня воскресенье, то показывается расписание на понедельник следующей недели
            # Также в этом случае, как week_type используется тип следующей недели
            # if datetime.weekday(tomorrow) == 6:
            #   tomorrow += timedelta(days=1)
            #   week_type = (week_type + 1) % 2

            days = [helpers.daysOfWeek[datetime.weekday(day_after_tomorrow)]]
        else:
            days = [helpers.ScheduleType[key]]

        for day in days:
            try:
                with ScheduleDB(app.config) as db:
                    user = db.find_user(uid)
                if user and user[0] != '':
                    result = create_schedule_text(user[0], day, week_type)
                    message += result[0] + "\n\n"
                else:
                    message = registration_message
            except BaseException as e:
                if uid == 354726059:
                    return 'schedule: ' + str(e), '', ''
                message = error_message
    except BaseException as e:
        app.logger.warning('schedule: {}'.format(str(e)))
        return error_message, '', ''
    return message, '', ''
Ejemplo n.º 30
0
def schedule(uid, key, data=""):
    # Если пользователя нет в базе, то ему выведет предложение зарегистрироваться
    try:
        with ScheduleDB(app.config) as db:
            user = db.find_user(uid)
        if not user or user[0] == '':
            message = "Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации:\n"
            message += 'Введите команду(без кавычек):\n\nрегистрация "название вуза" "факультет" "группа"\n\n'
            message += 'Если вы допустите ошибку, то просто наберите команду заново.\n'
            return message
    except BaseException as e:
        return 'Случилось что то странное, попробуйте ввести команду заново'

    week_type = -1
    message = ''
    if key == 'неделя':
        days = helpers.ScheduleType['неделя']
    elif key == 'сегодня' or key == 'расписание':
        today = datetime.now()
        # Если запрашивается расписание на сегодняшний день,
        # то week_type равен остатку от деления на 2 номера недели в году, т.е он определяет чётная она или нечётная
        week_type = today.isocalendar()[1] % 2

        # Если время больше чем 21:30, то показываем расписание на следующий день
        if today.time() >= time(21, 30):
            today += timedelta(days=1)
        # Если сегодня воскресенье, то показывается расписание на понедельник следующей недели
        # Также в этом случае, как week_type используется тип следующей недели
        if datetime.weekday(today) == 6:
            today += timedelta(days=1)
            week_type = (week_type + 1) % 2

        days = [helpers.daysOfWeek[datetime.weekday(today)]]
    elif key == 'завтра':
        tomorrow = datetime.now()
        # Если запрашивается расписание на сегодняшний день,
        # то week_type равен остатку от деления на 2 номера недели в году, т.е он определяет чётная она или нечётная
        week_type = tomorrow.isocalendar()[1] % 2

        tomorrow += timedelta(days=1)
        # Если сегодня воскресенье, то показывается расписание на понедельник следующей недели
        # Также в этом случае, как week_type используется тип следующей недели
        if datetime.weekday(tomorrow) == 6:
            tomorrow += timedelta(days=1)
            week_type = (week_type + 1) % 2

        days = [helpers.daysOfWeek[datetime.weekday(tomorrow)]]
    else:
        days = [helpers.ScheduleType[key]]

    for day in days:
        try:
            with ScheduleDB(app.config) as db:
                user = db.find_user(uid)
            if user and user[0] != '':
                result = create_schedule_text(user[0], day, week_type)
                for schedule_message in result:
                    message += schedule_message + "\n\n"
            else:
                message = "Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации:\n"
                message += 'Введите команду(без кавычек): регистрация "название вуза" "факультет" "группа"\n\n'
                message += 'Если вы допустите ошибку, то просто наберите команду заново.\n'
        except BaseException as e:
            message = "Случилось что то странное, попробуйте ввести команду заново"
    return message