Как изменить текст встроенной кнопки при ее нажатии в боте telegram? - PullRequest
3 голосов
/ 24 января 2020

Я довольно новичок в создании ботов для телеграмм. Я использую модуль 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

1 Ответ

1 голос
/ 25 января 2020

Наконец-то я смог достичь того, чего хотел. Может быть, немного длинный и не очень красивый код, но я опубликовал свое решение.

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()

...