How to handle clicking on my keyboard button in TelegramBot, created using Telegram Bot API - PHP SDK ?

There is such code:

$telegram = new Telegram\Bot\Api('MY_KEY'); $message = $telegram->getWebhookUpdates(); $chatId = $message['message']['chat']['id']; $keyboard = array( array(array('callback_data'=>'/butt1','text'=>'Кнопка 1')), array(array('callback_data'=>'/buut2','text'=>'Кнопка 2')), ); $reply_markup = $telegram->replyKeyboardMarkup([ 'keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => false ]); $telegram->sendMessage(array( 'chat_id' => $chatId, 'text' => 'НаТмитС Π½Π° ΠΎΠ΄Π½Ρƒ ΠΈΠ· ΠΊΠ½ΠΎΠΏΠΎΠΊ:', 'reply_markup' => $reply_markup, )); 

How can I catch, for example, pressing the button: "Button 1", with the command: / butt1 ???

    1 answer 1

    As I understood in version 2.2 of this library, you can only use regular text buttons without callback_data - for the transfer of which you need to use inline buttons.

    1) You need to upgrade to the dev-version, if through the composer, then like this:

     composer require irazasyed/telegram-bot-sdk:dev-master 

    2) Further, the code changes somewhat:

     <?php use Telegram\Bot\Commands\Command; use Telegram\Bot\Keyboard\Keyboard; $telegram = new Telegram\Bot\Api('MY_KEY'); $update = $telegram->getWebhookUpdates(); // Π΄Π°Π½Π½Ρ‹Π΅ сообщСния Π² зависимости ΠΎΡ‚ callback_query if ( isset($this->update['callback_query'])) { $message = $update['callback_query']; } else { $message = $update; } $chatId = $message['message']['chat']['id']; // ΠΏΡ€Π°Π²ΠΈΠ»ΡŒΠ½ΠΎ Ρ„ΠΎΡ€ΠΌΠΈΡ€ΡƒΠ΅ΠΌ ΠΊΠ»Π°Π²ΠΈΠ°Ρ‚ΡƒΡ€Ρƒ: $keyboard = [ [ Keyboard::inlineButton(['callback_data'=>'/butt1','text'=>'Кнопка 1']), Keyboard::inlineButton(['callback_data'=>'/buut2','text'=>'Кнопка 2']) ] ]; $reply_markup = $telegram->replyKeyboardMarkup([ // 'keyboard' => $keyboard, // вмСсто этого ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅ΠΌ: 'inline_keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => false ]); // Ссли Π½Π°ΠΆΠ°Π»ΠΈ ΠΊΠ½ΠΎΠΏΠΊΡƒ: if ( isset($this->update['callback_query'])) { $telegram->sendMessage(array( 'chat_id' => $chatId, 'text' => "Π’Ρ‹ Π½Π°ΠΆΠ°Π»ΠΈ Π½Π° ΠΊΠ½ΠΎΠΏΠΊΡƒ с ΠΊΠΎΠ΄ΠΎΠΌ: " . $message['data'], // ΠΈΠΌΠ΅Π½Π½ΠΎ Π² $message['data'] - Π±ΡƒΠ΄Π΅Ρ‚ Ρ‚ΠΎ Ρ‡Ρ‚ΠΎ прописано Ρƒ Π½Π°ΠΆΠ°Ρ‚ΠΎΠΉ ΠΊΠ½ΠΎΠΏΠΊΠΈ Π² качСствС callback_data 'reply_markup' => $reply_markup, )); } else { $telegram->sendMessage(array( 'chat_id' => $chatId, 'text' => 'НаТмитС Π½Π° ΠΎΠ΄Π½Ρƒ ΠΈΠ· ΠΊΠ½ΠΎΠΏΠΎΠΊ:', 'reply_markup' => $reply_markup, )); } 

    Maybe someone else will come in handy)

    • The answer is generally wrong! Have you ever checked whether the code works? - Hussein
    • checked, works! if in your opinion β€œthe answer is generally wrong”, you need to bring your correct proof, and not just emotions) - Enshtein