Exemplo n.º 1
0
def process(message):
    user_id = message.chat.id
    text = message.text
    if db.is_new_user(user_id):
        core.registration(user_id, text)
    elif db.is_blocked(user_id):
        return None
    elif text in core.msg_cases:
        core.msg_cases[text](id=user_id, state=db.get_state(user_id))
    else:
        core.state_cases[db.get_state(user_id)](id=user_id, text=text)
Exemplo n.º 2
0
def initiate_registration(user: telebot.types.User):
    """
    Запускает процесс регистрации для пользователя
    :param user: пользователь, которого необходимо зарегистрировать
    """
    state = get_state(user.id)

    first_name = user.first_name
    last_name = user.last_name

    bot.send_message(user.id, NEEDS_REG_MSG)

    if state.last_email_date and state.email_attempt >= MAX_NO_LIMIT_ATTEMPTS:
        seconds_passed = (datetime.now() - state.last_email_date).seconds
        seconds_left = EMAIL_LIMIT - seconds_passed

        if seconds_left > 0:
            return bot.send_message(user.id, reg_limit_msg(seconds_left))

    markup = None

    if last_name:
        markup = ReplyKeyboardMarkup(one_time_keyboard=True)
        markup.row(KeyboardButton(f'{first_name} {last_name}'))

    save_state(user.id, state)

    instruction = bot.send_message(user.id,
                                   REG_NAME_SURNAME_MSG,
                                   reply_markup=markup)
    return bot.register_next_step_handler(instruction, check_name_surname)
Exemplo n.º 3
0
def check_material(message: Message):
    """
    Обрабатывает введенное пользователем название материала
    для загрузки
    :param message: сообщение пользователя с названием материала
    """
    author_id = message.from_user.id

    if message.text in COMMANDS:
        return handle_cancel(message, 'загрузки')

    if not is_text(message) or not is_title_correct(message):
        instruction = bot.send_message(author_id, INCORRECT_DATA_MSG)
        return bot.register_next_step_handler(instruction, check_material)

    # так как сообщения в поиске выводятся в HTML,
    # для защиты необходимо экранировать пользовательский ввод
    message.text = escape(message.text)

    state = get_state(author_id)
    state.uploading_material = Resource(title=message.text,
                                        author_id=author_id)
    save_state(author_id, state)

    instruction = bot.send_message(author_id, UPLOAD_COURSE_MSG)
    bot.register_next_step_handler(instruction, check_course)
Exemplo n.º 4
0
def check_name_surname(message: Message):
    """
    Обрабатывает введенные пользователем имя и фамилию
    при регистрации
    :param message: сообщение пользователя с именем и фамилией
    """
    user_id = message.chat.id

    if message.text in COMMANDS:
        return handle_cancel(message, 'регистрации')

    if not is_text(message) or not is_name_surname_correct(message):
        instruction = bot.send_message(user_id, INCORRECT_DATA_MSG)
        return bot.register_next_step_handler(instruction, check_name_surname)

    message.text = escape(message.text)

    state = get_state(user_id)
    state.registering_user = User(user_id=user_id, name=message.text)
    save_state(user_id, state)

    instruction = bot.send_message(user_id,
                                   REG_MAIL_MSG,
                                   reply_markup=ReplyKeyboardRemove())
    bot.register_next_step_handler(instruction, check_email)
Exemplo n.º 5
0
def check_email(message: Message):
    """
    Обрабатывает введенный пользователем адрес электронной почты
    при регистрации
    :param message: сообщение пользователя с адресом электронной почты
    """
    chat_id = message.chat.id

    if message.text in COMMANDS:
        return handle_cancel(message, 'регистрации')

    if not is_text(message) or not is_email_correct(message):
        instruction = bot.send_message(chat_id, INCORRECT_DATA_MSG)
        return bot.register_next_step_handler(instruction, check_email)

    state = get_state(chat_id)

    state.registering_user.code = str(int.from_bytes(os.urandom(2), 'little'))
    state.registering_user.email = message.text

    # ставим статус боту, пока письмо отправляется
    bot.send_chat_action(chat_id, 'typing')

    send_email(state.registering_user.email, 'Регистрация в боте BaumanLib',
               state.registering_user.code)

    state.last_email_date = datetime.now()
    state.email_attempt += 1

    save_state(chat_id, state)

    instruction = bot.send_message(chat_id, REG_CODE_MSG)
    bot.register_next_step_handler(instruction, check_code)
