def de_json(cls, data, bot):
        if not data:
            return None

        data = super(ReplyKeyboardMarkup, cls).de_json(data, bot)

        data['keyboard'] = [KeyboardButton.de_list(keyboard, bot) for keyboard in data['keyboard']]

        return cls(**data)
Beispiel #2
0
def gates_cmd(bot, update):
    if not is_user_valid(bot, update):
        return cancel(bot, update)

    reply_msg = "Какие ворота вы хотите открыть или закрыть?"

    buttons = [
        KeyboardButton(KeyboardEnum.GATE_1.clean()),
        KeyboardButton(KeyboardEnum.GATE_2.clean()),
        KeyboardButton(KeyboardEnum.GARAGE.clean()),
        KeyboardButton(KeyboardEnum.GATE_1_AND_GARAGE.clean())
    ]

    cancel_btn = [KeyboardButton(KeyboardEnum.CANCEL.clean())]

    reply_mrk = ReplyKeyboardMarkup(
        build_menu(buttons, n_cols=3, footer_buttons=cancel_btn))
    update.message.reply_text(reply_msg, reply_markup=reply_mrk)

    return WorkflowEnum.GATES_SUB_CMD
Beispiel #3
0
def remove_coin(bot, update):
    """
    Update user's coins list: remove selected coin
    :param bot:
    :param update:
    :return: nex conversation state
    """
    coin = helper.clear_currency_code(update.message.text)
    if coin:
        user.remove_coin(update.message.chat_id, coin)

    buttons = [KeyboardButton("/remove_coin"), KeyboardButton("/cancel")]

    bot.send_message(chat_id=update.message.chat_id,
                     text=coin +
                     " was successfully removed from your coins list. "
                     "Do you want to remove more coins or cancel operation?",
                     reply_markup=get_markup(buttons, cols_num=2))

    return AddCoinStates.COMPLETE_REMOVE
 def build_reply_keyboard(items: List[str]) -> ReplyKeyboardMarkup:
     """
     Builds a menu to select an item from a list
     :param items: list of items to choose from
     :return: reply markup
     """
     items.append(CANCEL_KEYBOARD_COMMAND)
     keyboard = list(map(lambda x: KeyboardButton(x), items))
     # NOTE: the "selective=True" requires the menu to be sent as a reply
     # (or with an @username mention)
     return ReplyKeyboardMarkup.from_column(keyboard, one_time_keyboard=True, selective=True)
Beispiel #5
0
def start(bot, update):
    contact_button = KeyboardButton(text=_('Share my contact information'), request_contact=True)
    reply_keyboard = [[contact_button]]

    update.message.reply_text(_(
        "Hi! I'm alibot, your assistant in filing reports. "
        "first of all you have to give my you mobile number for verification."),
        reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
    )

    return LOGIN
Beispiel #6
0
def keyboard_cmds():
    command_buttons = [
        KeyboardButton("/help"),
        KeyboardButton("/comiditas"),
        KeyboardButton("/comiditas_hechas"),
        KeyboardButton("/comiditas_por_hacer"),
        KeyboardButton("pole"),
        KeyboardButton("/Comiditas favoritas"),
        KeyboardButton("/donaciones"),
        KeyboardButton("/start"),
    ]
    #Devuelve el telcado con 3 columnas y llamando a la funcion build que organiza el telcado
    return ReplyKeyboardMarkup(build_menu(command_buttons, n_cols=3))
Beispiel #7
0
def search_cmd(update: Update, context: CallbackContext) -> None:
    """Search libri.tel for books"""
    if not allowed_chat(update):
        return None

    search_query = str.join(" ", context.args[0:])
    results = lt.search(search_query)

    keyboard = [[KeyboardButton("/get " + r.url)] for r in results]
    reply_markup = ReplyKeyboardMarkup(keyboard)
    update.message.reply_text('Scegli ⤵️', reply_markup=reply_markup)
