예제 #1
0
def default_menu():
    markup = types.ReplyKeyboardMarkup()
    markup.row(types.KeyboardButton(Keyboard.SCHEDULE))
    markup.row(types.KeyboardButton(Keyboard.FEATURE))
    markup.row(types.KeyboardButton(Keyboard.SETTING),
               types.KeyboardButton(Keyboard.HELP))
    return markup
예제 #2
0
def get_user_score_view(user_id: int):
    """
    Возвращает view оценки пользователя
    """

    with Actions() as act:
        user_scores = act.get_all_questions_scores(user_id)

    # Делим на 2 потому что верный ответ это 2, частично верный 1
    user_score = int(
        sum(x.score for x in user_scores) / len(user_scores) / 2 * 100)

    if user_score > 84:
        user_score_description = get_template("52_result_excelent")
    elif user_score > 50:
        user_score_description = get_template("53_result_good")
    else:
        user_score_description = get_template("54_result_bad")

    answer_text = render_message(get_template("51_user_score"),
                                 user_score=user_score,
                                 user_score_description=user_score_description)

    row_buttons = [
        aiotypes.KeyboardButton("👍 Оценить бота"),
        aiotypes.KeyboardButton("🏠 Главное меню"),
    ]

    reply_kb = aiotypes.ReplyKeyboardMarkup(one_time_keyboard=True,
                                            resize_keyboard=True)
    reply_kb.row(*row_buttons)

    return View(answer_text, reply_kb)
예제 #3
0
class DecisionAboutRubricLinksOnDeletingReplyKeyboard(types.ReplyKeyboardMarkup):
    """
    Implements keyboard with choices to make decision about rubric links
    """

    text_for_button_to_set_none_rubric_for_links = '🖤 Set to non-rubric'
    text_for_button_to_delete_links = '🗑 Delete all related links'
    text_for_button_to_move_links_in_another_rubric = '📎 Move in another rubric'

    button_to_set_none_rubric_for_links = types.KeyboardButton(text_for_button_to_set_none_rubric_for_links)
    button_to_delete_links = types.KeyboardButton(text_for_button_to_delete_links)
    button_to_move_links_in_another_rubric = types.KeyboardButton(text_for_button_to_move_links_in_another_rubric)

    keyboard_structure_standard = [
        [button_to_set_none_rubric_for_links, button_to_delete_links, button_to_move_links_in_another_rubric]
    ]

    keyboard_structure_without_moving_decision = [
        [button_to_set_none_rubric_for_links, button_to_delete_links]
    ]

    def __init__(self, *args, does_user_have_other_rubrics: bool = True, **kwargs):
        """
        :keyword does_user_have_other_rubrics: offer to move related links in another rubric
            !only! if user has other rubrics
        :type does_user_have_other_rubrics: bool
        """

        if does_user_have_other_rubrics:
            super().__init__(self.keyboard_structure_standard, *args, **kwargs)
        else:
            super().__init__(self.keyboard_structure_without_moving_decision, *args, **kwargs)
예제 #4
0
async def choose_subtype(message: types.Message, state: FSMContext):
    if await cancel(message, state): return
    if await wrong_input(message, subtype_buttons, state): return

    async with state.proxy() as data:
        data['subtype'] = message.text

    await Form.next()  # регулярность
    key = types.ReplyKeyboardMarkup(resize_keyboard=True)
    if message.text == subtype_buttons[0]:
        await Form.next()  # время
        key.add(types.KeyboardButton(cancel_button))
        await message.answer(
            "Введите время отправки сообщения в формате `чч:мм`\n\n_Например_: `09:00`",
            parse_mode="Markdown",
            reply_markup=key)
    elif message.text == subtype_buttons[1]:
        key.add(days[0], days[1])
        key.add(days[2], days[3])
        key.add(days[4], days[5], days[6])
        key.add(types.KeyboardButton("Закончить выбор"))
        key.add(types.KeyboardButton(cancel_button))
        await message.answer(
            "Выберите нужные дни недели, после чего нажмите кнопку 'Закончить выбор'",
            reply_markup=key)
    elif message.text == subtype_buttons[2]:
        key.add(types.KeyboardButton(cancel_button))
        await message.answer(
            "Введите числа месяца через запятую\n_Например:_ `3, 7, 30`\n_Например:_ `21`",
            parse_mode="Markdown",
            reply_markup=key)
