Telegram Bot custom keyboard in PHP

Martin picture Martin · Jun 28, 2015 · Viewed 30.2k times · Source

I'm trying to make a Telegram Bot in PHP with a custom keyboard. The message is delivered, but the custom keyboard won't work. $keyb = array('keyboard' => array(array("A", "B"))); also no succes.

The sendMessage method referrers to ReplyKeyboardMarkup for the object. Making an array for ReplyKeyboardMarkup doesn't work. Also tried to json_encode($keyb) but that's also not the solution.

I searched in GitHub for examples but I haven't found one where the custom keyboard is used. Telegram runs on iPhone and desktop, both up-to-date.

Sample code:

$url = "https://api.telegram.org/bot<token>/sendMessage";

$keyb = array('ReplyKeyboardMarkup' => array('keyboard' => array(array("A", "B"))));
$content = array('chat_id' => <chat_id>, 'reply_markup' => $keyb, 'text' => "Test");

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  //fix http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);
curl_close ($ch);
var_dump($server_output);

Answer

Dan Belden picture Dan Belden · Jun 28, 2015

The docs seem to indicate you need to provide the reply_markup parameter as a JSON serialised object... kinda stupid for a form POST endpoint:

$replyMarkup = array(
    'keyboard' => array(
        array("A", "B")
    )
);
$encodedMarkup = json_encode($replyMarkup);
$content = array(
    'chat_id' => <chat_id>,
    'reply_markup' => $encodedMarkup,
    'text' => "Test"
);

Does this one work?