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
)
python类InlineKeyboardButton()的实例源码
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 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 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 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)