def start_button():
    key = types.ReplyKeyboardMarkup(resize_keyboard=True)
    but_1 = types.KeyboardButton("Поиск свободного времени")
    but_2 = types.KeyboardButton("Список мониторинга")
    key.add(but_1)
    key.add(but_2)
    return key
예제 #6
0
def settings_number_of_posts_keyboard(locale):
    keyboard_markup = types.ReplyKeyboardMarkup(row_width=2,
                                                resize_keyboard=True)
    keyboard_markup.add(
        *[types.KeyboardButton(number) for number in locale.number_of_posts])
    keyboard_markup.add(types.KeyboardButton(locale.back))
    return keyboard_markup
예제 #7
0
async def choose_regularity(message: types.Message, state: FSMContext):
    if await cancel(message, state): return

    text = None
    try:
        photo = message.photo[-1].file_id
    except IndexError:
        photo = None
    async with state.proxy() as data:
        if photo is None:
            data['media'] = None
            text = message.text
        else:
            data['media'] = photo
            if message.caption:
                text = message.caption

    if text:
        text = str(text).replace('_', '\\_').replace('*', '\\*').replace(
            '`', '\\`').replace('[', '\\[')
        if len(text) > 150:
            async with state.proxy() as data:
                data['text'] = None
            await message.answer("Сообщение слишком длинное!")
            return
    async with state.proxy() as data:
        data['text'] = text

    key = types.ReplyKeyboardMarkup(resize_keyboard=True)
    key.add(types.KeyboardButton(type_buttons[0]))
    key.add(types.KeyboardButton(type_buttons[1]))
    key.add(types.KeyboardButton(cancel_button))
    await Form.next()
    await message.answer("Выберите тип сообщения", reply_markup=key)
async def cmd_start(message: types.Message):
    poll_keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
    poll_keyboard.add(types.KeyboardButton(text="/deposit",
                                           request_poll=types.KeyboardButtonPollType(type=types.PollType.QUIZ)))
    poll_keyboard.add(types.KeyboardButton(text="/balance"))
    await message.answer("""Привет. Я бот - кошелёк. 
    Вы можете хранить ваши деньги, используя меня. Напиши /deposit (/d) что бы внести средства.""", reply_markup=poll_keyboard)
예제 #9
0
 def exam(self):
     keyboard_primery_entrance_exam = types.ReplyKeyboardMarkup(
         row_width=2, resize_keyboard=True)
     seven = types.KeyboardButton(text='7 класс')
     eight = types.KeyboardButton(text='8 класс')
     keyboard_primery_entrance_exam.add(seven, eight, self.back_button)
     return keyboard_primery_entrance_exam
예제 #10
0
def keyboard():
    markup = types.KeyboardMarkup(one_time_keyboard=False,
                                  resize_keyboard=True)
    button1 = types.KeyboardButton('Я заказчик')
    button2 = types.KeyboardButton('Я исполнитель')
    markup.add(button1, button2)
    return markup
예제 #11
0
async def command_start(message: types.Message):
    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
    button_1 = types.KeyboardButton(text="Для студентов")
    button_2 = types.KeyboardButton(text="Для абитурентов")
    button_3 = types.KeyboardButton(text="Контакты")
    keyboard.add(button_1, button_2, button_3)
    await bot.send_message(message.chat.id, "Выберете пункт", reply_markup=keyboard)
