Python telegram 模块,ReplyKeyboardMarkup() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用telegram.ReplyKeyboardMarkup()

项目:verkehrsbot    作者:dirkonet    | 项目源码 | 文件源码
def nearest_stations(bot, update, count=5):
    with open('allstations.csv', newline='', encoding='utf-8') as infile:
        csv_reader = csv.reader(infile, delimiter=';')
        stations = [(int(row[0]), float(row[1]), float(row[2]), row[3]) for row in csv_reader]

        # distance sorting based on http://stackoverflow.com/a/28368926 by Sergey Ivanov
        coord = (float(update.message.location.latitude), float(update.message.location.longitude))
        pts = [geopy.Point(p[1], p[2], p[0]) for p in stations]
        sts = [p[3] for p in stations]
        onept = geopy.Point(coord[0], coord[1])
        alldist = [(p, geopy.distance.distance(p, onept).m) for p in pts]
        nearest = sorted(alldist, key=lambda x: (x[1]))[:count]
        nearest_points = [n[0] for n in nearest]
        nearest_distances = [n[1] for n in nearest]
        nearest_sts = [sts[int(n.altitude)] for n in nearest_points]
        msg = 'Nächstgelegene Stationen:'
        for s, d, p in zip(nearest_sts, nearest_distances, nearest_points):
            msg += '\n{} (<a href="https://www.google.de/maps?q={},{}">{:.0f}m</a>)'.format(s, p.latitude,
                                                                                            p.longitude, d)

        reply_keyboard = [[telegram.KeyboardButton(text='/Abfahrten {}'.format(n))] for n in nearest_sts]
        bot.sendMessage(chat_id=update.message.chat_id, text=msg, parse_mode='HTML',
                        reply_markup=telegram.ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))
项目:vk-channelify    作者:reo7sp    | 项目源码 | 文件源码
def recover(bot, update, db, users_state):
    user_id = update.message.from_user.id

    users_state[user_id] = dict()
    users_state[user_id]['channels'] = dict()
    keyboard = []
    keyboard_row = []
    for channel in db.query(DisabledChannel).filter(DisabledChannel.owner_id == str(user_id)).order_by(DisabledChannel.created_at.desc()):
        title = '{} ({})'.format(channel.vk_group_id, channel.channel_id)
        users_state[user_id]['channels'][title] = channel.channel_id
        keyboard_row.append(title)
        if len(keyboard_row) == 2:
            keyboard.append(keyboard_row)
            keyboard_row = []
    if len(keyboard_row) != 0:
        keyboard.append(keyboard_row)

    if len(keyboard) == 0:
        update.message.reply_text('??? ???????, ??????? ????? ????????????')
        del_state(update, users_state)
        return ConversationHandler.END
    else:
        update.message.reply_text('???????? ?????', reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True))
        return ASKED_CHANNEL_ID_IN_RECOVER
项目:mau_mau_bot    作者:jh0ker    | 项目源码 | 文件源码
def show_settings(bot, update):
    chat = update.message.chat

    if update.message.chat.type != 'private':
        send_async(bot, chat.id,
                   text=_("Please edit your settings in a private chat with "
                          "the bot."))
        return

    us = UserSetting.get(id=update.message.from_user.id)

    if not us:
        us = UserSetting(id=update.message.from_user.id)

    if not us.stats:
        stats = '??' + ' ' + _("Enable statistics")
    else:
        stats = '?' + ' ' + _("Delete all statistics")

    kb = [[stats], ['??' + ' ' + _("Language")]]
    send_async(bot, chat.id, text='??' + ' ' + _("Settings"),
               reply_markup=ReplyKeyboardMarkup(keyboard=kb,
                                                one_time_keyboard=True))
项目:mau_mau_bot    作者:jh0ker    | 项目源码 | 文件源码
def kb_select(bot, update, groups):
    chat = update.message.chat
    user = update.message.from_user
    option = groups[0]

    if option == '??':
        us = UserSetting.get(id=user.id)
        us.stats = True
        send_async(bot, chat.id, text=_("Enabled statistics!"))

    elif option == '??':
        kb = [[locale + ' - ' + descr]
              for locale, descr
              in sorted(available_locales.items())]
        send_async(bot, chat.id, text=_("Select locale"),
                   reply_markup=ReplyKeyboardMarkup(keyboard=kb,
                                                    one_time_keyboard=True))

    elif option == '?':
        us = UserSetting.get(id=user.id)
        us.stats = False
        us.first_places = 0
        us.games_played = 0
        us.cards_played = 0
        send_async(bot, chat.id, text=_("Deleted and disabled statistics!"))
