我正在用 Python 编写 Telegram 机器人,并且想知道当我在机器人实例中按下按钮时如何获取或存储“文本”键的值。因为我想用它来调整下一个调用的函数中显示的消息(我希望它很清楚......)
我当前的代码是这样的:
def live_main(update: Update, context: CallbackContext) -> None:
query = update.callback_query
query.answer()
keyboard = [
[
InlineKeyboardButton("1", callback_data=str(LIVE)),
InlineKeyboardButton("2", callback_data=str(LIVE))
],
[InlineKeyboardButton("Back", callback_data=str(STARTOVER))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
query.edit_message_text(
text="How many people will attend the live session?", reply_markup=reply_markup
)
return FIRST
def live(update: Update, context: CallbackContext) -> None:
query = update.callback_query
query.answer()
keyboard = [
[InlineKeyboardButton("Btc", callback_data=str(PAYLIVE))],
[InlineKeyboardButton("Paypal", callback_data=str(PAYLIVE))],
[InlineKeyboardButton("Back", callback_data=str(LIVEM))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
query.edit_message_text(
text="Price for {**CallbackQuery.text**} { is {price_live/**CallbackQuery.text**)} USD or the equivalent in crypto-currencies. Please, choose your payment method. (And to be perfectly honest, we prefer crypto...)", reply_markup=reply_markup
)
return FIRST
如您所见,我想使用 live 函数内 live_main 函数的“1”或“2”值(我在其中放置了 CallbackQuery.text 占位符)。 我希望有人能帮帮忙。 问候
但是你可以记住你发送的内容!
要获取按钮文本,您应该生成文本ID并通过callback_data传递它
BUTTONS = {
'1': 'first button',
'2': 'second button',
'3': 'third button',
}
markup = InlineKeyboardMarkup()
for button_id, button_text in BUTTONS.items():
markup.add(InlineKeyboardButton(text=button_text, callback_data=f'menu:{button_id}'))
通过
labda c: c.data.startswith('menu:')
处理 CallbackQuery
然后解析数据并在你的字典中找到它:
button_id = callback_query.data.split(':')[1]
button_text = BUTTONS.get(button_id)
完成:)
附注:
循环原消息中的所有
inline_keyboards
并搜索右侧query.data
键:
def get_clicked_button_text(query):
key = query.data
for first_level in query.message["reply_markup"]["inline_keyboard"]:
for second_level in first_level:
if second_level["callback_data"] == key:
return second_level["text"]
例如。如果单击按钮 2:
def live_main(update: Update, context: CallbackContext) -> None:
query = update.callback_query
await query.answer()
button_text = get_clicked_button_text(query)
print(button_text)
#2