예제 #12
0
async def photo_processing(message):
    """
    Triggered when the user sends an image and saves it for further processing.
    """

    global flag
    global content_flag
    global style_flag

    # The bot is waiting for a picture with content from the user.
    if flag:
        await message.photo[-1].download('content.jpg')
        await message.answer(text= 'I got the content image.')
        flag = False
        content_flag = True # Now the bot knows that the content image exists.

    # The bot is waiting for a picture with style from the user.
    else:
        await message.photo[-1].download('style.jpg')
        await message.answer(text= 'I got the style image.')
        style_flag = True  # Now the bot knows that the style image exists.

    res = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
    res.add(types.KeyboardButton(text="Continue"))
    res.add(types.KeyboardButton(text="Reload"))
    await message.answer(text = 'Continue or Reload?', reply_markup=res)
예제 #13
0
    def main_buttons(self):
        markup = types.ReplyKeyboardMarkup(
            one_time_keyboard=True,
            resize_keyboard=True,
            row_width=2
        )

        book_table_btn = types.KeyboardButton(
            text='Забронировать столик ⏰',
        )

        show_menu_btn = types.KeyboardButton(
            text='Перейти в меню 🗒',
        )

        set_feedback_btn = types.KeyboardButton(
            text='Отзывы ✅',
        )

        markup.add(
            book_table_btn,
            show_menu_btn,
            set_feedback_btn,
        )

        return markup
예제 #14
0
async def choose_type(message: types.Message, state: FSMContext):
    if await cancel(message, state): return
    if await wrong_input(message, type_buttons, state): return

    async with state.proxy() as data:
        data['type'] = message.text
        data['reg'], data['time'], data['datetime'] = None, None, None

    await Form.next()  # подтипы
    key = types.ReplyKeyboardMarkup(resize_keyboard=True)
    if message.text == type_buttons[0]:
        await Form.next()  # регулярность
        await Form.next()  # время
        await Form.next()  # дата и время
        key.add(types.KeyboardButton(cancel_button))
        await message.answer(
            "Введите время отправки сообщения в формате `чч:мм`\n\n_Например_: `09:00`",
            parse_mode="Markdown",
            reply_markup=key)
    else:
        key.add(types.KeyboardButton(subtype_buttons[0]))
        key.add(types.KeyboardButton(subtype_buttons[1]))
        key.add(types.KeyboardButton(subtype_buttons[2]))
        key.add(types.KeyboardButton(cancel_button))
        await message.answer("Выберите подтип сообщения", reply_markup=key)
예제 #15
0
def menu_keyboard(locale):
    keyboard_markup = types.ReplyKeyboardMarkup(row_width=3,
                                                resize_keyboard=True)
    keyboard_markup.add(types.KeyboardButton(locale.get_updates))
    keyboard_markup.add(types.KeyboardButton(locale.settings))
    # keyboard_markup.add(types.KeyboardButton(locale.about_project))
    return keyboard_markup
예제 #16
0
async def student(message: types.Message):
    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
    button_1 = types.KeyboardButton(text="Рассписание")
    button_2 = types.KeyboardButton(text="График экзаменов")
    button_3 = types.KeyboardButton(text="Практика студентов")
    keyboard.add(button_1, button_2, button_3)
    await bot.send_message(message.chat.id, "Выберете пункт", reply_markup=keyboard)
예제 #17
0
async def change_user_settings(message):
    _keyboard = [
        [types.KeyboardButton('👅 Results language'), 
        types.KeyboardButton('⏳ Time filter'),],
        [types.KeyboardButton('🔞 Safe search'),
        types.KeyboardButton('🔙 Back')],
    ]

    keyboard = types.ReplyKeyboardMarkup(
            keyboard=_keyboard, resize_keyboard=True)

    settings = db_helper.show_settings(message.chat.id)

    if settings:
        await bot.send_message(
                message.chat.id,
                text=current_settings.format(settings['lang'], settings['safe']),
                reply_markup=keyboard)
    else:
        await bot.send_message(
                message.chat.id, text='Error. Enter /home and try again.')

    dp.register_message_handler(change_query_language, text='👅 Results language')
    dp.register_message_handler(change_tbs, text='⏳ Time filter')
    dp.register_message_handler(switch_safesearch, text='🔞 Safe search')
