'Telegram Bot: How to get callback_data value?
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"
]);
}
}
Solution 1:[1]
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
Solution 2:[2]
On update you have an array so you can get like below:
$callback_query_data = $update['callback_query']['data'];
Solution 3:[3]
change the word 'keyboard' to 'inline_keyboard' will solve your problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | AlexR1712 |
Solution 2 | |
Solution 3 | billynhk |