Exemplo n.º 6
0
def check_subject(message: Message):
    """
    Обрабатывает введенный пользователем предмет материала
    для загрузки
    :param message: сообщение пользователя с предметом материала
    """
    chat_id = message.chat.id

    if message.text in COMMANDS:
        return handle_cancel(message, 'загрузки')

    correct_subject = is_subject_correct(message)

    if not is_text(message) or not correct_subject:
        instruction = bot.send_message(chat_id, INCORRECT_DATA_MSG)
        return bot.register_next_step_handler(instruction, check_subject)

    state = get_state(chat_id)
    state.uploading_material.discipline = correct_subject

    save_state(chat_id, state)

    instruction = bot.send_message(chat_id,
                                   UPLOAD_FILE_MSG,
                                   reply_markup=ReplyKeyboardRemove())
    bot.register_next_step_handler(instruction, check_file)
Exemplo n.º 7
0
def check_file(message: Message):
    """
    Обрабатывает отправленный пользователем файл материала
    для загрузки
    :param message: сообщение пользователя с файлом материала
    """
    chat_id = message.chat.id

    if message.text in COMMANDS:
        return handle_cancel(message, 'загрузки')

    if message.content_type != 'document' or not is_file_correct(message):
        instruction = bot.send_message(chat_id, INCORRECT_DATA_MSG)
        return bot.register_next_step_handler(instruction, check_file)

    state = get_state(chat_id)
    uploading_material = state.uploading_material

    uploading_material.file_id = message.document.file_id
    uploading_material.rating = 0
    uploading_material.views = 0
    uploading_material.downloads = 0

    session.add(uploading_material)
    session.commit()

    # Закончили — можем отчистить состояние
    clear_state(chat_id)

    bot.send_message(chat_id, UPLOAD_SUCCESS_MSG)
Exemplo n.º 8
0
def check_course(message: Message):
    """
    Обрабатывает введенный пользователем курс материала
    для загрузки
    :param message: сообщение пользователя с курсом материала
    """
    chat_id = message.chat.id

    if message.text in COMMANDS:
        return handle_cancel(message, 'загрузки')

    if not is_text(message) or not is_course_correct(message):
        instruction = bot.send_message(chat_id, INCORRECT_DATA_MSG)
        return bot.register_next_step_handler(instruction, check_course)

    state = get_state(chat_id)
    state.uploading_material.course = message.text

    markup = ReplyKeyboardMarkup(one_time_keyboard=True)
    for subject in SUBJECTS:
        markup.row(KeyboardButton(subject))

    save_state(chat_id, state)

    instruction = bot.send_message(chat_id,
                                   UPLOAD_SUBJECT_MSG,
                                   reply_markup=markup)
    bot.register_next_step_handler(instruction, check_subject)
Exemplo n.º 9
0
def echo():
    user_id = request.json['session']['user_id']
    end = False
    if request.json['session']['new'] and not db.get_state(user_id):
        response = {
            'version': request.json['version'],
            'session': request.json['session'],
            'response': {
                'text': 'Привет! Как тебя зовут?'
            }
        }
        db.set_state(user_id, 0)
    else:
        state = db.get_state(user_id)
        inp = request.json['request']['original_utterance']

        if inp.lower() in ('удалить', 'убрать'):
            if not db.delete_user(user_id):
                text = 'О вас еще нет информации'
            else:
                text = 'Удалена вся информация о вас! :)\n Можете снова её добавить. Как вас зовут?'
                db.set_state(user_id, 0)
        elif inp.lower() in ('мои данные', 'данные'):
            name = db.get_user(user_id).name
            city = db.get_user(user_id).city
            text = f'Твое имя: {name}\nТвой город: {city}'
        elif state == 0:
            db.set_name(user_id, inp)
            db.set_state(user_id, 1)
            text = 'Круто! А откуда ты?'
        elif state == 1:
            db.set_city(user_id, inp)
            db.set_state(user_id, 2)
            text = 'Хороший город! Ладно, я все записал'
            end = True
        else:
            text = 'Я уже все записал'
        response = {
            'version': request.json['version'],
            'session': request.json['session'],
            'response': {
                'text': text,
                'end_session': end
            }
        }
    return response