예제 #18
0
def settings_city_keyboard(locale):
    keyboard_markup = types.ReplyKeyboardMarkup(row_width=2,
                                                resize_keyboard=True)
    keyboard_markup.add(
        *[types.KeyboardButton(text) for text in city_raw_text(locale)])
    keyboard_markup.add(types.KeyboardButton(locale.back))
    return keyboard_markup
예제 #19
0
 def admission_(self):
     keyboard_admission = types.ReplyKeyboardMarkup(row_width=2,
                                                    resize_keyboard=True)
     seven = types.KeyboardButton(text='Поступление в 7 класс')
     eight = types.KeyboardButton(text='Поступление в 8 класс')
     keyboard_admission.add(seven, eight, self.back_button)
     return keyboard_admission
예제 #20
0
async def check():
    global num
    while True:
        f = open('text.txt', 'r+', encoding='utf8')
        text = [str(i) for i in f.read().split('|')]
        f.close()
        if text[0] == 'Bot__police':
            open('text.txt', 'w').close()
            num = int(text[1])

            # главная функия диалога
            markup = types.ReplyKeyboardMarkup(
                row_width=1, one_time_keyboard=True)  # создание клавиатуры

            item1 = types.KeyboardButton(bot_police[num][0][0])
            item2 = types.KeyboardButton(bot_police[num][1][0])
            item3 = types.KeyboardButton(bot_police[num][2][0])
            item4 = types.KeyboardButton(bot_police[num][3][0])

            markup.add(item1, item2, item3,
                       item4)  # добовляем эелементы в клавиатуру

            await bot.send_message(config.ID_PERSON,
                                   text[2],
                                   reply_markup=markup)
        await asyncio.sleep(1)
예제 #21
0
async def contin(message: types.Message):
    """Preparing for image processing."""

    logging.debug("Received message: Continue")
    global flag
    global content_flag
    global style_flag

    if not style_flag:
        res = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
        res.add(types.KeyboardButton(text="Own style"))
        res.add(types.KeyboardButton(text="Build-in options"))

        await message.answer(text="Do you want to transfer you own style" 
                                  "\nor use build-in options?", reply_markup=res)

    else:
        await message.answer(text='Processing has started and will take about 10 secs. '
                                  '\n'
                                  '\nMeanwhile...'
                                  '\n- Why can’t dinosaurs clap?' 
                                  '\n- Because they are all dead.',
                             reply_markup=types.ReplyKeyboardRemove())
        transform('content.jpg', 'msgnet.pth', 'style.jpg')
        flag =  True
        content_flag =  False
        style_flag = False
        with open('result.jpg', 'rb') as file:
            await message.answer_photo(file, caption='Done!')
예제 #22
0
async def welcome(message):
    # keyboard
    global WantToPlay
    global LeftDistance
    global PersonAlive
    global CamelHealth
    global CamelAlive
    global PersonHealth
    global DistanceToBandits
    global CntWater
    global CntMeat
    global CntAct
    global WantToPlay
    global IsGameOn
    global Win
    global b
    if message.chat.id in players:
        id = players[message.chat.id]
        WantToPlay[id] = True
        IsGameOn[id] = False
        LeftDistance[id] = 0
        PersonAlive[id] = True
        CamelAlive[id] = True
        CamelHealth[id] = 100
        PersonHealth[id] = 100
        DistanceToBandits[id] = 100
        CntWater[id] = 3
        CntMeat[id] = 3
        CntAct[id] = 1
        Win[id] = False
        LeftDistance[id] = random.randint(1200, 1200)
        b[id] = []
    else:
        players[message.chat.id] = len(WantToPlay)
        WantToPlay.append(True)
        IsGameOn.append(False)
        PersonAlive.append(True)
        IsATTAKING.append(-1)
        CamelAlive.append(True)
        PersonHealth.append(100)
        CamelHealth.append(100)
        DistanceToBandits.append(100)
        CntWater.append(3)
        CntMeat.append(3)
        CntAct.append(1)
        Win.append(False)
        LeftDistance.append(random.randint(1200, 1200))
        b.append([])

    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    item1 = types.KeyboardButton("ДА")
    item2 = types.KeyboardButton("НЕТ")
    markup.add(item1, item2)
    await bot.send_message(
        chat_id=message.chat.id,
        text="Привет {0.first_name}!\nХочешь поиграть в прикольную игру?".
        format(message.from_user),
        parse_mode='html',
        reply_markup=markup)
