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

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

项目:ShiokBot    作者:kianhean    | 项目源码 | 文件源码
def call_handler(bot, update):
    """ https://stackoverflow.com/questions/39121678/updating-messages-with-inline-keyboards-using-callback-queries """

    if update.callback_query.data == 'update_taxi':
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text="Refreshing Promo Codes...")

        text_ = "<b>:black_large_square:List of Uber Promo Codes (Latest on Top)</b> \n\n"
        text_ += promo.get_code(1, smart=True)
        text_ += "\n<b>:white_check_mark:List of Grab Promo Codes (Latest on Top)</b> \n\n"
        text_ += promo.get_code(0, smart=True)
        text_ += "\n :repeat:Last Update: " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # Update Feature with Inline Keyboard
        promo_keyboard = InlineKeyboardButton(text="Update!", callback_data="update_taxi")
        custom_keyboard = [[promo_keyboard]]
        reply_markup = InlineKeyboardMarkup(custom_keyboard)

        bot.editMessageText(
            message_id=update.callback_query.message.message_id,
            chat_id=update.callback_query.message.chat.id,
            text=emojize(text_, use_aliases=True),
            parse_mode='HTML',
            reply_markup=reply_markup
        )
项目:VocaBot    作者:bomjacob    | 项目源码 | 文件源码
def keyboard(key, counts):
    # We don't want a keyboard if there's no results
    if counts[1] == 0:
        return None

    cur_page = counts[0] // 3 + 1
    last_page = math.ceil((counts[1]) / 3)

    data = 'page|{}|{}'.format(key, '{}')
    buttons = [InlineKeyboardButton('First' if cur_page > 1 else ' ',
                                    callback_data=data.format(1) if cur_page > 1 else 'page'),
               InlineKeyboardButton('Previous'.format(cur_page - 1) if cur_page > 1 else '?',
                                    callback_data=data.format((cur_page - 1)) if cur_page > 1 else 'page'),
               InlineKeyboardButton('•{}•'.format(cur_page),
                                    callback_data='page'),
               InlineKeyboardButton('Next'.format(cur_page + 1) if cur_page < last_page else '?',
                                    callback_data=data.format(cur_page + 1) if cur_page < last_page else 'page'),
               InlineKeyboardButton('Last'.format(last_page) if cur_page < last_page else ' ',
                                    callback_data=data.format(last_page) if cur_page < last_page else 'page')]
    return InlineKeyboardMarkup([buttons])
项目:forushandeBot    作者:pouya-barzegar    | 项目源码 | 文件源码
def build_menu(buttons,
               n_cols,
               header_buttons=None,
               footer_buttons=None):
    """
    :param buttons: a list of buttons.
    :param n_cols:  how many columns to show the butt,ons in
    :param header_buttons:  list of buttons appended to the beginning
    :param footer_buttons:  list of buttons added to the end
    :return: the menu
    """
    menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
    print(buttons)
    logger.debug("buttons created")
    if header_buttons:
        menu.insert(0, header_buttons)
    if footer_buttons:
        menu.append(footer_buttons)
    logger.debug("header and footer buttons added")
    print(InlineKeyboardButton(menu))
    return InlineKeyboardMarkup(menu)
项目:teamSpeakTelegram    作者:jossalgon    | 项目源码 | 文件源码
def start(bot, update, args):
    message = update.message
    user = message.from_user
    res = False

    link = "http://www.teamspeak.com/invite/%s/" % TS_HOST
    reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton(_('Connect TS'), url=link)]])

    if args:
        res = utils.validate_invitation_token(token=args[0], user_id=user.id, name=user.first_name)

    if res:
        text = _("Welcome %s you're now activated, using /who or /ts you can check who's in teamspeak.") % \
               user.first_name
    elif utils.is_allow(user.id):
        text = _("Hello %s, using /who or /ts you can check who's in teamspeak.") % user.first_name
    else:
        reply_markup = None
        text = _("Welcome, ask admin to generate an invitation link by /generate")
    bot.sendMessage(message.chat_id, text, reply_to_message_id=message.message_id, reply_markup=reply_markup)
项目:teamSpeakTelegram    作者:jossalgon    | 项目源码 | 文件源码
def ts_view(bot, update, message_id=None, chat_id=None):
    message = update.message
    if is_allow(update.effective_user.id):
        res = get_ts_view()

        keyboard = [[InlineKeyboardButton(_("Update"), callback_data='TS_UPDATE')]]
        reply_markup = InlineKeyboardMarkup(keyboard)

        if message_id and chat_id:
            bot.edit_message_text(text=res, chat_id=chat_id, message_id=message_id, reply_markup=reply_markup,
                                  parse_mode='Markdown')
        else:
            bot.send_message(message.chat.id, res, reply_to_message_id=message.message_id, reply_markup=reply_markup,
                             parse_mode='Markdown')
    else:
        bot.send_message(message.chat.id, _("You aren't allow to use this"), reply_to_message_id=message.message_id)