Exemplo n.º 10
0
def get_answer(body, vk_id):
    state = db.get_state(vk_id)
    att = None
    message = "Неверный ввод. Попробуйте ещё раз"
    next_state = state
    notify = False
    if state == '-1':
        notify = True
        name = vkapi.get_profile(vk_id)["first_name"]
        message = 'Здравствуйте, ' + name + '!\n'
        message += 'Спасибо за ваше сообщение! Мы обязательно ответим на него чуть позже.\n\n'
        message += 'На данный момент проходят Дистанционные выборы в Студенческий совет ВМК. Если вы студент ВМК, вы можете проголосовать прямо здесь\n\n'
        #years = set(settings.enable_years) - set(settings.close_years)
        #message += 'Голосование доступно для' + ", ".join(map(str, years)) + ' курса, для 2 курса магистратуры, к сожалению, голосование недоступно, т.к. на курсе не зарегистрировался ни один кандидат.\n\n'
        if settings.close_years:
            message += 'Голосование на ' + ", ".join(
                map(str, settings.close_years)) + ' курсах завершено.\n\n'
        message += 'Если вы хотите проголосовать, отправьте 1.\n\n'
        message += 'Если вы хотите отправить ещё одно сообщение в Студенческий совет ВМК, отправьте 2.'
        next_state = '0'

    if state in command_list.keys():
        for com in command_list[state]:
            msg, nxt_state = com.process(vk_id, body)
            if msg is not None:
                message = msg
                next_state = nxt_state
                notify = False
                break
    else:
        message = None
        next_state = None

    if not message and not att and (vk_id in settings.admin_ids
                                    or vk_id in settings.cand_ids):
        for com in cand_com_list:
            msg, att = com.process(vk_id, body)
            if msg is not None:
                message = msg
                next_state = state
                notify = False
                break

    if not message and not att and vk_id in settings.admin_ids:
        for com in adm_com_list:
            msg, att = com.process(vk_id, body)
            if msg is not None:
                message = msg
                next_state = state
                notify = False
                break

    if notify:
        vkapi.notify_admins("Сообщение Совету от пользователя @id" +
                            str(vk_id))
        vkapi.notify_admins("Текст:\n" + body)
    return message, next_state, kb.get_board(next_state, vk_id), att
Exemplo n.º 11
0
def echo():
    #    command = request.json["command"].split()
    #    command_len = len(command.split())
    #    response_text = ' '
    #    if command_len == 0:
    #    elif command_len == 1:
    #        if command == command[::-1]:
    #        response_text = 'Word is mirrorlike'
    #    else:
    #        response_text = 'Word is not mirrorlike'
    #else:
    #   response_text = 'too many words'

    response_text = 'I dont understand you!'

    user_id = request.json['session']['user_id']
    state = get_state(user_id)

    if state == 0:
        response_text = 'Hi! What is your FirstName?'
        set_state(user_id, 1)
    elif state == 1:
        set_firstname(user_id, request.json['request']['original_utterance'])
        response_text = 'And what is your LastName?'
        set_state(user_id, 2)

    elif state == 2:
        set_lastname(user_id, request.json['request']['original_utterance'])
        response_text = 'And what is your PhoneNumber?'
        set_state(user_id, 3)

    elif state == 3:
        set_phonenumber(user_id, request.json['request']['original_utterance'])
        response_text = 'Thank for your time! Bye!'
        set_state(user_id, 4)

    elif state == 4:
        response_text = f'Here is your Data:        ' \
                        f'FirstName   {get_firstname(user_id)}             '\
                        f'LastName    {get_lastname(user_id)}              '\
                        f'PhoneNumber +  {get_phonenumber(user_id)}        '

    response = {
        'version': request.json['version'],
        'session': request.json['session'],
        'response': {
            'text': response_text
        }
    }

    return response
Exemplo n.º 12
0
def send_question(message):
    chat_id = message.chat.id
    state = db.get_state(chat_id)

    if message.text == qa[state][1]:
        db.set_state(chat_id, state + 1)
        if state + 1 < len(qa):
            bot.send_message(chat_id=chat_id, text='Right! Next Q')
            bot.send_message(chat_id=chat_id, text=qa[state + 1][0])
        else:
            bot.send_message(chat_id=chat_id,
                             text='Congratulations! /restart to try again')
    else:
        bot.send_message(chat_id=chat_id, text='Try again')