项目:democracybot    作者:LiaungYip    | 项目源码 | 文件源码
def cmd_vote(bot: telegram.Bot, update: telegram.Update):
    cid = update.message.chat_id
    uid = update.message.from_user.id
    polls = get_polls(uid, bot)

    if update.message.chat.type != "private":
        bot.sendMessage(cid, text_private_chat_only)
        return ConversationHandler.END

    if len(polls) == 0:
        bot.sendMessage(cid, "You aren't eligible to vote in any polls.")
    else:
        keyboard_choices = [p["tag"] + ": " + p["title"] for p in polls]
        # keyboard array is a list of lists
        # because each list represents a new row
        # and we want each button on a separate row
        keyboard_array = [[k, ] for k in keyboard_choices]
        keyboard = ReplyKeyboardMarkup(keyboard_array,
                                       one_time_keyboard=True)
        bot.sendMessage(cid,
                        "Click the button for the poll you would like to vote in.",
                        reply_markup=keyboard)
    return state_vote_1
项目:BookingBot    作者:manu0466    | 项目源码 | 文件源码
def execute(self, chat_id, bot: Bot, update: Update):
        handled = False
        if update.message.text in self._buildings_dict:
            handled = True
            building_identifier = self._buildings_dict[update.message.text]
            classrooms = self.get_classroom_source().get_classrooms_in_building(building_identifier)
            keyboard_button = []
            counter = 0
            row = -1
            for classroom in classrooms:
                if counter == 0:
                    keyboard_button.append([])
                    row += 1
                keyboard_button[row].append(KeyboardButton("/"+classroom.get_name().lower()))
                counter += 1
                if counter == 3:
                    counter = 0
            keyboard_button.append(["/buildings"])
            reply_keyboard = ReplyKeyboardMarkup(keyboard_button)
            bot.send_message(chat_id=chat_id, text="Available classrooms", reply_markup=reply_keyboard)
        return handled
项目:bancolucas    作者:jacobogomez    | 项目源码 | 文件源码
def services(bot, update):
    reply_keyboard = [["Agregar Saldo"], ["Ver saldo"], ["Retirar"], ["Mis retiros"], ["Transferir"], ["Mis transferencias"], ["Recargar"],["Mis recargas"],
                      ["Menu Principal"]]
    response = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=False)
    update.message.reply_text("¿Que quieres hacer?", reply_markup=response)
    if response == "Ver saldo":
        return GET_BALANCE
    elif response == "Retirar":
        return WITHDRAW
    elif response == "Cuenta":
        return ACCOUNT_INFO
    elif response == "Transferir":
        return TRANSFERIR
    elif response == "Mis transferencias":
        return SHOW_TRANSFERS
    elif response == "Mis retiros":
        return SHOW_WITHDRAWS
    elif response == "Recargar":
        return RECARGAR
    elif response == "Mis recargas":
        return SHOW_RECHARGES
    elif response == "Menu Principal":
        return RETURN

    return ADD_BALANCE
项目:Telegram-Kraken-Bot    作者:Endogen    | 项目源码 | 文件源码
def trade_cmd(bot, update):
    reply_msg = "Buy or sell?"

    buttons = [
        KeyboardButton(KeyboardEnum.BUY.clean()),
        KeyboardButton(KeyboardEnum.SELL.clean())
    ]

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

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

    return WorkflowEnum.TRADE_BUY_SELL


# Save if BUY or SELL order and choose the currency to trade
项目:Telegram-Kraken-Bot    作者:Endogen    | 项目源码 | 文件源码
def trade_buy_sell(bot, update, chat_data):
    chat_data["buysell"] = update.message.text

    reply_msg = "Choose currency"

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

    # If SELL chosen, then include button 'ALL' to sell everything
    if chat_data["buysell"].upper() == KeyboardEnum.SELL.clean():
        cancel_btn.insert(0, KeyboardButton(KeyboardEnum.ALL.clean()))

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

    return WorkflowEnum.TRADE_CURRENCY


# Show confirmation to sell all assets
项目:Telegram-Kraken-Bot    作者:Endogen    | 项目源码 | 文件源码
def trade_price(bot, update, chat_data):
    chat_data["price"] = update.message.text

    reply_msg = "How to enter the volume?"

    buttons = [
        KeyboardButton(config["trade_to_currency"].upper()),
        KeyboardButton(KeyboardEnum.VOLUME.clean())
    ]

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

    reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2, footer_buttons=cancel_btn))

    update.message.reply_text(reply_msg, reply_markup=reply_mrk)
    return WorkflowEnum.TRADE_VOL_TYPE


