php telegram answercallbackquery sendmessage

2019-08-19 10:12发布

问题:

I'm trying to develop a Telegram Bot in PHP, but i failed to make my bot answer the user when he press an inline button. Can someone help me sending a message (sendMessage method) after calling the answerCallback method?

Here's my last trial code:

if ($call_back_query != null) {

    $response = $call_back_query;
    $botUrl = "https://api.telegram.org/bot" . BOT_TOKEN . "/answerCallbackQuery";
    $postFields = array('callback_query_id' =>  $call_back_id, 'text' => $response);
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
    curl_setopt($ch, CURLOPT_URL, $botUrl); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    $output = curl_exec($ch);

        //send Text
    $response = "help me if you can, i'm feeling down";
    header("Content-Type: application/json");
    $parameters = array('chat_id' => $chatId, "text" => $response);
    $parameters["method"] = "sendMessage";
    echo json_encode($parameters);


  }

thank you

回答1:

Ok, i've understood the problem:

In sendText i have to use $call_back_from instead of $chatId, because he's answering to the callback query and not a simple message (i think so...)

while

$chatId = isset($message['chat']['id']) ? $message['chat']['id'] : "";

$call_back_from = isset ($update['callback_query']['from']['id']) ? $update['callback_query']['from']['id'] : "";

the code will be

if ($call_back_query != null) {

    $response = $call_back_query;
    $botUrl = "https://api.telegram.org/bot" . BOT_TOKEN . "/answerCallbackQuery";
    $postFields = array('callback_query_id' =>  $call_back_id, 'text' => $response);
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
    curl_setopt($ch, CURLOPT_URL, $botUrl); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    $output = curl_exec($ch);

        //send Text
    $response = "help me if you can, i'm feeling down";
    header("Content-Type: application/json");
    $parameters = array('chat_id' => $call_back_from, "text" => $response);
    $parameters["method"] = "sendMessage";
    echo json_encode($parameters);


  }

Hope this could be helpful! Have a nice try!