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