项目:telegram_robot    作者:uts-magic-lab    | 项目源码 | 文件源码
def do_image_stuff(self, update):
        # Get topics of type Image
        topics_and_types = rospy.get_published_topics()
        image_topics = []
        for top, typ in topics_and_types:
            if typ == 'sensor_msgs/Image':
                image_topics.append(top)

        keyboard = []
        for topicname in image_topics:
            keyboard.append([InlineKeyboardButton(
                topicname, callback_data=topicname)])

        reply_markup = InlineKeyboardMarkup(keyboard)

        update.message.reply_text('Choose image topic:',
                                  reply_markup=reply_markup)
项目:telegram-icecast2-bot    作者:hmsuorg    | 项目源码 | 文件源码
def start_tcb(self, bot, update, args):

        """
        start_tcb - callback triggered on /start command

        :param bot: bot object comes from telegram API
        :param update: update object comes from telegram API
        :param args: our custom args

        """

        user_data = bot.get_chat(update.message.chat_id)

        bot.sendMessage(
            chat_id=update.message.chat_id, text="Hello {}, I'm HMSU Radio Bot.".format(user_data.username)
        )

        # keyboard = [[InlineKeyboardButton("Get radiokey", callback_data='1'), InlineKeyboardButton("Help", callback_data='2')]]

        # reply_markup = InlineKeyboardMarkup(keyboard)

        # update.message.reply_text('Please choose:', reply_markup=reply_markup)


        bot.sendMessage(chat_id=update.message.chat_id, text="Type /help for full list of commands")
项目:street-agitation-telegram-bot    作者:Kurpilyansky    | 项目源码 | 文件源码
def process(self):
        event = models.AgitationEvent.objects.select_related('place__region', 'cubeusageinevent').filter(id=self._event_id).first()
        if not event or event.is_canceled or not event.need_cube:
            return
        region = event.place.region
        if not region.registrations_chat_id:
            return
        if self._prev_message_id:
            utils.safe_delete_message(self._bot, region.registrations_chat_id, self._prev_message_id)
        cube_usage = event.cube_usage
        if cube_usage and cube_usage.delivered_from and cube_usage.delivered_by:
            return
        new_message = self._bot.send_message(region.registrations_chat_id,
                                             '?????????? ????????? ??? ?? %s %s' % (event.show(), event.place.show()),
                                             parse_mode='Markdown',
                                             reply_markup=InlineKeyboardMarkup([[
                                                InlineKeyboardButton(
                                                    '????????????',
                                                    callback_data=TRANSFER_CUBE_TO_EVENT + str(event.id))]]))
        self._prev_message_id = new_message.message_id
        return self.repeat()
项目:street-agitation-telegram-bot    作者:Kurpilyansky    | 项目源码 | 文件源码
def process(self):
        event = models.AgitationEvent.objects.select_related('place__region', 'cubeusageinevent').filter(id=self._event_id).first()
        if not event or event.is_canceled or not event.need_cube:
            return
        region = event.place.region
        if not region.registrations_chat_id:
            return
        if self._prev_message_id:
            utils.safe_delete_message(self._bot, region.registrations_chat_id, self._prev_message_id)
        cube_usage = event.cube_usage
        if cube_usage and cube_usage.shipped_to and cube_usage.shipped_by:
            return
        new_message = self._bot.send_message(region.registrations_chat_id,
                                             '?????????? ?????? ??? ????? %s %s' % (event.show(), event.place.show()),
                                             parse_mode='Markdown',
                                             reply_markup=InlineKeyboardMarkup([[
                                                InlineKeyboardButton(
                                                    '????????????',
                                                    callback_data=TRANSFER_CUBE_TO_EVENT + str(event.id))]]))
        self._prev_message_id = new_message.message_id
        return self.repeat()
项目:ptbtest    作者:Eldinnie    | 项目源码 | 文件源码
def test_sendMessage(self):
        keyb = InlineKeyboardMarkup(
            [[InlineKeyboardButton(
                "test 1", callback_data="test1")],
             [InlineKeyboardButton(
                 "test 2", callback_data="test2")]])
        self.mockbot.sendMessage(
            1,
            "test",
            parse_mode=telegram.ParseMode.MARKDOWN,
            reply_markup=keyb,
            disable_notification=True,
            reply_to_message_id=334,
            disable_web_page_preview=True)
        data = self.mockbot.sent_messages[-1]

        self.assertEqual(data['method'], "sendMessage")
        self.assertEqual(data['chat_id'], 1)
        self.assertEqual(data['text'], "test")
        self.assertEqual(
            eval(data['reply_markup'])['inline_keyboard'][1][0][
                'callback_data'], "test2")
项目:walkdir-telegram-bot    作者:deepserket    | 项目源码 | 文件源码
def start(bot, update):
    global bot_
    bot_ = bot
    logger.info("from {}: /start".format(update.message.chat_id))

    if update.message.chat_id not in ADMINS:
        update.message.reply_text("You aren't an admin!")

        for id_ in ADMINS: # Warning to the admins
            bot.send_message(chat_id=id_,
                   text="{} attempted to access".format(update.message.chat_id))
        return

    term.current_dir = term.start_dir
    reply_markup = InlineKeyboardMarkup(term.create_keyboard())
    update.message.reply_text(term.current_dir, reply_markup=reply_markup)
