vavania
vavania

Reputation: 61

How to sendmessage after answercallbackquery in Telegram?

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);                
  }

Upvotes: 2

Views: 5900

Answers (1)

vavania
vavania

Reputation: 61

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!

Upvotes: 4

Related Questions