Beispiel #8
0
def show_start_keyboard(bot, chat_id):
    message = textwrap.dedent('''
        Разгадайте ребусы и получите подарок.''')
    keyboard = KeyboardButton(text="Начать игру")
    reply_markup = ReplyKeyboardMarkup([[keyboard]],
                                       one_time_keyboard=True,
                                       row_width=1,
                                       resize_keyboard=True)
    return bot.send_message(chat_id=chat_id,
                            text=message,
                            reply_markup=reply_markup)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Send a message with a button that opens a the web app."""
    await update.message.reply_text(
        "Please press the button below to choose a color via the WebApp.",
        reply_markup=ReplyKeyboardMarkup.from_button(
            KeyboardButton(
                text="Open the color picker!",
                web_app=WebAppInfo(
                    url="https://python-telegram-bot.org/static/webappbot"),
            )),
    )
Beispiel #10
0
def cajero(bot, update, user_data):
    """Handler de banelco y link
    Arranca pidiendo la direccion"""
    user_data['red'] = update.message.text.upper()
    markup_boton_direccion = ReplyKeyboardMarkup(
        [[KeyboardButton('Mandame tu direción', request_location=True)]],
        resize_keyboard=True,
        one_time_keyboard=True)
    bot.sendMessage(chat_id=update.message.chat_id,
                    text='Ingresá la dirección a partir del botón',
                    reply_markup=markup_boton_direccion)
def ask_info(bot, update, **kwargs):
    user = kwargs['user']

    contact_keyboard = KeyboardButton(text=langs[user.lang]["send_contact"],
                                      request_contact=True)
    reply_keyboard = [[contact_keyboard, no_contact],
                      [langs[user.lang]["start_again"]]]
    update.message.reply_text(langs[user.lang]["ask_contact"],
                              reply_markup=ReplyKeyboardMarkup(
                                  reply_keyboard, one_time_keyboard=True))
    return END
Beispiel #12
0
def get_buttons_line(btn_captions, is_inline):
    buttons_line = []
    for emo_caption_dict in btn_captions:
        for emo_code in emo_caption_dict:
            button_text = '%s %s' % (get_emotion(emo_code), emo_caption_dict[emo_code])
            if not is_inline:
                button = KeyboardButton(button_text)
            else:
                button = InlineKeyboardButton(text=button_text, callback_data=emo_code)
            buttons_line.append(button)
    return buttons_line
Beispiel #13
0
def choose_product(update, context):
    bot = context.bot
    lang = extract_language_and_update_if_not_present(update, context)
    keyboard = [
        [KeyboardButton(f"📝{translate('send_name', lang)}")],
        [KeyboardButton(f"📸📝{translate('send_name_and_photo', lang)}")],
        [KeyboardButton(f"📦📝{translate('send_name_and_barcode', lang)}")],
        [KeyboardButton(f"🚫{translate('cancel', lang)}")]
    ]
    reply_markup = ReplyKeyboardMarkup(keyboard,
                                       one_time_keyboard=False,
                                       resize_keyboard=True)

    bot.send_message(update.message.chat_id, f"{translate('select_option', lang)}", reply_markup=reply_markup)

    edit_stat("item_checker")
    edit_user_stat(update.message.chat_id, "item_checker")
    edit_daily_active_users_stat(update.message.chat_id)

    return SELECT_TYPE
Beispiel #14
0
def preview(update, context):
    """Ask user to create a poll and display a preview of it"""
    # using this without a type lets the user chooses what he wants (quiz or poll)
    button = [[
        KeyboardButton("Press me!", request_poll=KeyboardButtonPollType())
    ]]
    message = "Press the button to let the bot generate a preview for your poll"
    # using one_time_keyboard to hide the keyboard
    update.effective_message.reply_text(message,
                                        reply_markup=ReplyKeyboardMarkup(
                                            button, one_time_keyboard=True))
Beispiel #15
0
    def __print_prediction(self, update: Update, context: CallbackContext,
                           question: GameAI.Question):
        buttons = []
        buttons.append(KeyboardButton(self.__button_restart))

        reply_markup = ReplyKeyboardMarkup(keyboard=self.build_menu(
            buttons, 2, KeyboardButton(self.__button_explanation_decisions)),
                                           resize_keyboard=True,
                                           one_time_keyboard=True)

        update.message.reply_text(text=f'✅ {question.prediction.text}',
                                  reply_markup=reply_markup)

        if (question.prediction.src != None
                and question.prediction.img != None):
            update.message.reply_photo(
                photo=question.prediction.img,
                caption=
                f"Ссылка на <a href='{question.prediction.src}'>игру</a>",
                parse_mode='HTML')
Beispiel #16
0
def get_response_ask_consent(bot, update, user_data):
    global user_response

    user_input = update.message.text
    user_response = user_input
    query = update.callback_query

    yes_button = KeyboardButton(text='Yes', callback_data='Yes')
    no_button = KeyboardButton(text='No', call_back='No')
    consent_button = [yes_button, no_button]

    text = 'Thank you for reporting!\n'
    text += 'Do you consent to give this information along with your telegram use ID to the developer team?'

    bot.send_message(text=text,
                     chat_id=update.message.chat_id,
                     reply_markup=ReplyKeyboardMarkup(
                         keyboard=[consent_button], one_time_keyboard=True))

    return 2
Beispiel #17
0
def add_wish(bot, update):
    user = get_user(update.message.chat_id)
    user_language = Language(user.lang)

    kb = ReplyKeyboardMarkup(
        [[KeyboardButton(buttons[Button.BACK_TO_WISH_LIST][user_language])]],
        resize_keyboard=True)
    bot.send_message(chat_id=update.message.chat_id,
                     text=messages[Message.ADD_WISH][user_language],
                     reply_markup=kb,
                     parse_mode=ParseMode.MARKDOWN)
Beispiel #18
0
def command_location_handler(bot, update):

    chat_id = update.message.chat_id
    user_id = update.message.from_user.id
    reply_keyboard = [[KeyboardButton(MENU)]]
    bot.sendMessage(
        chat_id,
        text=u'Чтобы узнать погоду по координатам введите: <широта>,<долгота>',
        reply_markup=ReplyKeyboardMarkup(reply_keyboard, resize_keyboard=True))
    report.track_screen(user_id, 'location')
    return STATE_LOCATION
Beispiel #19
0
def newFriend(bot, update):
    user = update.message.from_user
    logger.info("User %s started a new connection." % (user.first_name))

    reply_keyboard = [[
        KeyboardButton(text="send_contact", mapUserCurrent_contact=True)
    ]]
    update.message.reply_text('Choose a contact to add?',
                              reply_markup=ReplyKeyboardMarkup(
                                  reply_keyboard, one_time_keyboard=True))
    return PROCESS_FRIEND
    def Play(self, bot, update):
        """
        Метод бота "/play"
        Args:
            bot (:class:`telegram.Bot`): хэндлер бота
            update(:class:`telegram.ext.Updater`): обновления

        """
        logger.info("Method play")
        update.message.reply_text(text=Strings.greeting2)
        keyboard = [[
            KeyboardButton("/encrypt ✉➡🗻"),
            KeyboardButton("/decrypt 🗻➡✉")
        ], [KeyboardButton("/upload picture"),
            KeyboardButton("/depart")]]
        reply_markup = ReplyKeyboardMarkup(keyboard,
                                           one_time_keyboard=True,
                                           resize_keyboard=True)
        update.message.reply_text('Please choose:', reply_markup=reply_markup)
        return logger.info("game begins")
    def __get_menu_keyboard(button, keyb_type):

        emoji_1 = '\U0001F4DA'
        emoji_2 = '\U0001F4C4'
        emoji_3 = '\U0000260E'

        if keyb_type == admin_menu_keyboard:
            emoji_1 = '\U0001F4D2'
            emoji_2 = '\U0001F4D1'
            emoji_3 = '\U0001F5C4'

        return ReplyKeyboardMarkup(
            [
                [KeyboardButton(f'{emoji_1} {button[1]}')],
                [KeyboardButton(f'{emoji_2} {button[2]}')],
                [KeyboardButton(f'{emoji_3} {button[3]}')],
                # [KeyboardButton(f'\U00002699 {lang[4]}')],
            ],
            resize_keyboard=True,
            one_time_keyboard=True)
Beispiel #22
0
def process_distance_filter(update, context):
    cities = R.hgetall('1:cities').items()
    cities = sorted(cities, key=lambda item: item[1])
    button_list = [
        KeyboardButton(text=name.decode('utf-8')) for _, name in cities
    ]
    reply_markup = ReplyKeyboardMarkup(build_menu(button_list, n_cols=1),
                                       one_time_keyboard=True)
    context.bot.send_message(update.effective_chat.id,
                             'Выберите ваш город',
                             reply_markup=reply_markup)
Beispiel #23
0
def send_location(bot, update):
    location_button = KeyboardButton('Send current location',
                                     request_location=True)
    bot.send_message(
        chat_id=update.effective_message.chat_id,
        text='Please, share you location so we can find nearest gas stations.\n'
        'Tap the button if you are near gas station now, or choose location manually',
        reply_markup=ReplyKeyboardMarkup([[location_button]],
                                         one_time_keyboard=True,
                                         resize_keyboard=True))
    return LOCATION
Beispiel #24
0
def get_keyboard():
    contact_button = KeyboardButton('Прислать контакты', request_contact=True)
    location_button = KeyboardButton('Прислать координаты', request_location=True)
    my_keyboard = ReplyKeyboardMarkup([
                                        [
                                           'Список планет', 
                                           '/planet', 
                                           'Котэ'
                                        ],
                                        [
                                           'Полнолуние', 
                                           '/wordcount',
                                           'Сменить аватар'
                                        ],
                                        [
                                            contact_button, 
                                            location_button
                                        ]
                                      ], resize_keyboard=True)
    return my_keyboard
Beispiel #25
0
def generateKeyboard():
    events = "https://www.finnkino.fi/xml/Events/?listType=ComingSoon&includeVideos=false"
    s = requests.Session()
    res = s.get(events)
    root = ET.fromstring(res.text)
    keyboard = []
    for child in root:
        for i in child:
            if i.tag == "Title":
               keyboard.append(KeyboardButton(i.text))
    return keyboard
def issnextpass(bot, update):
    keyboard = [[
        KeyboardButton("Send location",
                       request_contact=False,
                       request_location=True)
    ]]
    update.message.reply_text('We need access to your current location!',
                              reply_markup=ReplyKeyboardMarkup(
                                  keyboard,
                                  resize_keyboard=True,
                                  one_time_keyboard=True))
Beispiel #27
0
    def __restart_command(self, update, context):
        self.__predictor.reset()
        buttons = [KeyboardButton(f'{self.__button_start}')]

        reply_markup = ReplyKeyboardMarkup(keyboard=self.build_menu(
            buttons, 2),
                                           resize_keyboard=True,
                                           one_time_keyboard=True)

        update.message.reply_text(text=f'{self.__welcome_text}',
                                  reply_markup=reply_markup)
Beispiel #28
0
    def menu_from_class_data(self, update: telegram.Update, msg=None):
        msg = msg if msg != None else self.menu_message
        tpl = Template(msg)
        ctx = self.default_context(update)

        context = Context(ctx)
        message = tpl.render(context)

        if update.effective_chat.type == "group" or update.effective_chat.type == "supergroup":
            menu_type = "inline"
        else:
            menu_type = self.menu_display

        if menu_type == "inline":
            ClassButton = InlineKeyboardButton
            ClassKeyboard = InlineKeyboardMarkup
        else:
            ClassButton = KeyboardButton
            ClassKeyboard = ReplyKeyboardMarkup

        replies = []
        buttons = []
        i = 0
        for state in self.transitions:
            if state in self.no_buttons:
                continue

            pre = self.pre_item[state] if state in self.pre_item else ''
            post = self.post_item[state] if state in self.post_item else ''
            state_shown = pre + state + post
            if menu_type == "inline":
                buttons.append(
                    InlineKeyboardButton(state_shown, callback_data=state))
            else:
                buttons.append(KeyboardButton(state_shown))
            i += 1

            if i == 2:
                replies.append(copy(buttons))
                buttons.clear()
                i = 0
        if (len(buttons) > 0):
            replies.append(copy(buttons))
        logger.trace("replies :: {}", repr(replies))

        if menu_type == "inline":
            kbd = InlineKeyboardMarkup(replies)
        else:
            kbd = ReplyKeyboardMarkup(replies,
                                      resize_keyboard=True,
                                      one_time_keyboard=True)

        logger.debug("{}", message)
        return message, kbd
Beispiel #29
0
def keyboard_cmds():
    command_buttons = [
        KeyboardButton("/help"),
        KeyboardButton("/nuria"),
        KeyboardButton("/aetm"),
        KeyboardButton("/capitulito"),
        KeyboardButton("pole"),
        KeyboardButton("/github"),
        KeyboardButton("/donaciones"),
        KeyboardButton("/start"),
    ]
    #Devuelve el telcado con 3 columnas y llamando a la funcion build que organiza el telcado
    return ReplyKeyboardMarkup(build_menu(command_buttons, n_cols=3))
Beispiel #30
0
def coordinates_handler(update, context):
    reply_markup = ReplyKeyboardMarkup(
        [[KeyboardButton(item) for item in WEATHER_CONVERSATION_COMMANDS]]
    )

    context.user_data["location"] = update.message.location
    update.message.reply_text(
        'Thank you. You location {} is captured'.format(context.user_data["location"]),
        reply_markup=reply_markup
    )
    return 1
    def message_settingstimes(self):
        """
		Called when the user sends the information which push time he wants to change
		"""
        if '🍜 Menu Push' in self.message.text:
            menuPushTime = self.message.user.pushTimes['menu']
            self.bot.sendMessage(self.message.user.chatID, (
                "You currently receive the menu push at " + menuPushTime +
                ". To change that, send me the new time in the format <b>HH:MM</b>. Please notice that it has to be "
                +
                "a quarter of an hour, e.g. 10:15 and that the push is always for the <b>current</b> day."
            ),
                                 parse_mode=ParseMode.HTML)
            self.message.user.tempParams['pushtimeToBeChanged'] = 'menu'
            self.message.user.expectedMessageType = 'changepushtime'
        elif '🕒 Lecture Plan Push' in self.message.text:
            lecturePushTime = self.message.user.pushTimes['lecture']
            self.bot.sendMessage(self.message.user.chatID, (
                "You currently receive the lecture push at " +
                lecturePushTime +
                ". To change that, send me the new time in the format <b>HH:MM</b>. Please notice that it has to be "
                +
                "a quarter of an hour, e.g. 17:15 and that the push is always for the <b>next</b> day."
            ),
                                 parse_mode=ParseMode.HTML)
            self.message.user.tempParams['pushtimeToBeChanged'] = 'lecture'
            self.message.user.expectedMessageType = 'changepushtime'
        elif '⏪ Back' in self.message.text:
            self.bot.sendMessage(
                self.message.user.chatID,
                'What do you want to change?',
                reply_markup=ReplyKeyboardMarkup(
                    [[KeyboardButton('️🧍 Personal Information')],
                     [KeyboardButton('📲 Subscription-Settings')],
                     [KeyboardButton('⏰ Push Time Settings')],
                     [KeyboardButton('🧨 Cancel')]],
                    resize_keyboard=True,
                    one_time_keyboard=True))
            self.message.user.expectedMessageType = 'settingstype'
        else:
            menuPushTime = self.message.user.pushTimes['menu']
            lecturePushTime = self.message.user.pushTimes['lecture']
            self.bot.sendMessage(
                self.message.user.chatID,
                "What push notification should come on another time? ",
                reply_markup=ReplyKeyboardMarkup(
                    [[
                        KeyboardButton(
                            ('🍜 Menu Push (currently ' + menuPushTime + ')'))
                    ],
                     [
                         KeyboardButton(('🕒 Lecture Plan Push (currently ' +
                                         lecturePushTime + ')'))
                     ], [KeyboardButton('⏪ Back')]],
                    resize_keyboard=True,
                    one_time_keyboard=True))
    def de_json(data):
        """
        Args:
            data (str):

        Returns:
            telegram.ReplyKeyboardMarkup:
        """
        if not data:
            return None

        data['keyboard'] = [KeyboardButton.de_list(keyboard) for keyboard in data['keyboard']]

        return ReplyKeyboardMarkup(**data)
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.ReplyKeyboardMarkup:
        """
        if not data:
            return None

        data = super(ReplyKeyboardMarkup, ReplyKeyboardMarkup).de_json(data, bot)

        data['keyboard'] = [KeyboardButton.de_list(keyboard, bot) for keyboard in data['keyboard']]

        return ReplyKeyboardMarkup(**data)