Telegram Bot: How to get callback_data value?

Patricio Carvajal H. picture Patricio Carvajal H. · Oct 29, 2017 · Viewed 14.6k times · Source

I have a simple bot in Telegram. My "/select" command displays two buttons and each button has its own value. So, if user clicks on a button I can get the text, but I can't get the callback_data value. Not sure what I am doing wrong.

Here's the code:

$update = json_decode(file_get_contents('php://input'));

$callback_query = $update['callback_query'];

if (isset($callback_query)){
    //Fetching callback
    $data = $callback_query->data;
    $message = $callback_query->message;
    $message_id = $callback_query->message->message_id;
    $chat_id = $message->chat->id;

    switch($data){
        case "1":
           bot('SendMessage',[
               'chat_id' => $chat_id,
               'text' => "1"
           ]);
           break;

       case "2":
           bot('SendMessage',[
               'chat_id' => $chat_id,
               'text' => "2"
            ]);
            break;
     }
   }else{

    $message = $update->message;
    $message_id = $update->message->message_id;
    $text = $message->text;
    $chat_id = $message->chat->id;

    //Statement beginning

    switch($text){

        case "/select":            
            $keyboard = array(
                'keyboard' => [[['text' =>  "one", 'callback_data' => "1"]],[['text' =>  "two", 'callback_data' => "2"]]],
                'resize_keyboard' => true, 
                'one_time_keyboard' => true
            );
        $markup = json_encode($keyboard, true);            

        bot('SendMessage',[
            'chat_id' => $chat_id,
            'reply_markup' => $markup,
            'text' => "Choose your option"
        ]);
        break;            

    default:

        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' => "This is a test"
        ]);
}

}

Answer

AlexR1712 picture AlexR1712 · Oct 29, 2017

You only need to proccess the update incoming from telegram to your webhook, this means you need to make condition if the update is of type callback_query and parse the data.

Please check telegram documentation, or watch some examples for PHP like:

How can I differentiate between a 'Message' update and a 'Callback Query' update? (Telegram Bot API)

https://jqueryajaxphp.com/telegram-bot-api-keyboards-callbacks/

Good luck! & Keep Calm and Send Telegram's :D