Esempio n. 1
0
def _show_form(update: Update, context: CallbackContext):
    chat_data = ChatData.from_context(context)
    user_data = UserData.from_context(context)

    chat_data.send_form(user_data, callback_data=str(REMOVE))
    update.callback_query.answer()
    return SELECT_ACTION
Esempio n. 2
0
def _delete_answer(update: Update, context: CallbackContext):
    user_data = UserData.from_context(context)
    question = user_data.questions[user_data.current_question]
    try:
        del user_data.answers[question]
    except MissingDataError:
        pass
    return _ask_question(update, context)
Esempio n. 3
0
def _start(update: Update, context: CallbackContext) -> None:
    logger.debug(f'{update.message.text}')

    try:
        UserData.from_context(context)
    except MissingDataError:
        UserData(update.message.chat).update_context(context)
        ChatData(update.message.chat).update_context(context)
        logger.debug(f'Created new user data: {update.message.chat.id}')
        update.message.reply_text(text=HELP, parse_mode=ParseMode.MARKDOWN_V2)

    try:
        bot_data = BotData.from_context(context)
        bot_data.owner = (context.args[0], update.message.chat.id)
    except (IndexError, MissingDataError):
        pass

    return _select_level(update, context)
Esempio n. 4
0
def _withdraw_form(update: Update, context: CallbackContext):
    user_data = UserData.from_context(context)
    bot_data = BotData.from_context(context)

    # Anyway change form status
    user_data.status = FormStatus.BLOCKING
    bot_data.pending_forms.remove(user_data.id)

    update.callback_query.answer('Отправка анкеты отменена.')
    return _manage_form(update, context)
Esempio n. 5
0
def _shift_question(update: Update, context: CallbackContext):
    user_data = UserData.from_context(context)
    if update.callback_query.data == str(NEXT_QUESTION):
        user_data.current_question += 1
    elif update.callback_query.data == str(PREV_QUESTION):
        user_data.current_question -= 1
    else:
        logger.error('Incorrect state! IT SHOULD NEVER HAPPEN!')
        raise ValueError(f'Incorrect converstation state: {update.callback_query.data}')

    return _ask_question(update, context)
Esempio n. 6
0
def _show_media(update: Update, context: CallbackContext):
    user_data = UserData.from_context(context)
    chat_data = ChatData.from_context(context)
    question = user_data.questions[user_data.current_question]

    try:
        chat_data.send_media(user_data, question.question_type)
    except NoMediaError:
        pass

    update.callback_query.answer()
    return ASK_QUESTION
Esempio n. 7
0
def _state(func, back = None, *args, **kwargs): # pylint: disable=W1113
    chat_data = ChatData.from_context(args[1])
    user_data = UserData.from_context(args[1])
    if back:
        user_data.back = back

    chat_data.clear_error()

    chat_data.delete_form(chat_data.id)

    if args[0].callback_query:
        args[0].callback_query.answer()

    return func(*args, *kwargs)
Esempio n. 8
0
def _delete_form(update: Update, context: CallbackContext):
    bot_data = BotData.from_context(context)
    user_data = UserData.from_context(context)
    try:
        user_data.status = FormStatus.BLOCKING
        channel = ChatData.by_id(bot_data.dating_channel)
    except MissingDataError:
        pass
    else:
        channel.delete_form(user_data.id)

    logger.info(f'Form has been deleted: {str(user_data)}')
    update.callback_query.answer('Анкета успешно удалена.')
    return _manage_form(update, context)
Esempio n. 9
0
def _ask_question(update: Update, context: CallbackContext) -> None:
    user_data = UserData.from_context(context)
    chat_data = ChatData.from_context(context)
    question = user_data.questions[user_data.current_question]

    show: bool = False
    remove: bool = False

    try:
        answer = user_data.answers[question].value
    except MissingDataError as exc:
        if question.question_type in (QuestionType.TEXT, QuestionType.DIGITS):
            answer = 'Не отвечено'
        elif question.question_type == QuestionType.AUDIO:
            answer = 'Нет саундтрека'
        elif question.question_type == QuestionType.PHOTO:
            answer = 'Нет фото'
        else:
            raise AssertionError from exc
    else:
        if question.question_type in (QuestionType.TEXT, QuestionType.DIGITS):
            pass
        elif question.question_type == QuestionType.AUDIO:
            if answer[0]:
                show = True
                answer = 'Добавлено аудио'
            else:
                answer = answer[1]
        elif question.question_type == QuestionType.PHOTO:
            show = True
            answer = f'Добавлено {len(answer)} фото'
        else:
            raise AssertionError
        remove = True

    chat_data.print_messages(
        {'text': _format_question_text(question), 'parse_mode': 'MarkdownV2'},
        {'text': answer, 'reply_markup': _question_keyboard(show, remove)}
    )
    return ASK_QUESTION