# Save volume type decision and enter volume
项目:Telegram-Kraken-Bot    作者:Endogen    | 项目源码 | 文件源码
def orders_choose_order(bot, update):
    buttons = list()

    # Go through all open orders and create a button
    if orders:
        for order in orders:
            order_id = next(iter(order), None)
            buttons.append(KeyboardButton(order_id))
    else:
        update.message.reply_text("No open orders")
        return ConversationHandler.END

    msg = "Which order to close?"

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

    reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=1, footer_buttons=close_btn))

    update.message.reply_text(msg, reply_markup=reply_mrk)
    return WorkflowEnum.ORDERS_CLOSE_ORDER


# Close all open orders
项目:Telegram-Kraken-Bot    作者:Endogen    | 项目源码 | 文件源码
def bot_cmd(bot, update):
    reply_msg = "What do you want to do?"

    buttons = [
        KeyboardButton(KeyboardEnum.UPDATE_CHECK.clean()),
        KeyboardButton(KeyboardEnum.UPDATE.clean()),
        KeyboardButton(KeyboardEnum.RESTART.clean()),
        KeyboardButton(KeyboardEnum.SHUTDOWN.clean()),
        KeyboardButton(KeyboardEnum.SETTINGS.clean()),
        KeyboardButton(KeyboardEnum.CANCEL.clean())
    ]

    reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2))
    update.message.reply_text(reply_msg, reply_markup=reply_mrk)

    return WorkflowEnum.BOT_SUB_CMD


# Execute chosen sub-cmd of 'bot' cmd
项目:Telegram-Kraken-Bot    作者:Endogen    | 项目源码 | 文件源码
def chart_cmd(bot, update):
    reply_msg = "Choose currency"

    buttons = list()
    for coin, url in config["coin_charts"].items():
        buttons.append(KeyboardButton(coin))

    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.CHART_CURRENCY


# Get chart URL for every coin in config
项目:Telegram-Kraken-Bot    作者:Endogen    | 项目源码 | 文件源码
def settings_cmd(bot, update):
    settings = str()
    buttons = list()

    # Go through all settings in config file
    for key, value in config.items():
        settings += key + " = " + str(value) + "\n\n"
        buttons.append(KeyboardButton(key.upper()))

    # Send message with all current settings (key & value)
    update.message.reply_text(settings)

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

    msg = "Choose key to change value"

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

    return WorkflowEnum.SETTINGS_CHANGE


# Change setting
项目:Telegram-Kraken-Bot    作者:Endogen    | 项目源码 | 文件源码
def keyboard_cmds():
    command_buttons = [
        KeyboardButton("/trade"),
        KeyboardButton("/orders"),
        KeyboardButton("/balance"),
        KeyboardButton("/price"),
        KeyboardButton("/value"),
        KeyboardButton("/chart"),
        KeyboardButton("/history"),
        KeyboardButton("/funding"),
        KeyboardButton("/bot")
    ]

    return ReplyKeyboardMarkup(build_menu(command_buttons, n_cols=3))


# Generic custom keyboard that shows YES and NO
项目:TelegramBots    作者:d-qoi    | 项目源码 | 文件源码
def eventSelectEditing(self, bot, update, user_data):

        user_data[user_data['editing_choice']] = update.message.text
        reply_text = ""

        if user_data['editing_choice'] == 'Time' and not isTimeString(update.message.text):
            reply_text = "Your time string is not formatted correctly, please try again.\n\n"
            user_data['Time'] = None
        elif user_data['editing_choice'] == 'Date' and not isDateString(update.message.text):
            reply_text = 'You Date string is not formatted correctly (m/d/20xx), please try again.\n\n'
            user_data['Date'] = None

        reply_keyboard = [['Name', 'Time', 'Date'],
                              ['Group','Place'],
                              ['Description']]

        if all (key in user_data for key in ['Name','Time','Date','Description','Place','Group']):
            reply_keyboard.append(['Cancel','Done'])
        else:
            reply_keyboard.append(['Cancel'])
        markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
        reply_text += "Please select which you would like to edit, once you've entered something for all of these, you will be able to create the event."
        update.message.reply_text(reply_text, reply_markup=markup)
        return EVENTSELECT
