我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用telegram.InlineKeyboardButton()。
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 )
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])
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)
def parents_menu(bot, update): categories = apifetch.fetch_json(baseurl_g, "category/parents") # TODO: implement fetch from database instead of url logger.debug("update categories requested!") option_btn = 'name' callback = 'id' parent_names, button_list = gen_category(categories, option_btn, callback, "paid:") if len(parent_names) < 6: reply_markup = build_menu(button_list, n_cols=3) else: show_more = InlineKeyboardButton("?????...", callback_data="more_categories") button_rest = button_list[6:] del button_list[6:] reply_markup = build_menu(button_list, n_cols=3, footer_buttons=[show_more]) logger.debug("reply keyboard for category was returned") return reply_markup
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)
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)
def markup_append_pagination(bot, update, items, markup, page, callback, items_per_page=10): pag_max = math.ceil(len(items) / items_per_page) pag_button = InlineKeyboardButton(_('Page') + ' %s/%s' % (str(page), str(pag_max)), callback_data='%s_PG_NEXT' % callback) if len(items) >= items_per_page: if page == 1: sig_button = InlineKeyboardButton(_('Page') + ' %s/%s ?' % (str(page), str(pag_max)), callback_data='%s_PG_NEXT' % callback) markup.append([sig_button]) elif 1 < page < pag_max: ant_button = InlineKeyboardButton('? ' + _('Prev'), callback_data='%s_PG_PREV' % callback) sig_button = InlineKeyboardButton('? ' + _('Next'), callback_data='%s_PG_NEXT' % callback) markup.append([ant_button, pag_button, sig_button]) elif page == pag_max: ant_button = InlineKeyboardButton(_('Page') + ' %s/%s ?' % (str(page), str(pag_max)), callback_data='%s_PG_PREV' % callback) markup.append([ant_button]) return markup
def send_ts_group_details(bot, update, chat_data, group_id=None): message = update.effective_message chat_id = message.chat_id if group_id is not None: chat_data[message.message_id]['group_id'] = group_id else: group_id = chat_data[message.message_id]['group_id'] ts_group = get_ts_group(group_id) if int(ts_group['savedb']) == 0: bot.answer_callback_query(update.callback_query.id, _('Access to default group is forbidden')) return False text = '?? *' + ts_group['name'] + ' ' + _('group:') + '*' markup = [[InlineKeyboardButton('?? ' + _('List users'), callback_data='GROUP_DETAIL_USERS_%s' % group_id)], [InlineKeyboardButton('? ' + _('Add user'), callback_data='GROUP_%s_ADD' % group_id), InlineKeyboardButton('? ' + _('Delete user'), callback_data='GROUP_%s_DEL' % group_id)], [InlineKeyboardButton('?? ' + _('Back'), callback_data='GROUP_DETAIL_BACK')]] reply_markup = InlineKeyboardMarkup(markup) bot.edit_message_text(text, chat_id=chat_id, message_id=message.message_id, reply_markup=reply_markup, parse_mode='Markdown')
def send_ts_users_in_group(bot, update, chat_data, group_id=None): message = update.effective_message text = '?? ' + _('*Group users:*') + '\n\n' \ + _('Here is a list of all users in this group, pressing any of them will take you to his detail.') if group_id is not None: chat_data[message.message_id]['group_id'] = group_id else: group_id = chat_data[message.message_id]['group_id'] users = get_ts_users_in_group(group_id) users = sorted(users, key=lambda user: user['client_lastconnected'], reverse=True) back_button_row = [InlineKeyboardButton('?? ' + _('Back'), callback_data='GROUP_DETAIL_USERS_%s_BACK' % group_id)] paginate_items(bot, update, chat_data, items=users, principal_property='client_nickname', backend_property='client_database_id', text=text, callback='GROUP_DETAIL_USERS', additional_row=back_button_row)
def send_add_user_to_group(bot, update, chat_data, group_id=None): message = update.effective_message text = '?? ' + _('*Select an user to add to the group:*') if group_id is not None: chat_data[message.message_id]['group_id'] = group_id else: group_id = chat_data[message.message_id]['group_id'] users = get_users_tsdb() users = sorted(users, key=lambda user: user['client_lastconnected'], reverse=True) back_button_row = [InlineKeyboardButton('?? ' + _('Back'), callback_data='GROUP_%s_ADD_BACK' % group_id)] paginate_items(bot, update, chat_data, items=users, principal_property='client_nickname', backend_property='cldbid', text=text, callback='GROUP_%s_ADD' % group_id, additional_row=back_button_row)
def send_delete_user_from_group(bot, update, chat_data, group_id=None): message = update.effective_message text = '?? ' + _('*Select an user to delete from group:*') if group_id is not None: chat_data[message.message_id]['group_id'] = group_id else: group_id = chat_data[message.message_id]['group_id'] users = get_ts_users_in_group(group_id) users = sorted(users, key=lambda user: user['client_lastconnected'], reverse=True) back_button_row = [InlineKeyboardButton('?? ' + _('Back'), callback_data='GROUP_%s_DEL_BACK' % group_id)] paginate_items(bot, update, chat_data, items=users, principal_property='client_nickname', backend_property='client_database_id', text=text, callback='GROUP_%s_DEL' % group_id, additional_row=back_button_row)
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)
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")
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")
def ls(self): """ Generate a list of InlineKeyboardButton of files and dir in current_dir """ p = Popen('ls', cwd=self.current_dir, shell=True, stdout=PIPE, stderr=PIPE).communicate() files = str(p[0], 'utf-8').strip().split('\n') # Also contains directories files = [f for f in files if check_file(f)] # removing bad files... kb = [] if self.current_dir != '/': kb.append([InlineKeyboardButton("..", callback_data='..d')]) for f in files: # First the directories... path = os.path.join(self.current_dir, f) if os.path.isdir(path): kb.append([InlineKeyboardButton("dir: {}".format(f), callback_data="{}d".format(f))]) for f in files: # ...Then the files path = os.path.join(self.current_dir, f) if os.path.isfile(path): kb.append([InlineKeyboardButton("file: {}".format(f), callback_data="{}f".format(f))]) return kb
def create_keyboard(self, window=0): self.files = self.ls() self.files.insert(0, [InlineKeyboardButton('OPEN TERMINAL HERE', callback_data=' t')]) if len(self.files) <= 52: return self.files start = 0 if window == 0 else window * 50 stop = start + 50 head = None if start == 0 else (InlineKeyboardButton("<<<PREVIOUS<<<", callback_data="{}w".format(window-1))) foot = None if stop > len(self.files) else (InlineKeyboardButton(">>>NEXT>>>", callback_data="{}w".format(window+1))) kb = build_menu(self.files[start:stop], header=head, footer=foot) return kb
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()
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)
def updateKeyboard(chat_data): keyboard = list() for i in range(0,len(chat_data['langlist'][:12]),2): if i >= (len(chat_data['langlist']) -1): keyboard.append([InlineKeyboardButton(chat_data['langlist'][i], callback_data=str(i))]) chat_data[str(i)] = chat_data['langlist'][i] else: keyboard.append([InlineKeyboardButton(chat_data['langlist'][i], callback_data=str(i)), InlineKeyboardButton(chat_data['langlist'][i+1], callback_data=str(i+1))]) chat_data[str(i)] = chat_data['langlist'][i] chat_data[str(i+1)] = chat_data['langlist'][i+1] chat_data['working'] = chat_data['langlist'][:12] chat_data['langlist'] = chat_data['langlist'][12:] keyboard.append([InlineKeyboardButton('More', callback_data='more'), InlineKeyboardButton('Cancel', callback_data='cancel')]) return keyboard
def updateKeyboardDial(chat_data): keyboard = list() for i in range(0,len(chat_data['langlist']),2): if i >= len(chat_data['langlist'])-1: keyboard.append([InlineKeyboardButton(chat_data['langlist'][i][1], callback_data=str(i))]) chat_data[str(i)] = chat_data['langlist'][i][0] else: keyboard.append([InlineKeyboardButton(chat_data['langlist'][i][1], callback_data=str(i)), InlineKeyboardButton(chat_data['langlist'][i+1][1], callback_data=str(i+1))]) chat_data[str(i)] = chat_data['langlist'][i][0] chat_data[str(i+1)] = chat_data['langlist'][i+1][0] chat_data['langlist'] = [] chat_data['working'] = [] keyboard.append([InlineKeyboardButton('Return', callback_data='more'), InlineKeyboardButton('Cancel', callback_data='cancel')]) return keyboard
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)
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)
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)
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))
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 ])
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)
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)
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
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
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)
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.'))
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.'))
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
def github_link_kb(): button0 = InlineKeyboardButton(text="Source code", url="https://github.com/DcSoK/ImgurPlus") buttons_list = [[button0]] keyboard = InlineKeyboardMarkup(buttons_list) return keyboard
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)
def gen_category(categories, buttonfield, callbackfield, callbackheader, url=""): cat_names = [] for item in categories: print(item) cat_names.append(item[buttonfield]) logger.info("generated a list from the name of categories; {}" .format(cat_names)) button_list = [InlineKeyboardButton(s, url=url.format(str(categories[cat_names.index(s)][callbackfield])), callback_data=callbackheader + str(categories[cat_names.index(s)][callbackfield])) for s in cat_names] return cat_names, button_list
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)
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
def send_ts_groups_by_user(bot, update, chat_data, cldbid): text = '?? ' + _('*Group list:*') + '\n\n' \ + _('Here is the TeamSpeak group list of this user, pressing any of them will take you to his detail.') back_button_row = [InlineKeyboardButton('?? ' + _('Back'), callback_data='GROUP_BY_USER_%s_BACK' % cldbid)] clean_pages(chat_data, update.effective_message.message_id) paginate_items(bot, update, chat_data, items=get_ts_groups_by_client_id(cldbid), principal_property='name', backend_property='sgid', text=text, callback='GROUP', additional_row=back_button_row)
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)
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)
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()
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)
def convert(self): return InlineKeyboardButton(text=self.text, **self.options)
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
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
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