项目:recyclebot    作者:opendatahackathon    | 项目源码 | 文件源码
def where_cmd(bot, update, **args):
    msgText = 'where!! '
    query = update.callback_query
    where_args = args.get("args")
    buttonsListFlg = False
    address = ""
    if len(where_args) > 0:
        print(where_args[0])
        address = find_address(where_args[0])
        if address != "":
            msgText = msgText + ' ' + address;
        else:
            buttonsListFlg = True
    else:
        buttonsListFlg = True
    if buttonsListFlg:
        reply_markup = InlineKeyboardMarkup(districts_button_list)
        bot.sendMessage(chat_id=update.message.chat_id, reply_markup=reply_markup,
                        text='???????? ?????????? ????? ??????:')
    else:
        bot.sendMessage(chat_id=update.message.chat.id, text=msgText)
项目:bicingbot    作者:marivipelaez    | 项目源码 | 文件源码
def remove_group_command(chat_id, text):
    """
    Sends a keyboard to the user with the name of all her groups to choose the one to remove

    :param chat_id: Telegram chat id
    :param text: remove group command
    """
    db_connection = DatabaseConnection()
    logger.info('COMMAND {}: chat_id={}'.format(text, chat_id))
    groups = grouper(db_connection.get_groups_names(chat_id))
    buttons_lines = []
    for groups_line in groups:
        buttons_lines.append(
            [InlineKeyboardButton(group_name, callback_data='{}_{}'.format(REMOVE_GROUP_CALLBACK, group_name))
             for group_name in groups_line if group_name])
    buttons_lines.append([InlineKeyboardButton(tr('removegroup_cancel', chat_id),
                                               callback_data='{}_unused'.format(REMOVE_CANCEL_CALLBACK))])
    keyboard = InlineKeyboardMarkup(buttons_lines)
    get_bot().send_message(chat_id=chat_id, text=tr('removegroup_name', chat_id), reply_markup=keyboard)
    db_connection.close()
项目:tgbot    作者:PaulSonOfLars    | 项目源码 | 文件源码
def warn(user_id, chat, reason, bot, message):
    if is_user_admin(chat, user_id):
        message.reply_text("Damn admins, can't even be warned!")
        return

    user_warned = sql.warn_user(user_id, chat.id, reason)
    if user_warned.num_warns >= 3:
        res = chat.kick_member(user_id)
        if res:
            bot.send_sticker(chat.id, 'CAADAgADOwADPPEcAXkko5EB3YGYAg')  # banhammer marie sticker
            message.reply_text("3 warnings, this user has been banned!")
            sql.reset_warns(user_id, chat.id)
        else:
            message.reply_text("An error occurred, I couldn't ban this person!")
    else:
        keyboard = InlineKeyboardMarkup([[InlineKeyboardButton("Remove warn", callback_data="rm_warn({})".format(user_id))]])
        if reason:
            message.reply_text("{}/3 warnings... watch out! Latest one was because:\n{}".format(user_warned.num_warns, reason), reply_markup=keyboard)
        else:
            message.reply_text("{}/3 warnings... watch out!".format(user_warned.num_warns), reply_markup=keyboard)
项目:TelegramBots    作者:d-qoi    | 项目源码 | 文件源码
def chooseLanguage(bot, update, chat_data, args):
    TRACKING.total.post()
    if not checkValidCommand(update.message.text, bot.username):
        return
    logger.info("Choose language received")
    if args:
        for key in LANGUAGES:
            for lang in LANGUAGES[key]:
                if lang[0] == args[0]:
                    reply_text = 'Set language to: %s' % args[0]
                    update.message.reply_text(reply_text)
                    chat_data['lang'] = args[0]

                    return

    chat_data['choosing'] = True
    logger.debug("Starting choose language inline mess")
    reply_text = "Please choose your language, or the closest.\n"
    if not 'lang' in chat_data:
        reply_text += "Current language selected: en-US"
        chat_data['lang'] = 'en-US'

    chat_data['langlist'] = sorted(LANGUAGES.keys())
    keyboard = InlineKeyboardMarkup(updateKeyboard(chat_data))
    update.message.reply_text(reply_text, reply_markup=keyboard, quote=False)
项目:TelegramBots    作者:d-qoi    | 项目源码 | 文件源码
def chooseLanguage(bot, update, chat_data, args):
    TRACKING.total.post()
    if not checkValidCommand(update.message.text, bot.username):
        return
    logger.info("Choose language received")
    if args:
        for key in LANGUAGES:
            for lang in LANGUAGES[key]:
                if lang[0] == args[0]:
                    reply_text = 'Set language to: %s' % args[0]
                    update.message.reply_text(reply_text)
                    chat_data['lang'] = args[0]

                    return

    chat_data['choosing'] = True
    logger.debug("Starting choose language inline mess")
    reply_text = "Please choose your language, or the closest.\n"
    if not 'lang' in chat_data:
        reply_text += "Current language selected: en-US"
        chat_data['lang'] = 'en-US'

    chat_data['langlist'] = sorted(LANGUAGES.keys())
    keyboard = InlineKeyboardMarkup(updateKeyboard(chat_data))
    update.message.reply_text(reply_text, reply_markup=keyboard, quote=False)