项目:helpdeskbot    作者:juliarizza    | 项目源码 | 文件源码
def start(bot, update):
    """
        Shows an welcome message and help info about the available commands.
    """
    me = bot.get_me()

    # Welcome message
    msg = _("Hello!\n")
    msg += _("I'm {0} and I came here to help you.\n").format(me.first_name)
    msg += _("What would you like to do?\n\n")
    msg += _("/support - Opens a new support ticket\n")
    msg += _("/settings - Settings of your account\n\n")

    # Commands menu
    main_menu_keyboard = [[telegram.KeyboardButton('/support')],
                          [telegram.KeyboardButton('/settings')]]
    reply_kb_markup = telegram.ReplyKeyboardMarkup(main_menu_keyboard,
                                                   resize_keyboard=True,
                                                   one_time_keyboard=True)

    # Send the message with menu
    bot.send_message(chat_id=update.message.chat_id,
                     text=msg,
                     reply_markup=reply_kb_markup)
项目:helpdeskbot    作者:juliarizza    | 项目源码 | 文件源码
def settings(bot, update):
    """
        Configure the messages language using a custom keyboard.
    """
    # Languages message
    msg = _("Please, choose a language:\n")
    msg += "en_US - English (US)\n"
    msg += "pt_BR - Português (Brasil)\n"

    # Languages menu
    languages_keyboard = [
        [telegram.KeyboardButton('en_US - English (US)')],
        [telegram.KeyboardButton('pt_BR - Português (Brasil)')]
    ]
    reply_kb_markup = telegram.ReplyKeyboardMarkup(languages_keyboard,
                                                   resize_keyboard=True,
                                                   one_time_keyboard=True)

    # Sends message with languages menu
    bot.send_message(chat_id=update.message.chat_id,
                     text=msg,
                     reply_markup=reply_kb_markup)
项目:ShiokBot    作者:kianhean    | 项目源码 | 文件源码
def traffic(bot, update, args):
    """ Get Traffic Updates """

    if len(args) == 0:
        final_string = 'Please enter either traffic Woodlands or traffic Tuas'
        custom_keyboard = [['/traffic Tuas', '/traffic Woodlands']]
        reply_markup = ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True, selective=True)
        bot.sendMessage(update.message.chat_id, final_string, reply_markup=reply_markup)

    else:
        bot.sendMessage(update.message.chat_id, text='I go turn on my spycam, please wait',
                        parse_mode='HTML')
        bot.sendChatAction(update.message.chat_id, action=ChatAction.TYPING)
        final_string = gov.traffic_get(args[0])
        bot.sendMessage(update.message.chat_id, text=final_string, parse_mode='HTML')
        botan_track(update.message.from_user.id, update.message, update.message.text)
项目:youtubetomp3bot    作者:pcanapa    | 项目源码 | 文件源码
def __init__(self, token, host, port, cert, cert_key, working_dir):

        self.token = token
        self.host = host
        self.port = port
        self.cert = cert
        self.cert_key = cert_key

        self.bot = telegram.Bot(self.token)
        self.app = Flask(__name__)
        self.context = (self.cert, self.cert_key)
        self.working_dir = working_dir
        self.kb = [[telegram.KeyboardButton('Offer me a coffee'), telegram.KeyboardButton('Source Code'), telegram.KeyboardButton('Vote Me')]]
        self.kb_markup = telegram.ReplyKeyboardMarkup(self.kb, resize_keyboard=True)
项目:RaiWalletBot    作者:SergiySW    | 项目源码 | 文件源码
def custom_keyboard(bot, chat_id, buttons, text):
    reply_markup = ReplyKeyboardMarkup(buttons, resize_keyboard = True)
    try:
        bot.sendMessage(chat_id=chat_id, 
                     text=text, 
                     parse_mode=ParseMode.MARKDOWN,
                     disable_web_page_preview=True,
                     reply_markup=reply_markup)
    except BadRequest:
        bot.sendMessage(chat_id=chat_id, 
                     text=replace_unsafe(text), 
                     parse_mode=ParseMode.MARKDOWN,
                     disable_web_page_preview=True,
                     reply_markup=reply_markup)
    except RetryAfter:
        sleep(240)
        bot.sendMessage(chat_id=chat_id, 
                     text=text, 
                     parse_mode=ParseMode.MARKDOWN,
                     disable_web_page_preview=True,
                     reply_markup=reply_markup)
    except TimedOut:
        sleep(10)
        bot.sendMessage(chat_id=chat_id, 
                     text=text, 
                     parse_mode=ParseMode.MARKDOWN,
                     disable_web_page_preview=True,
                     reply_markup=reply_markup)
    except:
        sleep(1)
        bot.sendMessage(chat_id=chat_id, 
                     text=text, 
                     parse_mode=ParseMode.MARKDOWN,
                     disable_web_page_preview=True,
                     reply_markup=reply_markup)