Exemplo n.º 13
0
def check_code(message: Message):
    """
    Обрабатывает введенный пользователем код при регистрации
    :param message: сообщение пользователя с кодом
    """
    chat_id = message.chat.id

    if message.text in COMMANDS:
        return handle_cancel(message, 'регистрации')

    state = get_state(chat_id)
    registering_user = state.registering_user

    if registering_user.code != message.text:
        state.code_attempt += 1
        save_state(chat_id, state)

        if state.code_attempt >= MAX_CODE_ATTEMPTS:
            state.code_attempt = 0
            save_state(chat_id, state)

            handle_cancel(message, 'регистрации')
            return bot.send_message(chat_id, CODE_LIMIT_MSG)

        instruction = bot.send_message(chat_id, INCORRECT_DATA_MSG)
        return bot.register_next_step_handler(instruction, check_code)

    registering_user.verified = True

    session.add(registering_user)
    session.commit()

    # Закончили — можем отчистить состояние
    clear_state(chat_id)

    bot.send_message(chat_id, REG_SUCCESS_MSG)
Exemplo n.º 14
0
 def GET(self, name):
     d = db.get_state(name)
     if d is None:
         raise web.notfound()
     return render.state(d)
Exemplo n.º 15
0

@bot.message_handler(commands=['start', 'restart'])
def send_welcome(message):
    chat_id = message.chat.id
    db.set_state(chat_id, 0)

    bot.send_message(
        chat_id=chat_id,
        text='''Hello {}, answer my questions, please :)'''.format(
            message.chat.first_name))
    bot.send_message(chat_id=chat_id, text=qa[0][0])


@bot.message_handler(
    func=lambda message: db.get_state(message.chat.id) < len(qa))
def send_question(message):
    chat_id = message.chat.id
    state = db.get_state(chat_id)

    if message.text == qa[state][1]:
        db.set_state(chat_id, state + 1)
        if state + 1 < len(qa):
            bot.send_message(chat_id=chat_id, text='Right! Next Q')
            bot.send_message(chat_id=chat_id, text=qa[state + 1][0])
        else:
            bot.send_message(chat_id=chat_id,
                             text='Congratulations! /restart to try again')
    else:
        bot.send_message(chat_id=chat_id, text='Try again')
Exemplo n.º 16
0
                        'content-type' in cherrypy.request.headers and \
                        cherrypy.request.headers['content-type'] == 'application/json':
            length = int(cherrypy.request.headers['content-length'])
            json_string = cherrypy.request.body.read(length).decode("utf-8")
            update = telebot.types.Update.de_json(json_string)
            # Эта функция обеспечивает проверку входящего сообщения
            bot.process_new_updates([update])
            return ''
        else:
            raise cherrypy.HTTPError(403)


# Набор директив для работы с ботом
@bot.message_handler(
    commands=['start'],
    func=lambda message: db.get_state(message.chat.id) == State.EMAIL.value)
def send_email(message):
    """
    Выводим сообщение с просьбой о вводе email
    """
    msg.get_email_input(message)


@bot.message_handler(
    commands=['start'],
    func=lambda message: db.get_state(message.chat.id) == State.CHOICE.value)
def send_choice(message):
    """
    Выводим меню выбора
    """
    msg.get_choice_menu(message)
Exemplo n.º 17
0
    def index(self):
        if 'content-length' in cherrypy.request.headers and \
                        'content-type' in cherrypy.request.headers and \
                        cherrypy.request.headers['content-type'] == 'application/json':
            length = int(cherrypy.request.headers['content-length'])
            json_string = cherrypy.request.body.read(length).decode("utf-8")
            update = telebot.types.Update.de_json(json_string)
            # Эта функция обеспечивает проверку входящего сообщения
            bot.process_new_updates([update])
            return ''
        else:
            raise cherrypy.HTTPError(403)


@bot.message_handler(commands=['start'],
                     func=lambda message: db.get_state(message.chat.id) in [
                         State.START.value, State.HELP.value, State.MENU.value,
                         State.FINISH.value
                     ])
def get_start_message(message):
    """
    Выводим стартовое сообщение
    """
    msg.get_start(message)


@bot.message_handler(commands=['help'],
                     func=lambda message: db.get_state(message.chat.id) in [
                         State.START.value, State.HELP.value, State.MENU.value,
                         State.FINISH.value
                     ])
Exemplo n.º 18
0
 def GET(self, name):
     d = db.get_state(name)
     return render.state(d)
Exemplo n.º 19
0
def get_state(_id):
    state = db.get_state((str(_id),))[0][0]
    return state
Exemplo n.º 20
0
 def GET(self, name):
     d = db.get_state(name)
     if d is None:
         raise web.notfound()
     return render.state(d)