Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get callback_data from Telegram in PHP

I want to get callback data from response but array is empty.

I am trying to show in message callback_data array.

Here is my code:

$botToken = "token";
$botAPI = "https://api.telegram.org/bot" . $botToken;
$update = json_decode(file_get_contents('php://input'), TRUE);
$message = $update["message"]["text"]
$chatId = $update["message"]["chat"]["id"];
$callback_query = $update['callback_query'];
$callback_query_data = $callback_query['data'];
$url = $botAPI . '/sendMessage?chat_id=' . $chatId . '&text=';

if(isset($callback_query)){
    file_get_contents($url . $callback_query_data);
}

if($message == "/start"){
    $parameters = array('chat_id' => $chatId, "text" => "Здравствуйте. Выберите язык. \nАссалом. Забонро интихоб кунед.\nHi! Select your language.");
    $parameters["method"] = "sendMessage";
    $keyboard = ['inline_keyboard' => [[
        ['text' => "🇹🇯Точики", 'callback_data' => 'tajik'],
        ['text' =>  "🇷🇺Русский", 'callback_data' => 'russian'],
        ['text' => '🇺🇸English', 'callback_data' => 'english']
    ]]];
    $parameters["reply_markup"] = json_encode($keyboard, true);
    echo json_encode($parameters);
}

like image 680
Akram Baratov Avatar asked Mar 24 '20 13:03

Akram Baratov


People also ask

How can I send message from telegram to PHP?

To send a message to the Telegram channel use the following PHP script example: <? php $apiToken = "5082654068:AAF7quCLZ4xuTq2FBdo3POssdJsM_FRHwTs"; $data = [ 'chat_id' => '515382482', 'text' => 'Hello from PHP! ' ]; $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" .

What is the URL for Telegram API?

The first part of the URL indicates that you want to communicate with the Telegram API ( api.telegram.org ).

What is telegram callback query?

CallbackQuery(*args, **kwargs)[source] Bases: telegram.TelegramObject. This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present.


1 Answers

There are some small mistakes in the code, I'll try to address them;


Using php://input is only possible with webhooks, did you tell Telegram the location of your script?
https://api.telegram.org/bot<MY-TOKEN>/setWebhook?url=https://example.com/telegram/script.php

$callback_query_data = $callback_query['data']

Is only set if a button is pressed, this should be called after the check if there is some callback data

if (isset($update['callback_query'])) {
    $callback_query_data = $update['callback_query']['data'];
}


Working example:
<?php

    $update = json_decode(file_get_contents('php://input'), TRUE);

    $botToken = "<MY-TOKEN>";
    $botAPI = "https://api.telegram.org/bot" . $botToken;

    // Check if callback is set
    if (isset($update['callback_query'])) {

        // Reply with callback_query data
        $data = http_build_query([
            'text' => 'Selected language: ' . $update['callback_query']['data'],
            'chat_id' => $update['callback_query']['from']['id']
        ]);
        file_get_contents($botAPI . "/sendMessage?{$data}");
    }

    // Check for normal command
    $msg = $update['message']['text'];
    if ($msg === "/start") {

        // Create keyboard
        $data = http_build_query([
            'text' => 'Please select language;',
            'chat_id' => $update['message']['from']['id']
        ]);
        $keyboard = json_encode([
            "inline_keyboard" => [
                [
                    [
                        "text" => "english",
                        "callback_data" => "english"
                    ],
                    [
                        "text" => "russian",
                        "callback_data" => "russian"
                    ]
                ]
            ]
        ]);

        // Send keyboard
        file_get_contents($botAPI . "/sendMessage?{$data}&reply_markup={$keyboard}");
    }

enter image description here

Please let me know if something is not clear!

like image 107
0stone0 Avatar answered Oct 07 '22 00:10

0stone0