项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
def reply_to_start_command(bot, update):
    reply_keyboard = [['???????? ??????', '?????? ??????', '????????? ??????']]
    update.message.reply_text(
        "??????! ? ???, ??????? ??????? ????????? ??????? ??????.",
        reply_markup=ReplyKeyboardMarkup(reply_keyboard)
    )
项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
def reply_to_start_command(bot, update):
    reply_keyboard = [['???????? ??????', '?????? ??????', '????????? ??????']]
    update.message.reply_text(
        "??????! ? ???, ??????? ??????? ????????? ??????? ??????.",
        reply_markup=ReplyKeyboardMarkup(reply_keyboard)
    )
项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
def get_name(bot, update, user_data):
    user_name = update.message.text
    if len(user_name.split(" ")) < 2:
        update.message.reply_text("??????????, ???????? ??? ? ???????")
        return "name"
    else:
        user_data["name"] = user_name
        reply_keyboard = [["1", "2", "3", "4", "5"]]

        update.message.reply_text(
            "?????????? ?? ??? ????? ??????? ?? ????? ?? 1 ?? 5",
            reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
        )
        return "attitude"
项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
def attitude(bot, update, user_data):
    user_data["attitude"] = update.message.text

    reply_keyboard = [["1", "2", "3", "4", "5"]]

    update.message.reply_text(
        "??? ?? ???? ???????? ??????? ?? ????? ?? 1 ?? 5",
        reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
    )
    return "understanding"
项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
def comment(bot, update, user_data):
    user_data["comment"] = update.message.text
    reply_keyboard = [['???????? ??????', '?????? ??????']]
    update.message.reply_text("??????? ?? ??? ???????????!", reply_markup=ReplyKeyboardMarkup(reply_keyboard))
    return ConversationHandler.END
项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
def reply_to_start_command(bot, update, user_data):
    first_name = update.effective_user.first_name
    last_name = update.effective_user.last_name
    avatar = get_avatar(user_data)
    text = "??????, {} {}! ? ???, ??????? ???????? ??????? /start".format(first_name, avatar)
    logging.info("???????????? {} {} ????? {}".format(first_name, last_name, "/start"))
    update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup(get_keyboard(), resize_keyboard=True))
项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
def change_avatar_step1(bot, update, user_data):
    reply_keyboard = []
    for index, ava in enumerate(avatars):
        button = "/avatar {} {}".format(index, ava)
        button = emojize(button, use_aliases=True)
        reply_keyboard.append(button)
    text = '?????? ???????? {}'.format(get_avatar(user_data))
    update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup([reply_keyboard], resize_keyboard=True))
项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
def change_avatar_step2(bot, update, args, user_data):
    try:
        ava = avatars[int(args[0])]
        user_data['avatar'] = emojize(ava, use_aliases=True)
        update.message.reply_text('???????? ????????', reply_markup=ReplyKeyboardMarkup(get_keyboard(), resize_keyboard=True))
    except(IndexError, ValueError):
        update.message.reply_text('?????????? ??? ???')
项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
def reply_to_start_command(bot, update, user_data):
    user = get_user(update.effective_user, user_data)
    text = "??????, {} {}! ? ???, ??????? ???????? ??????? /start".format(user.first_name, user.avatar)
    logging.info("???????????? {} {} ????? {}".format(user.first_name, user.last_name, "/start"))
    update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup(get_keyboard(), resize_keyboard=True))
项目:simplebot    作者:korneevm    | 项目源码 | 文件源码
def change_avatar_step1(bot, update, user_data):
    user = get_user(update.effective_user, user_data)
    reply_keyboard = []
    for index, ava in enumerate(avatars):
        button = "/avatar {} {}".format(index, ava)
        button = emojize(button, use_aliases=True)
        reply_keyboard.append(button)
    text = '?????? ???????? {}'.format(get_avatar(user_data))
    update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup([reply_keyboard], resize_keyboard=True))
项目:telegram_robot    作者:uts-magic-lab    | 项目源码 | 文件源码
def start(bot, update):
    hiKey = KeyboardButton("Hi", callback_data="Bonjour")
    howRU = KeyboardButton("How are you?")
    bye = KeyboardButton("Bye")
    introduce = KeyboardButton("I'm Gutsy")

    keyboard = [
    [hiKey, howRU],
    [bye, introduce]
    ]

    reply_markup = ReplyKeyboardMarkup(keyboard)

    update.message.reply_text('Please choose:', reply_markup=reply_markup)