项目:secreth_telegrambot    作者:d0tcc    | 项目源码 | 文件源码
def vote(bot, game):
    log.info('vote called')
    #When voting starts we start the counter to see later with the vote/calltovote command we can see who voted.
    game.dateinitvote = datetime.datetime.now()
    strcid = str(game.cid)
    btns = [[InlineKeyboardButton("Ja", callback_data=strcid + "_Ja"),
             InlineKeyboardButton("Nein", callback_data=strcid + "_Nein")]]
    voteMarkup = InlineKeyboardMarkup(btns)
    for uid in game.playerlist:
        if not game.playerlist[uid].is_dead:
            if game.playerlist[uid] is not game.board.state.nominated_president:
                # the nominated president already got the board before nominating a chancellor
                bot.send_message(uid, game.board.print_board())
            bot.send_message(uid,
                             "Do you want to elect President %s and Chancellor %s?" % (
                                 game.board.state.nominated_president.name, game.board.state.nominated_chancellor.name),
                             reply_markup=voteMarkup)
项目:secreth_telegrambot    作者:d0tcc    | 项目源码 | 文件源码
def draw_policies(bot, game):
    log.info('draw_policies called')
    strcid = str(game.cid)
    game.board.state.veto_refused = False
    # shuffle discard pile with rest if rest < 3
    shuffle_policy_pile(bot, game)
    btns = []
    for i in range(3):
        game.board.state.drawn_policies.append(game.board.policies.pop(0))
    for policy in game.board.state.drawn_policies:
        btns.append([InlineKeyboardButton(policy, callback_data=strcid + "_" + policy)])

    choosePolicyMarkup = InlineKeyboardMarkup(btns)
    bot.send_message(game.board.state.president.uid,
                     "You drew the following 3 policies. Which one do you want to discard?",
                     reply_markup=choosePolicyMarkup)
项目:telegram-autoposter    作者:vaniakosmos    | 项目源码 | 文件源码
def command_choose(self, bot: Bot, update: Update):
        channels = []
        for label, channel in self.channels.items():
            button = InlineKeyboardButton(text=label, callback_data=label)
            channels.append(button)

        keyboard = [channels]
        reply_markup = InlineKeyboardMarkup(keyboard)

        bot.send_message(chat_id=update.message.chat_id,
                         text='Choose channel.',
                         reply_markup=reply_markup)
项目:py_mbot    作者:evgfilim1    | 项目源码 | 文件源码
def settings(bot, update):
    keyboard = []
    for i, (lang, flag) in enumerate(config.flags.items()):
        text = '{0} {1}'.format(flag, lang)
        callback_data = 'settings:lang:{0}'.format(lang)
        if i % 2 == 0:
            keyboard.append([InlineKeyboardButton(text, callback_data=callback_data)])
        else:
            keyboard[-1].append(InlineKeyboardButton(text, callback_data=callback_data))
    update.message.reply_text('Choose your language',
                              reply_markup=InlineKeyboardMarkup(keyboard))
项目:memes-reposter    作者:vaniakosmos    | 项目源码 | 文件源码
def command_choose(self, bot: Bot, update: Update):
        channels = []
        for label, channel in self.channels.items():
            button = InlineKeyboardButton(text=label, callback_data=label)
            channels.append(button)

        keyboard = [channels]
        reply_markup = InlineKeyboardMarkup(keyboard)

        bot.send_message(chat_id=update.message.chat_id,
                         text='Choose channel.',
                         reply_markup=reply_markup)
项目:memes-reposter    作者:vaniakosmos    | 项目源码 | 文件源码
def build_keyboard_markup(self, post: Post, pass_original=True):
        keyboard = []
        if pass_original:
            keyboard.append(InlineKeyboardButton('original', url=post.url))
        keyboard.append(InlineKeyboardButton('comments', url=post.comments))

        return InlineKeyboardMarkup([
            keyboard
        ])
项目:pybot    作者:raelga    | 项目源码 | 文件源码
def get_menu(data, columns=2):
    "Function to convert an array to Telegram InlineKeyboard."

    menu = []
    menu.append([])

    i = 0
    for option in enumerate(data):

        if not option[1]:
            # Insert blank elements to emulate a separator
            blank = (option[0] + 1) % columns
            while blank:
                menu.append([])
                blank -= 1

        elif re.search(r'^http:|https:.*', option[1][1]):

            menu[i].append(
                telegram.InlineKeyboardButton(option[1][0],
                                              url=option[1][1]))
        else:
            menu[i].append(
                telegram.InlineKeyboardButton(option[1][0],
                                              callback_data=option[1][1]))

        if not (option[0] + 1) % columns:
            menu.append([])
            i += 1

    return telegram.InlineKeyboardMarkup(menu)
项目:argosd    作者:danielkoster    | 项目源码 | 文件源码
def create_button_markup(text, callback_data):
        """Creates markup for a single inline keyboard button in a message."""
        keyboard = [[InlineKeyboardButton(text, callback_data=callback_data)]]
        return InlineKeyboardMarkup(keyboard)
