Home > Mobile >  Telegram inline_keyboard doesn't work - PHP
Telegram inline_keyboard doesn't work - PHP

Time:09-24

<?php
require_once('core.php');
$content = file_get_contents("php://input");
$update = json_decode($content , true);
$chat_id = $update["message"]['chat']['id'];
$text = $update["message"]['text'];
$message_id = $update["message"]['message_id'];
if($text == '/start'){
    $matn = 'Welcome';
    MessageRequestJson('sendMessage' , array('chat_id'=>$chat_id , 'text'=>$matn , 'reply_markup'=>array(
    "inline_keyboard" => array(array(array("text" => "My Button Text"))))));
}
?>

I used sendMessage method and response 'Welcome' when user send '/start' to bot. I used reply_markup and inline_keyboard but when I run my code and I send '/start' it doesn't work!

This is core.php codes:

<?php
const BOT_TOKEN =  'I passed token here!';
const API_URL = 'https://api.telegram.org/bot'.BOT_TOKEN.'/';

function MessageRequestJson($method , $parameters){
    if (!$parameters) {
        $parameters = array();
    }

    $parameters["method"] = $method;

    $handle = curl_init(API_URL);
    curl_setopt($handle , CURLOPT_RETURNTRANSFER , true);
    curl_setopt($handle , CURLOPT_CONNECTTIMEOUT , 5);
    curl_setopt($handle , CURLOPT_TIMEOUT , 60);
    curl_setopt($handle , CURLOPT_POSTFIELDS, json_encode($parameters));
    curl_setopt($handle , CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    $result = curl_exec($handle);
    return $result;
}
?>

CodePudding user response:

If I run your code, but include a var_dump($result); Telegram returns the following error:

Bad Request:

Can't parse inline keyboard button: Text buttons are unallowed in the inline keyboard

That's caused by an invalid reply_markup, consider this alternative:

$matn = 'Welcome';
$keyboard = [
    "inline_keyboard" => [
        [
            [
                "text" => "My Button Text",
                "callback_data" => "test"
            ]
        ]
    ]
];
MessageRequestJson('sendMessage' , [ 'chat_id'=> $chat_id , 'text'=> $matn , 'reply_markup' => $keyboard ]);

I left the MessageRequestJson() unchanged.

Running the code after applying the above, shows me: enter image description here

  • Related