项目:telegram_robot    作者:uts-magic-lab    | 项目源码 | 文件源码
def start(self, bot, update):
        keyboardStr = [
            ["-", "?", "+"],
            ["?", " ", "?"],
            ["?", "?", "?"],
            ["STOP"],
        ]

        headKeyboard = [
            [" ", "?", " "],
            ["?", " ", "?"],
            [" ", "?", " "],
            ["Paparazzi"],
        ]

        gripperKeyboard = [
            ["Open Left", "Open Right"],
            ["Close Half Left", "Close Half Right"],
            ["Close Left", "Close Right"]
        ]

        keyboard = self.createKeyboard(keyboardStr)

        reply_markup = ReplyKeyboardMarkup(keyboard)

        update.message.reply_text(
            'Tap the arrows to move the PR2:', reply_markup=reply_markup)
项目:vk-channelify    作者:reo7sp    | 项目源码 | 文件源码
def new_in_state_asked_vk_group_link(bot, update, users_state):
    vk_url = update.message.text
    vk_domain = vk_url.split('/')[-1]
    users_state[update.message.from_user.id] = dict()
    users_state[update.message.from_user.id]['vk_domain'] = vk_domain

    update.message.reply_text('???????! ??????:')
    update.message.reply_text('1. ???????? ????? ?????. ????? ???????????? ????????????')
    keyboard = [['? ??????']]
    update.message.reply_text('2. ???????? ????? ???? (@vk_channelify_bot) ? ?????????????? ??????',
                              reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True))
    return ASKED_CHANNEL_ACCESS_IN_NEW
项目:vk-channelify    作者:reo7sp    | 项目源码 | 文件源码
def filter_by_hashtag(bot, update, db, users_state):
    user_id = update.message.from_user.id

    users_state[user_id] = dict()
    users_state[user_id]['channels'] = dict()
    keyboard = []
    keyboard_row = []
    for channel in db.query(Channel).filter(Channel.owner_id == str(user_id)).order_by(Channel.created_at.desc()):
        try:
            channel_chat = bot.get_chat(chat_id=channel.channel_id)
            users_state[user_id]['channels'][channel_chat.title] = channel.channel_id
            keyboard_row.append(channel_chat.title)
            if len(keyboard_row) == 2:
                keyboard.append(keyboard_row)
                keyboard_row = []
        except telegram.TelegramError:
            logger.warning('filter_by_hashtag: cannot get title of channel {}'.format(channel.channel_id))
            traceback.print_exc()
    if len(keyboard_row) != 0:
        keyboard.append(keyboard_row)

    update.message.reply_text('???????? ?????', reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True))
    return ASKED_CHANNEL_ID_IN_FILTER_BY_HASHTAG
项目:UnivaqBot    作者:giacomocerquone    | 项目源码 | 文件源码
def discab_keyboard(bot, update):
    """
    Command that shows keyboard of sections for:
    discab_news, discabon and discaboff
    """

    keys = [['News del Dipartimento'], ['Area Biotecnologie'], ['Area Medica'],
            ['Area Scienze Motorie'], ['Area Psicologia'], ['Chiudi']]

    bot.sendMessage(update.message.chat_id,
                    'Scegli la sezione:',
                    reply_markup=telegram.ReplyKeyboardMarkup(
                        keys, one_time_keyboard=True))

    return "discab"
项目:UnivaqBot    作者:giacomocerquone    | 项目源码 | 文件源码
def mesva_keyboard(bot, update):
    """
    Command that shows keyboard of sections for:
    mesva_news, mesvaon and mesvaoff
    """

    keys = [['In Evidenza'], ['Area Medicina'], ['Area Scienze Ambientali'],
            ['Area Scienze Biologiche'], ['Chiudi']]

    bot.sendMessage(update.message.chat_id,
                    'Scegli la sezione:',
                    reply_markup=telegram.ReplyKeyboardMarkup(
                        keys, one_time_keyboard=True))

    return "mesva"
项目:UnivaqBot    作者:giacomocerquone    | 项目源码 | 文件源码
def univaq(bot, update):
    """
    Command that shows keyboard of sections for:
    inevidenza, ultimissime, univaqon, univaqoff
    """

    keys = [['In Evidenza'], ['Ultimissime'], ['Chiudi']]

    bot.sendMessage(update.message.chat_id,
                    'Scegli la sezione:',
                    reply_markup=telegram.ReplyKeyboardMarkup(
                        keys, one_time_keyboard=True))

    return "univaq"