项目:VocaBot    作者:bomjacob    | 项目源码 | 文件源码
def song_keyboard(data, inline=False):
    if not data:
        return
    keyboard = [[]]
    keyboard[-1].append(InlineKeyboardButton(text=Emoji.SCROLL + _('Lyrics'),
                                             callback_data='ly|{}'.format(data['id'])))

    # TODO: Add "Artist Info" button to inline

    # If it's from an entry search we get pVs instead of pvServices
    if 'pVs' in data:
        data['pvServices'] = ', '.join([x['service'] for x in data['pVs']])

    if not data['pvServices'] == 'Nothing':
        keyboard.append([])
        for service in PV_SERVICES:
            if service in data['pvServices']:
                callback_data = 'pv|{}|{}'.format(data['id'], service)
                keyboard[-1].append(InlineKeyboardButton(text=Emoji.MOVIE_CAMERA + service,
                                                         callback_data=callback_data))

    keyboard.append([
        InlineKeyboardButton(text=_('Share song'), switch_inline_query='!s#{}'.format(data['id'])),
        InlineKeyboardButton(text=_('View on VocaDB.net'), url=vocadb_url(data, song=True))
    ])

    return InlineKeyboardMarkup(keyboard)


# noinspection PyTypeChecker
项目:VocaBot    作者:bomjacob    | 项目源码 | 文件源码
def artist_keyboard(data, inline=False):
    if not data:
        return
    keyboard = []
    if not inline:
        keyboard.append([
            InlineKeyboardButton(text=Emoji.TOP_WITH_UPWARDS_ARROW_ABOVE + _('Popular songs'),
                                 callback_data='arlist|ps|{}'.format(data['id'])),
            InlineKeyboardButton(text=Emoji.CLOCK_FACE_THREE_OCLOCK + _('Latest songs'),
                                 callback_data='arlist|ls|{}'.format(data['id']))
        ])
        keyboard.append([
            InlineKeyboardButton(text=Emoji.TOP_WITH_UPWARDS_ARROW_ABOVE + _('Popular albums'),
                                 callback_data='arlist|pa|{}'.format(data['id'])),
            InlineKeyboardButton(text=Emoji.CLOCK_FACE_THREE_OCLOCK + _('Latest albums'),
                                 callback_data='arlist|la|{}'.format(data['id']))
        ])

    keyboard.append([
        InlineKeyboardButton(text=_('Share artist'), switch_inline_query='!ar#{}'.format(data['id'])),
        InlineKeyboardButton(text=_('View on VocaDB.net'), url=vocadb_url(data, artist=True))
    ])

    return InlineKeyboardMarkup(keyboard)


# noinspection PyTypeChecker
项目:VocaBot    作者:bomjacob    | 项目源码 | 文件源码
def album_keyboard(data, inline=False):
    if not data:
        return
    keyboard = [[]]
    keyboard[-1].append(InlineKeyboardButton(text=Emoji.MUSICAL_SCORE + _('Tracks'),
                                             callback_data='allist|{}'.format(data['id'])))

    keyboard.append([
        InlineKeyboardButton(text=_('Share Album'), switch_inline_query='!al#{}'.format(data['id'])),
        InlineKeyboardButton(text=_('View on VocaDB.net'), url=vocadb_url(data, album=True))
    ])

    return InlineKeyboardMarkup(keyboard)
项目:VocaBot    作者:bomjacob    | 项目源码 | 文件源码
def lyrics(bot, update, groups, lang):
    data = voca_db.song(groups[0], lang=lang, fields='MainPicture, Names, Lyrics, Artists, PVs')

    reply_keyboard = InlineKeyboardMarkup([
        [InlineKeyboardButton(get_lyric_lang(lyric['translationType'], lyric['cultureCode']),
                              callback_data='ly|{}|{}'.format(data['id'],
                                                              lyric['id'])) for lyric in data['lyrics']]])

    inline = bool(update.callback_query.inline_message_id)

    if data['lyrics']:
        if groups[1] == '':
            text = _('What language would you like the lyrics for <b>{name} by {artist}</b> in?').format(
                name=data['name'],
                artist=data['artistString'])
            edit_message_text(bot, update, send_if_possible=True,
                              text=text,
                              reply_markup=reply_keyboard,
                              parse_mode=ParseMode.HTML)
            update.callback_query.answer()
        else:
            for lyric in data['lyrics']:
                if lyric['id'] == int(groups[1]):
                    text = ''
                    if inline:
                        text = content_parser(data, info=True, inline=True, bot_name=bot.username)
                    text += '\n\n' + Emoji.SCROLL
                    text += _('<b>{lang} lyrics for {song} by {artist}</b>\n'
                              '{lyrics}').format(song=data['name'],
                                                 artist=data['artistString'],
                                                 lang=get_lyric_lang(lyric['translationType'], lyric['cultureCode'],
                                                                     long=True),
                                                 lyrics=lyric['value'])
                    edit_message_text(bot, update,
                                      text=text,
                                      reply_markup=song_keyboard(data, inline=True) if inline else reply_keyboard,
                                      parse_mode=ParseMode.HTML)
                    update.callback_query.answer()
    else:
        update.callback_query.answer(_('No lyrics found.'))
项目:VocaBot    作者:bomjacob    | 项目源码 | 文件源码
def send_changer(bot, update, setting):
    user = get_user(bot, update)
    if setting in user:
        global settings
        keyboard = [InlineKeyboardButton(button_text, callback_data='set|{}|{}'.format(setting, button_id)) for
                    button_id, button_text in settings[setting]['trans'].items()]
        keyboard = InlineKeyboardMarkup([keyboard])
        bot.edit_message_text(chat_id=update.callback_query.message.chat.id,
                              message_id=update.callback_query.message.message_id,
                              text=settings[setting]['msg'],
                              reply_markup=keyboard,
                              parse_mode=ParseMode.HTML)
    else:
        update.callback_query.answer(_('Unknown setting, try again.'))
