gpt4 book ai didi

python - 在电报机器人中单击时如何更改内联按钮文本?

转载 作者:行者123 更新时间:2023-12-01 22:18:31 25 4
gpt4 key购买 nike

我在电报机器人创建方面还很陌生。我正在使用python-telegram-bot构建电报机器人的模块。我陷入了实现一个内联按钮的困境,该按钮在单击时会更改其文本。您能分享一些来源或方式吗?提前致谢。

简而言之,我的意思如下。例如,一个带有文本“1”的内联按钮,当我单击时,我希望它更改为“2”。

def one(update, context):
"""Show new choice of buttons"""
query = update.callback_query
bot = context.bot
keyboard = [
[InlineKeyboardButton("3", callback_data=str(THREE)),
InlineKeyboardButton("4", callback_data=str(FOUR))]
]
keyboard[0][int(query)-1] = InlineKeyboardButton("X", callback_data=str(THREE))
reply_markup = InlineKeyboardMarkup(keyboard)
bot.edit_message_text(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
text="First CallbackQueryHandler, Choose a route",
reply_markup=reply_markup
)
return FIRST

最佳答案

终于,我可以实现我想要的了。也许代码有点长而且看起来不太酷,但我发布了我的解决方案。

from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Updater,
CommandHandler,
CallbackQueryHandler,
ConversationHandler)

import logging

FIRST, SECOND = range(2)

counter = 0

keyboard = [[InlineKeyboardButton('Decrement', callback_data='0')],
[InlineKeyboardButton(f'[{counter}]', callback_data='1')],
[InlineKeyboardButton('Increment', callback_data='2')]]


def start(update, context):
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(
'Please choose one of our services\n',
reply_markup=reply_markup
)

return FIRST


def update_and_get_reply_markup(inc_or_dec=None):
global keyboard
global counter
if inc_or_dec == True:
counter += 1
else:
counter -= 1

keyboard[1][0] = InlineKeyboardButton(
f'[{counter}]', callback_data='2')

reply_markup = InlineKeyboardMarkup(keyboard)

return reply_markup


def increment(update, context):
query = update.callback_query

reply_markup = update_and_get_reply_markup(inc_or_dec=True)
bot = context.bot
bot.edit_message_text(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
text="Please choose one of our services\n",
reply_markup=reply_markup
)

return FIRST


def decrement(update, context):
query = update.callback_query

reply_markup = update_and_get_reply_markup()
bot = context.bot
bot.edit_message_text(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
text="Please choose one of our services\n",
reply_markup=reply_markup
)

return FIRST


def main():
updater = Updater(
'TOKEN', use_context=True)
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
FIRST: [CallbackQueryHandler(decrement, pattern='^'+str(0)+'$'),
CallbackQueryHandler(increment, pattern='^'+str(2)+'$')]
},
fallbacks=[CommandHandler('start', start)]
)

dp.add_handler(conv_handler)
updater.start_polling()
updater.idle()

if __name__ == "__main__":
main()

关于python - 在电报机器人中单击时如何更改内联按钮文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59898515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com