项目:UnivaqBot    作者:giacomocerquone    | 项目源码 | 文件源码
def section_keyboard(bot, update):
    """
    Command that shows keyboard of departments for:
    news, newson and newsoff
    """

    keys = [['Univaq'], ['Disim'], ['Mesva'],
            ['Discab'], ['Chiudi']]

    bot.sendMessage(update.message.chat_id,
                    'Scegli il dipartimento:',
                    reply_markup=telegram.ReplyKeyboardMarkup(
                        keys, one_time_keyboard=True))

    return "department"
项目:UnivaqBot    作者:giacomocerquone    | 项目源码 | 文件源码
def feedback_command(bot, update):
    """Defining the command to ask for user's feedback"""

    keys = [['Lascia un messaggio agli sviluppatori'], ['Chiudi']]

    bot.sendMessage(update.message.chat_id,
                    'Cosa desideri fare?',
                    reply_markup=telegram.ReplyKeyboardMarkup(
                        keys, one_time_keyboard=True))

    return "send_feedback"
项目:python-telegram-dialog-bot    作者:Saluev    | 项目源码 | 文件源码
def _convert_answer_part(self, answer_part):
        if isinstance(answer_part, str):
            return Message(answer_part)
        if isinstance(answer_part, (collections.abc.Iterable, Keyboard)):
            # ???????????
            resize_keyboard = False
            one_time_keyboard = True

            if isinstance(answer_part, collections.abc.Iterable):
                answer_part = list(answer_part)
            else:
                one_time_keyboard = answer_part.one_time_keyboard
                resize_keyboard = answer_part.resize_keyboard
                answer_part = answer_part.markup

            if isinstance(answer_part[0], str):
                # ???! ????????? ??? ?????????????? ??? ??????.
                # ??????, ??? ???? ?????????? ??????????? -- ??? ???? ??????.
                return ReplyKeyboardMarkup([answer_part], one_time_keyboard=one_time_keyboard,
                                           resize_keyboard=resize_keyboard)
            elif isinstance(answer_part[0], collections.abc.Iterable):
                # ????????? ???????????
                answer_part = list(map(list, answer_part))
                if isinstance(answer_part[0][0], str):
                    # ???!
                    return ReplyKeyboardMarkup(answer_part, one_time_keyboard=one_time_keyboard,
                                               resize_keyboard=resize_keyboard)
        if isinstance(answer_part, Inline):
            return answer_part.convert()
        return answer_part
项目:AlarmBot    作者:guysoft    | 项目源码 | 文件源码
def new_alarm(self, bot, update):
        keyboard = [[InlineKeyboardButton("Daily"),
                     InlineKeyboardButton("Weekday Only")],
        [InlineKeyboardButton("Close")]]

        reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)

        update.message.reply_text('Select type of alarm, or /cancel to cancel:', reply_markup=reply_markup)
        return self.ALARM_TYPE
项目:AlarmBot    作者:guysoft    | 项目源码 | 文件源码
def set_timezone(self, bot, update):
        keyboard = []

        for continent in sorted(get_timezones().keys()):
            keyboard.append([InlineKeyboardButton(continent)])

        reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)
        update.message.reply_text('Please select a continent, or /cancel to cancel:', reply_markup=reply_markup)
        return self.TIMEZONE_CONTINENT
项目:AlarmBot    作者:guysoft    | 项目源码 | 文件源码
def timezone_continent(self, bot, update):
        reply = handle_cancel(update)
        if reply is None:
            keyboard = []
            self.selected_continent = update.message.text
            for continent in sorted(get_timezones()[self.selected_continent]):
                keyboard.append([InlineKeyboardButton(continent)])
            reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)
            update.message.reply_text('Please select a timezone, or /cancel to cancel:', reply_markup=reply_markup)

            return self.TIMEZONE_TIME
        return ConversationHandler.END
项目:heydjbot    作者:mongonauta    | 项目源码 | 文件源码
def chat(bot, update):
    user = update.message.from_user
    logger.info('chat - %s' % user)

    update.message.reply_text(
        "Sobre que quieres hablar?",
        reply_markup=ReplyKeyboardMarkup(
            GENRE_KEYBOARD,
            one_time_keyboard=True,
            resize_keyboard=True
        )
    )

    return GENRE_SELECTOR
