I’m trying to add an inline keyboard to my Telegram bot using PHP but it’s not working. Here’s what I’ve tried:
$keyboard = [
'inline_keyboard' => [
[['text' => 'Button1', 'callback_data' => 'test']]
]
];
$keyboard = json_encode($keyboard);
$sendto = API_URL . 'sendMessage?chat_id=' . $chatID . '&text=' . $reply . '&parse_mode=HTML&reply_markup=' . $keyboard;
The regular keyboard works fine, but this inline version doesn’t show up. Am I formatting the array wrong? Or is there something else I’m missing?
I’ve looked at the Telegram Bot API docs but still can’t figure it out. Any help would be great!
I’ve encountered this problem before, and it can be frustrating. One thing that worked for me was double-checking the API_URL constant. Make sure it includes the correct bot token and ends with a forward slash. Also, consider using cURL instead of direct URL manipulation for more reliable results.
Here’s a snippet that worked in my project:
$ch = curl_init(API_URL . 'sendMessage');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'chat_id' => $chatID,
'text' => $reply,
'parse_mode' => 'HTML',
'reply_markup' => json_encode($keyboard)
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
This approach has been more reliable in my experience. Let me know if it helps!
I’ve dealt with this issue before, and it can be tricky. One thing to check is the format of your ‘callback_data’. Make sure it’s a string, not an integer. Also, verify that your bot has the necessary permissions to send inline keyboards.
Another potential solution is to use the Telegram Bot SDK for PHP. It simplifies these processes and handles encoding automatically. Here’s a quick example:
$telegram = new Telegram\Bot\Api('YOUR_BOT_TOKEN');
$keyboard = [
['text' => 'Button1', 'callback_data' => 'test']
];
$reply_markup = $telegram->replyKeyboardMarkup([
'inline_keyboard' => [$keyboard],
'resize_keyboard' => true,
'one_time_keyboard' => true
]);
$telegram->sendMessage([
'chat_id' => $chatID,
'text' => $reply,
'reply_markup' => $reply_markup
]);
This approach has worked consistently for me. Give it a try and see if it resolves your issue.
yo ethan, i had the same issue! try using urlencode() on ur $keyboard after json_encode. like this:
$keyboard = urlencode(json_encode($keyboard));
that fixed it for me. telegram can be picky bout special chars in the url. give it a shot n lemme kno if it works!