How to create inline buttons in PHP Bot Telegram

Ciccio picture Ciccio · Aug 26, 2017 · Viewed 16.5k times · Source

I must program in php due to company needs... but I am working with php for first time... and it's the first time I am working with telegram bot :'( In some way, before, when i ran the command /start and doWork everything worked...

but now I must modify the bot, in a way that all commands are "hidden" behind some telegram button... Here how I edited my php page:

if(strpos($text, "/start") === 0)
{
    $response = "Ciao $firstname, benvenuto!";

    $keyboard = [
        'inline_keyboard' => [
            [
                ['text' => 'forward me to groups']
            ]
        ]
    ];

    $encodedKeyboard = json_encode($keyboard);
    $parameters = 
        array(
            'chat_id' => $chatId, 
            'text' => $response, 
            'reply_markup' => $encodedKeyboard
        );
    $parameters["method"] = "sendMessage";
    echo json_encode($parameters);

}

With BotFather I ran the command /setinline too...

So I think I am working how I parameters array.. can anyone help me please?

Ps.: (if can anyone suggest me also an IDE I work with please... i am using notepad++ now)

Thank you all

Answer

Majeed Askari picture Majeed Askari · Aug 27, 2017

First of all you don't need to use /setinline command in botFather. this command is for "inline mode" while you are using an inline_keyboard which is a custom keyboard in normal chat mode.

also you need to provide a callback_data in your keyboard array for each button:

$keyboard = [
    'inline_keyboard' => [
        [
            ['text' => 'forward me to groups', 'callback_data' => 'someString']
        ]
    ]
];
$encodedKeyboard = json_encode($keyboard);
$parameters = 
    array(
        'chat_id' => $chatId, 
        'text' => $response, 
        'reply_markup' => $encodedKeyboard
    );

send('sendMessage', $parameters); // function description Below

At last you need to send it via curl. here is a function i use in my codes:

function send($method, $data)
{
    $url = "https://api.telegram.org/bot<Bot-Token>". "/" . $method;

    if (!$curld = curl_init()) {
        exit;
    }
    curl_setopt($curld, CURLOPT_POST, true);
    curl_setopt($curld, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curld, CURLOPT_URL, $url);
    curl_setopt($curld, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($curld);
    curl_close($curld);
    return $output;
}

P.S. I personally use PhpStorm, its nice ;)