예제 #23
0
async def start(message: types.Message):
    await process.model.set()
    res = types.ReplyKeyboardMarkup(resize_keyboard=True,
                                    one_time_keyboard=True)
    res.add(types.KeyboardButton(text='nst'))
    res.add(types.KeyboardButton(text="gan"))

    await message.reply('выбери модель', reply_markup=res)
예제 #24
0
def settings_keyboard(locale):
    keyboard_markup = types.ReplyKeyboardMarkup(row_width=3,
                                                resize_keyboard=True)
    keyboard_markup.add(types.KeyboardButton(locale.settings_city))
    keyboard_markup.add(types.KeyboardButton(locale.settings_representation))
    keyboard_markup.add(types.KeyboardButton(locale.settings_number_of_posts))
    keyboard_markup.add(types.KeyboardButton(locale.back))
    return keyboard_markup
예제 #25
0
async def cmd_start(message: types.Message):
    """Отправляет приветственное сообщение и помощь по боту"""
    poll_keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
    poll_keyboard.add(types.KeyboardButton(text="USD"))
    poll_keyboard.add(types.KeyboardButton(text="RUB"))
    poll_keyboard.add(types.KeyboardButton(text="EUR"))
    await message.answer('Бот для получения обменного курса тенге',
                         reply_markup=poll_keyboard)
예제 #26
0
def startMarkup():
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True,
                                       one_time_keyboard=True)
    markup.add(types.KeyboardButton(text='Приступить к настройке'))
    markup.add(
        types.KeyboardButton(
            text='Пропустить и задать настройки по умолчанию'))
    return markup
예제 #27
0
def button_from_source(
        button: Union[str, Dict[str, Any]]) -> types.KeyboardButton:
    if isinstance(button, str):
        return types.KeyboardButton(text=button)
    elif isinstance(button, dict):
        return types.KeyboardButton(**button)
    else:
        assert False
예제 #28
0
async def hello_handler(message: types.Message) -> None:
    markup = types.ReplyKeyboardMarkup(row_width=2)
    item1 = types.KeyboardButton('да')
    item2 = types.KeyboardButton('нет')
    markup.add(item1, item2)
    logger.info(f"User {message.from_user.id} is on server")
    await message.answer("Доброго времени суток. Рассказать что я умею?",
                         reply_markup=markup)
예제 #29
0
파일: main.py 프로젝트: aogavrilov/P2SBot
async def start_dialog(message: types.Message):
    poll_keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
    poll_keyboard.add(types.KeyboardButton("О приложении"))
    poll_keyboard.add(types.KeyboardButton("Style Transfer"))
    poll_keyboard.add(types.KeyboardButton("Преобразовать фото в скетч(криво увы)"))
    # poll_keyboard.add(types.KeyboardButton("Поддержать"))
    poll_keyboard.add(types.KeyboardButton("Отмена"))
    await message.answer("Выберите действие, которое хотите совершить", reply_markup=poll_keyboard)
예제 #30
0
async def get_basemenu_keyboard():
    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)

    keyboard.row(types.KeyboardButton(attack_message),
                 types.KeyboardButton(defense_message))
    keyboard.add(types.KeyboardButton(help_message))
    # for name in basemenu_list: keyboard.add(types.KeyboardButton(name))
    return keyboard