项目:ImgurPlus    作者:DcSoK    | 项目源码 | 文件源码
def defaul_res():
    button0 = InlineKeyboardButton(text="48x48", callback_data="48x48")
    button1 = InlineKeyboardButton(text="72x72", callback_data="72x72")
    button2 = InlineKeyboardButton(text="96x96", callback_data="96x96")
    button3 = InlineKeyboardButton(text="144x144", callback_data="144x144")
    button4 = InlineKeyboardButton(text="Custom resolution", callback_data="custom")
    button5 = InlineKeyboardButton(text="Default resolution", callback_data="default")
    buttons_list = [[button0, button1, button2, button3], [button5]]
    keyboard = InlineKeyboardMarkup(buttons_list)
    return keyboard
项目:ImgurPlus    作者:DcSoK    | 项目源码 | 文件源码
def github_link_kb():
    button0 = InlineKeyboardButton(text="Source code", url="https://github.com/DcSoK/ImgurPlus")
    buttons_list = [[button0]]
    keyboard = InlineKeyboardMarkup(buttons_list)
    return keyboard
项目:Automate-it    作者:PacktPublishing    | 项目源码 | 文件源码
def start(bot, update):
    keyboard = [
                [InlineKeyboardButton("Happy", callback_data='1'),
                 InlineKeyboardButton("Whatever", callback_data='2')],
                [InlineKeyboardButton("Sad", callback_data='3')]]

    reply_markup = InlineKeyboardMarkup(keyboard)

    update.message.reply_text('Hey there! How do you feel today?', reply_markup=reply_markup)