Esempio n. 10
0
def _proc_answer(update: Update, context: CallbackContext):
    user_data = UserData.from_context(context)
    chat_data = ChatData.from_context(context)
    question = user_data.questions[user_data.current_question]

    if question.question_type == QuestionType.PHOTO:
        queue = context.dispatcher.update_queue

        updates = [update]
        for _ in range(queue.qsize()):
            updates.append(queue.get())
        data = [update.message for update in updates]
    else:
        data = update.message

    try:
        user_data.answers = (question.tag, data)
        user_data.current_question += 1
        return _ask_question(update, context)
    except AnswerError as exc:
        chat_data.print_error(str(exc))
        return ASK_QUESTION
Esempio n. 11
0
def _send_form(update: Update, context: CallbackContext):
    user_data = UserData.from_context(context)
    bot_data = BotData.from_context(context)
    bot = Dispatcher.get_instance().bot

    # Send message to all admins chats (chats have negative ID)
    for chat in [c for c in bot_data.admins if c < 0]:
        text = utils.helpers.escape_markdown(
            f'Новая анкета: {user_data.id} \({user_data.mention()}\)'
        )
        keyboard = InlineKeyboardMarkup.from_button(InlineKeyboardButton(
            text='Показать', callback_data=f'{str(SHOW)}{user_data.id}'
        ))
        bot.sendMessage(chat, text=text, reply_markup=keyboard, parse_mode='MarkdownV2')

    # Update form status
    bot_data.pending_forms.append(user_data.id)
    user_data.status = FormStatus.PENDING

    logger.info('New form has been sent: {str(user_data)}')
    update.callback_query.answer('Анкета успешно отправлена!')
    return _manage_form(update, context)
Esempio n. 12
0
def _back(update: Update, context: CallbackContext) -> None:
    user_data = UserData.from_context(context)
    if user_data.back:
        logger.debug(f'returning back: {user_data.back}')
        return user_data.back(update, context)
    return _select_level(update, context)
Esempio n. 13
0
def _manage_form(update: Update, context: CallbackContext):
    user_data = UserData.from_context(context)
    chat_data = ChatData.from_context(context)

    answer_button = InlineKeyboardButton(text='Ответить на вопросы',
                                         callback_data=str(ASK_QUESTION))
    show_form_button = InlineKeyboardButton(text='Показать анкету',
                                         callback_data=str(SHOW_FORM))

    buttons = [[], [], []]
    text = str()

    status = user_data.status
    if status == FormStatus.BLOCKING:
        buttons[0].append(
            answer_button
        )
        text = (
            'Заполни анкету для отправки.'
        )
    elif status == FormStatus.IDLE:
        buttons[0].extend(
            (answer_button, show_form_button)
        )
        buttons[1].append(
            InlineKeyboardButton(text='Отправить анкету',
                                         callback_data=str(SEND_FORM))
        )
        text = (
            'Анкета заполнена и готова к отправке на ревью админами.'
        )
    elif status == FormStatus.PENDING:
        buttons[0].append(
            show_form_button
        )
        buttons[1].append(
            InlineKeyboardButton(text='Отозвать анкету',
                                         callback_data=str(WITHDRAW_FORM))
        )
        text = (
            'Анкета отправлена и ожидает ревью. Если хочешь внести правки -- '
            'сначала отзови анкету назад.'
        )
    elif status == FormStatus.PUBLISHED:
        buttons[1].append(
            InlineKeyboardButton(text='Удалить анкету',
                                         callback_data=str(DELETE_FORM))
        )
        text = (
            'Анкета успешно опубликована! Поздравляю. В любой момент ты можешь '
            'удалить её из канала.'
        )
    elif status == FormStatus.RETURNED:
        buttons[0].extend(
            (answer_button, show_form_button)
        )
        buttons[1].append(
            InlineKeyboardButton(text='Отправить анкету',
                                         callback_data=str(SEND_FORM))
        )
        text = (
            'К сожалению, твоя анкета не прошла ревью админами. Ознакомься '
            'с замечаниями и попробуй ещё раз.'
        )

    buttons[2].append(
        InlineKeyboardButton(text='Назад', callback_data=str(BACK))
    )
    keyboard = InlineKeyboardMarkup(buttons)

    logger.debug(f'{text}, {keyboard}')
    chat_data.print_messages(
            {'text': text},
            {'text': user_data.print_status(), 'reply_markup': keyboard}
    )
    return SELECT_ACTION