I
I
Iva442020-01-20 16:48:30
PHP
Iva44, 2020-01-20 16:48:30

Processing a button click in a telegram bot?

I created a bot, and I'm stuck on the fact that I can't figure out how to send when I click on the button in the telegram, send a request to the server? There is a link when you go to which some action occurs, tell me how can I do so that I can send this request to the server when I click in the bot?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2020-01-30
@SwitcherN

First, you need to decide how you display the button - the event handling methods differ from this.
There are two types of buttons - a custom keyboard that replaces the standard keyboard, or online buttons - displayed under the message. For both options, do not forget to import the library:
from telebot import types
1. Custom keyboard generation.
I made a separate function for generating the keyboard, which receives as arguments. Creating a keyboard looks like this:

keyboard = utilits.generate_keyboard('Сделать заказ', 'Хочу скидку на заказ', 'Изменить персональную информацию')
bot.send_message(message.chat.id, msg, reply_markup=keyboard)

Here we create a keyboard using the generate_keyboard function, which I have in the utilits. We pass as arguments what should be written on the buttons.
The generate_keyboard function itself:
def generate_keyboard (*answer):
    keyboard = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
    for item in answer:
        button = types.KeyboardButton(item)
        keyboard.add(button)
    return keyboard

Here we call the ReplyKeyboardMarkup method from the types library. Then we iteratively go through the received arguments and generate buttons along the way adding buttons to the keyboard - keyboard.add(button).
We return the assembled keyboard.
Next, we process the received response. To process the received response, I came up with the following crutch - the status of each client, which I store along with its ID in the database. Status - in fact, the place of each client on the way to checkout:
@bot.message_handler(content_types=["text"])
def check_text_message(message):
    status = int()
    try:
        status = config.current_users[message.chat.id][0]
    except Exception as er:
        status = 0
    if status == 0:
        bot.send_message(message.chat.id, 'Извините, я запутался. Давайте начнем сначала')
        first_step(message)
    elif status == 10:
        if message.text == 'Сделать заказ':
            Dialogs.order(message) ...

That is, I check the status - "elif status == 10:"
If we get the answer "Make an order", then we display the following message, which we generate using the order function - "Dialogs.order(message)". I have the same function and changes the status, saving it along the way to the database, in case the bot "lies" and forgets who is at what stage.
2. Online keyboard generation.
Everything is very good. This is how I generate this type of keyboard, but here, in addition to the inscription on the button itself, it is also necessary to set a command by which we will process the event additionally (callback_data):
keyboard = utilits.generate_inline_keyboard(['Имя', 'change_name'],
                                                 ['Телефон', 'change_phone'],
                                                 ['️Адрес', 'change_adress'],
                                                 ['Вернуться обратно', 'back'])

def generate_inline_keyboard (*answer):
    keyboard = types.InlineKeyboardMarkup()
    temp_buttons = []
    for i in answer:
        temp_buttons.append(types.InlineKeyboardButton(text=i[0], callback_data=i[1]))
    keyboard.add(*temp_buttons)
    return keyboard

And this is event handling. It’s easier here, you can process it not through the status, but for a specific callback_data:
@bot.callback_query_handler(func=lambda call: True)
def ans(call):
    try:
        message = call.message
        if call.data == 'change_name':
            Dialogs.change_name(message)
        elif call.data == 'change_phone': ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question