项目:teamSpeakTelegram    作者:jossalgon    | 项目源码 | 文件源码
def generate_invitation(bot, update):
    message = update.message
    token = utils.generate_invitation()
    link = 'https://telegram.me/%s?start=%s' % (bot.username, token)
    share_link = 'https://telegram.me/share/url?url={0}&text=Click%20the%20link%20to%20join%20the%20teamspeak%20bot'.format(link)
    keyboard = [[InlineKeyboardButton(_('Join'), url=link)],
                [InlineKeyboardButton(_('Share link'), url=share_link)]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    bot.sendMessage(message.chat_id, '?? ' + _('Welcome to TeamSpeak bot') + ' ??\n\n' +
                    _('This is an invitation to use the TeamSpeak bot'),
                    reply_markup=reply_markup)
项目:teamSpeakTelegram    作者:jossalgon    | 项目源码 | 文件源码
def paginate_items(bot, update, chat_data, items, principal_property, backend_property, text, callback, additional_row=None):
    message = update.effective_message
    chat_id = message.chat_id
    markup = []
    first_message = bool(update.message)

    page = chat_data[message.message_id]['pages'] if not first_message else 1

    start = 10 * (page - 1) if page > 1 else 0
    end = start + 10 if start + 10 < len(items) else len(items)
    for i in range(start, end, 2):
        item1 = items[i]
        row = [InlineKeyboardButton(item1[principal_property],
                                    callback_data='%s_DETAIL_%s' % (callback, str(item1[backend_property])))]
        if i + 1 < len(items):
            item2 = items[i + 1]
            row.append(InlineKeyboardButton(item2[principal_property],
                                            callback_data='%s_DETAIL_%s' % (callback, str(item2[backend_property]))))
        markup.append(row)

    markup = markup_append_pagination(bot, update, items, markup, page, callback)

    if additional_row is not None:
        markup.append(additional_row)

    reply_markup = InlineKeyboardMarkup(markup)

    if len(items) == 0:
        text = _('No results')
    if not first_message:
        bot.edit_message_text(text, chat_id=chat_id, message_id=message.message_id, reply_markup=reply_markup,
                              parse_mode='Markdown')
    else:
        msg = bot.send_message(chat_id, text, disable_notification=True, reply_markup=reply_markup,
                               parse_mode='Markdown')
        chat_data[msg.message_id] = dict()
        chat_data[msg.message_id]['pages'] = page
项目:telegram_robot    作者:uts-magic-lab    | 项目源码 | 文件源码
def start(bot, update):
    keyboard = [[InlineKeyboardButton("Option 1", callback_data='1'),
                 InlineKeyboardButton("Option 2", callback_data='2')],

                [InlineKeyboardButton("Option 3", callback_data='3')]]

    reply_markup = InlineKeyboardMarkup(keyboard)

    update.message.reply_text('Please choose:', reply_markup=reply_markup)
项目:JackOfAllGroups-telegram-bot    作者:Kyraminol    | 项目源码 | 文件源码
def cmd_settings(bot, update):
    message = update.message
    msg_parse(bot, update)
    text = ""
    keyboard = []
    if message.chat.type == "private":
        text = "Cosa vuoi impostare?"
        keyboard += [[InlineKeyboardButton("Impostazioni globali", callback_data="settings.set.0"),
                      InlineKeyboardButton("Impostazioni per gruppo", callback_data="settings.groups")]]
        keyboard += [[InlineKeyboardButton("Aiuto", callback_data="help.main")]]
        keyboard += [[InlineKeyboardButton("Lascia un suggerimento", callback_data="feedback.leave"),
                      InlineKeyboardButton("Informazioni sviluppatore", callback_data="dev.info")]]
        reply_markup = InlineKeyboardMarkup(keyboard)
        bot.send_message(message.chat.id, markdown_to_html(text), reply_to_message_id=message.message_id, reply_markup=reply_markup, parse_mode=ParseMode.HTML)
项目:animebot    作者:EV3REST    | 项目源码 | 文件源码
def inline(bot, update): #Inline Handler & Parser
    query = update.inline_query.query
    if query is None:
        query = 'rating:s'
        client = Pybooru('Yandere')
        posts = client.posts_list(tags=query, limit=50)
        lposts = len(posts)
        inlinequery = list()
        reply_markup = InlineKeyboardMarkup([InlineKeyboardButton("More", callback_data='More')])
        for post in posts:
            inlinequery.append(InlineQueryResultPhoto(
                    type='photo',
                    id=uuid4(),
                    photo_url=post['file_url'],
                    photo_width=post['preview_width']*6,
                    photo_height=post['preview_height']*6,
                    #reply_markup=reply_markup,
                    thumb_url=post['preview_url']),)
        bot.answerInlineQuery(update.inline_query.id, results=inlinequery, switch_pm_text="Help", switch_pm_parameter="ihelp")
        inlinequery.clear()
    else:
        client = Pybooru('Yandere')
        posts = client.posts_list(tags=query, limit=50)
        lposts = len(posts)
        inlinequery = list()
        reply_markup = InlineKeyboardMarkup([InlineKeyboardButton("More", callback_data='More')])
        for post in posts:
            inlinequery.append(InlineQueryResultPhoto(
                    type='photo',
                    id=uuid4(),
                    photo_url=post['file_url'],
                    photo_width=post['preview_width']*6,
                    photo_height=post['preview_height']*6,
                    #reply_markup=reply_markup,
                    thumb_url=post['preview_url']),)
        bot.answerInlineQuery(update.inline_query.id, results=inlinequery, switch_pm_text="Help", switch_pm_parameter="ihelp")
        inlinequery.clear()
项目:animebot    作者:EV3REST    | 项目源码 | 文件源码
def idd(bot, update, tags=None, chat_id=None):
    randomint = randint(1000, 10000000)
    try:
        bot.sendChatAction(chat_id, "upload_document")
        tags = update.message.text.split(' ', 1)[1]
        chat_id = update.message.chat_id
        try:
            client = Pybooru('Yandere')
            posts = client.posts_list(tags="id:"+str(tags), limit=1)
            for post in posts:
                urllib.request.urlretrieve(post['file_url'], "tmp/anime_bot_" + str(randomint) + ".jpg")
                tmp_data = "Uploader: " + post['author']  + "\nID: " + str(post['id'])
                globalarray[chat_id] = dict(data=tmp_data)
            photo = open('tmp/anime_bot_' + str(randomint) + ".jpg", 'rb')
            reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton("More", callback_data='More')]])
            bot.sendDocument(chat_id, photo, reply_markup=reply_markup)
            os.remove('tmp/anime_bot_' + str(randomint) + ".jpg")
        except Exception as e:
            print(e)
    except:
        bot.sendChatAction(chat_id, "upload_document")
        client = Pybooru('Yandere')
        try:
            posts = client.posts_list(tags="id:"+str(tags), limit=1)
            for post in posts:
                urllib.request.urlretrieve(post['file_url'], "tmp/anime_bot_" + str(randomint) + ".jpg")
                tmp_data = "Uploader: " + post['author']  + "\nID: " + str(post['id'])
                globalarray[chat_id] = dict(data=tmp_data)
            photo = open('tmp/anime_bot_' + str(randomint) + ".jpg", 'rb')
            reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton("More", callback_data='More')]])
            bot.sendDocument(chat_id, photo, reply_markup=reply_markup)
            os.remove('tmp/anime_bot_' + str(randomint) + ".jpg")
        except Exception as e:
            print(e)
项目:python-telegram-dialog-bot    作者:Saluev    | 项目源码 | 文件源码
def convert(self):
        print(self.keyboard)
        keyboard = [
            [
                (button if isinstance(button, Button) else Button(button)).convert()
                for button in row
            ]
            for row in self.keyboard
        ]
        return InlineKeyboardMarkup(keyboard)
项目:AlarmBot    作者:guysoft    | 项目源码 | 文件源码
def list_alarms(self, bot, update):
        keyboard = []

        for i, job in enumerate(self.crontab.job_list()):
            description = short_description(job).split(",")

            icon = emojize(":bell:", use_aliases=True)
            alarm_button = InlineKeyboardButton(icon, callback_data=build_callback(
                {"command": "disable", "alarm": get_job_id(job)}))

            if not job.enabled:
                icon = emojize(":no_bell:", use_aliases=True)
                alarm_button = InlineKeyboardButton(icon, callback_data=build_callback(
                    {"command": "enable","alarm": get_job_id(job)}))

            icon = emojize(":x:", use_aliases=True)
            delete_button = InlineKeyboardButton(icon, callback_data=build_callback(
                    {"command": "remove","alarm": get_job_id(job)}))

            close = build_callback({"command": "close"})
            if len(job) > 1:
                keyboard.append([alarm_button, delete_button,
                                 InlineKeyboardButton(description[0], callback_data=close),
                                 InlineKeyboardButton(", ".join(description[1:]), callback_data=close)])
            else:
                keyboard.append([alarm_button, delete_button,
                                 InlineKeyboardButton(description[0], callback_data=close)])

        reply_markup = InlineKeyboardMarkup(keyboard)
        update.message.reply_text('Alarm list:', reply_markup=reply_markup)
        return