项目:heydjbot    作者:mongonauta    | 项目源码 | 文件源码
def search_song(bot, update):
    user = update.message.from_user
    song_name = update.message.text
    logger.info('search_song for user %s and song name %s' % (user, song_name))

    url = '{}/song/{}'
    resp = requests.get(
        url=url.format(API_SERVER, song_name)
    )

    if resp.status_code != 200 or not resp.json():
        update.message.reply_text('Lo siento pero lo que estás buscando es demasiado raro incluso para Spotify')
        return ConversationHandler.END

    else:
        song_list = json.loads(resp.content)

        update.message.reply_text(
            u"""{} (Popularidad% {})\nActividad: {}\nAlbum: {}\nArtistas: {}\n{}\n{}""".format(
                song_list[0]['track_name'],
                song_list[0]['track_popularity'],
                song_list[0]['activity'],
                song_list[0]['track_album_name'],
                ','.join(a['name'] for a in song_list[0]['artists']),
                song_list[0]['thumb'],
                song_list[0]['external_url'],
            ),
            reply_markup=ReplyKeyboardMarkup(
                SONG_KEYBOARD,
                one_time_keyboard=True,
                resize_keyboard=True
            )
        )

        bot.song_cache = song_list[0]

    return SONG_ACTION
项目:heydjbot    作者:mongonauta    | 项目源码 | 文件源码
def choose_activity(bot, update):
    user = update.message.from_user
    logger.info('choose_activity - %s' % user)

    update.message.reply_text(
        "Que tipo de playlist quieres?",
        reply_markup=ReplyKeyboardMarkup(
            ACTIVITY_KEYBOARD,
            one_time_keyboard=True,
            resize_keyboard=True
        )
    )

    return ACTIVITY_SELECTOR
项目:heydjbot    作者:mongonauta    | 项目源码 | 文件源码
def train(bot, update):
    user = update.message.from_user
    logger.info('show_song_to_clasify %s' % user)

    resp = requests.get(
        url='{}/user_info/{}/'.format(API_SERVER, user.id)
    )

    if not resp.json():
        update.message.reply_text(
            'Sorry {}, but I can\'t do that. Please, use "connect" command'.format(user['first_name'])
        )

    else:
        resp = requests.get(
            url='{}/train/{}/'.format(API_SERVER, user.id)
        )

        song = resp.json()['song'] if 'song' in resp.json() else None
        if song:
            bot.song_cache = song
            update.message.reply_text(
                u"""
                    Choose one activity for this song:\n\n
                    Title: {}\n
                    Artist: {}\n
                    Album: {}\n
                """.format(song[1], song[4], song[2]),
                reply_markup=ReplyKeyboardMarkup(ACTIVITY_KEYBOARD, one_time_keyboard=True, resize_keyboard=True)
            )

        else:
            update.message.reply_text("Server error. %s" % resp.json())

    return SAVE_SONG
项目:heydjbot    作者:mongonauta    | 项目源码 | 文件源码
def save_classification(bot, update):
    user = update.message.from_user
    logger.info('save_classification(%s) %s - %s' % (user, bot.song_cache, update.message.text))

    resp = requests.get(
        url='{}/user_info/{}/'.format(API_SERVER, user.id)
    )

    if not resp.json():
        update.message.reply_text(
            'Sorry {}, but I can\'t do that. Please, use "connect" command'.format(user['first_name'])
        )

    else:
        resp = requests.get(
            url='{}/classify/{}/{}'.format(
                API_SERVER,
                bot.song_cache[0],
                ACTIVITY_KEYBOARD[0].index(update.message.text)
            )
        )

        result = resp.json()
        resp = requests.get(
            url='{}/stats/{}/'.format(
                API_SERVER,
                user.id
            )
        )
        result['total'] = resp.json()['total']
        result['classified'] = resp.json()['classified']

        update.message.reply_text(
            'Result: %s \n\n Statistics:\n %s' % (result, resp.json()),
            reply_markup=ReplyKeyboardMarkup([[NAVIGATION_KEYBOARD[1]]], one_time_keyboard=True, resize_keyboard=True)
        )
    return SAVE_SONG
项目:telegram-yt_mp3-bot    作者:Javinator9889    | 项目源码 | 文件源码
def key_ben(bot, update,chat_id):
    keyboard = [
    ['While downloading','Other...']
    ]
    reply_markup = ReplyKeyboardMarkup(
    keyboard = keyboard, 
    resize_keyboard=True, 
    one_time_keyboard=True)
    bot.sendMessage(chat_id=chat_id,
        text="_When are you having your error?_ *(use the keyboard that appears just below)*",
        parse_mode=telegram.ParseMode.MARKDOWN, 
        reply_markup=reply_markup)