Creating a PHP-based Telegram Bot with Custom Keyboard

I’m working on a Telegram Bot using PHP and I’m stuck trying to add a custom keyboard. The bot sends messages fine but the keyboard isn’t showing up. I’ve tried different ways to set up the keyboard array but nothing seems to work.

Here’s what I’ve attempted:

$keyboard = [
    'keyboard' => [
        ['Option 1', 'Option 2'],
        ['Option 3', 'Option 4']
    ],
    'resize_keyboard' => true,
    'one_time_keyboard' => true
];

$message = [
    'chat_id' => $chat_id,
    'text' => 'Please choose an option:',
    'reply_markup' => json_encode($keyboard)
];

$response = file_get_contents('https://api.telegram.org/bot' . $bot_token . '/sendMessage?' . http_build_query($message));

The message sends but the keyboard doesn’t appear. I’ve checked the Telegram Bot API docs and I think I’m following the right structure. Am I missing something? Has anyone successfully implemented a custom keyboard in their PHP Telegram bot?

I’ve encountered this issue before, and it’s often due to how the reply_markup is encoded. Instead of using json_encode() directly on the $keyboard array, try creating a separate array for the reply_markup:

$reply_markup = [
‘keyboard’ => $keyboard[‘keyboard’],
‘resize_keyboard’ => true,
‘one_time_keyboard’ => true
];

$message = [
‘chat_id’ => $chat_id,
‘text’ => ‘Please choose an option:’,
‘reply_markup’ => json_encode($reply_markup)
];

This approach ensures that the keyboard structure is correctly formatted for the Telegram API. Also, double-check your bot token and make sure you’re using the latest version of the Telegram Bot API. If the issue persists, you might want to log the API response to see if there are any error messages.

hey, hve u tried using cURL instead of file_get_contents? sometimes it works better. heres a quick example:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘https://api.telegram.org/bot’ . $bot_token . ‘/sendMessage’);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($message));
$response = curl_exec($ch);
curl_close($ch);

give it a shot and see if that helps with the keyboard issue!

I’ve had success implementing custom keyboards in PHP Telegram bots by using the Telegram Bot API library. It simplifies the process and handles a lot of the quirks behind the scenes.

Here’s a snippet that worked for me:

$telegram = new Telegram($bot_token);

$keyboard = [
    ['Option 1', 'Option 2'],
    ['Option 3', 'Option 4']
];

$reply_markup = $telegram->replyKeyboardMarkup([
    'keyboard' => $keyboard, 
    'resize_keyboard' => true, 
    'one_time_keyboard' => true
]);

$telegram->sendMessage([
    'chat_id' => $chat_id,
    'text' => 'Please choose an option:',
    'reply_markup' => $reply_markup
]);

This approach has been reliable for me across different bot projects. If you’re still having issues, double-check your bot permissions and make sure it’s allowed to send keyboard commands in the chat.