项目:walkdir-telegram-bot    作者:deepserket    | 项目源码 | 文件源码
def refresh_stdout_on_telegram():
    old_lines = ''

    # TODO add command buttons
    reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('stop terminal', 
                                                          callback_data=' s')]])
    while term.is_started_real_terminal:
        sleep(0.1)
        if old_lines == term.text_stdout: # no changes...
            continue

        old_lines = term.text_stdout

        bot_.edit_message_text(chat_id=last_chat_id,
                               message_id=last_message_id,
                               text=old_lines+'_',
                               reply_markup=reply_markup)
项目:TBot8-1    作者:Danzilla-cool    | 项目源码 | 文件源码
def start(bot, update):
    keyboard = [[InlineKeyboardButton("Option 1", callback_data='1'),
                 InlineKeyboardButton("Option 2", callback_data='2')],

                [InlineKeyboardButton("Option 3", callback_data='3')]]

    reply_markup = InlineKeyboardMarkup(keyboard)


    bot.sendMessage(update.message.chat_id, text="Please choose:", reply_markup=reply_markup)
项目:recyclebot    作者:opendatahackathon    | 项目源码 | 文件源码
def types_cmd(bot, update, **args):
    reply_markup = InlineKeyboardMarkup(types_button_list)
    text = '????? ???? ?????? ????????? ??????? ?????????.\n' \
           '?? ?????? ??????? ????? ?? ??? ??? ????????? ?????????????? ??????????:'
    bot.sendMessage(chat_id=update.message.chat_id, reply_markup=reply_markup, text=text)
    # bot.sendMessage(chat_id=update.message.chat.id, text=u'?????????? ?????? ??????? ????????? ? ???????????: \n' + find_types())
项目:telegram-yt_mp3-bot    作者:Javinator9889    | 项目源码 | 文件源码
def key_a(bot, update):
    keyboard = [[InlineKeyboardButton("Continuar la descarga", callback_data='Ax'),InlineKeyboardButton("Cancelar", callback_data='Ay')]]

    reply_markup2 = InlineKeyboardMarkup(keyboard)

    update.message.reply_text('¿Continuar con la descarga?',
      parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=reply_markup2)
项目:telegram-yt_mp3-bot    作者:Javinator9889    | 项目源码 | 文件源码
def key_aen(bot,update):
    keyboard = [[InlineKeyboardButton("Continue download", callback_data='Ax'),InlineKeyboardButton("Cancell", callback_data='Ay')]]

    reply_markup2 = InlineKeyboardMarkup(keyboard)

    update.message.reply_text('Do you want to continue with the download?',
      parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=reply_markup2)
项目:telegram-yt_mp3-bot    作者:Javinator9889    | 项目源码 | 文件源码
def key_l(bot, update):
    keyboard = [[InlineKeyboardButton("Español ????", callback_data='es'),InlineKeyboardButton("English ????", callback_data='en')]]

    reply_markup2 = InlineKeyboardMarkup(keyboard)

    update.message.reply_text('Elige tu idioma / choose your language:',
      parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=reply_markup2)
项目:telegram-yt_mp3-bot    作者:Javinator9889    | 项目源码 | 文件源码
def key_l(bot, update,chat_id):
    keyboard = [[InlineKeyboardButton("Español ????", callback_data='es'),InlineKeyboardButton("English ????", callback_data='en')]]

    reply_markup2 = InlineKeyboardMarkup(keyboard)

    bot.sendMessage(text='Elige tu idioma / choose your language:',
      parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=reply_markup2, chat_id=chat_id)
项目:telegram-yt_mp3-bot    作者:Javinator9889    | 项目源码 | 文件源码
def key_l2(bot, update,chat_id):
    keyboard = [[InlineKeyboardButton("Español ????", callback_data='castell'),InlineKeyboardButton("English ????", callback_data='glish')]]

    reply_markup2 = InlineKeyboardMarkup(keyboard)

    bot.sendMessage(text='Elige tu idioma / choose your language:',
      parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=reply_markup2, chat_id=chat_id)
项目:telegram-yt_mp3-bot    作者:Javinator9889    | 项目源码 | 文件源码
def key_osen(bot, update,chat_id):
    keyboard = [[InlineKeyboardButton("Android - W. Phone ??", callback_data='droiden'),InlineKeyboardButton("iOS ??", callback_data='iosen')]]

    reply_markup2 = InlineKeyboardMarkup(keyboard)

    bot.sendMessage(text='What is your operative system? _(only smartphones; this option is irrelevant for PC users)_',
      parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=reply_markup2,chat_id=chat_id)