简体   繁体   中英

Telegram webhook php bot doesn't answer

I'm trying to set up a telegram bot with a webhook. I can get it to work with getUpdates, but I want it to work with a webhook.

My site (that hosts the bot php script) has the SSL certificate working (I get the green lock in the address bar):

I set up the webhook with

https://api.telegram.org/bot<token>/setwebhook?url=https://www.example.com/bot/bot.php

And I got: {"ok":true,"result":true,"description":"Webhook was set"}

(I don't know if this matters, but I have given rwx rights to both the folder and the script)

The php bot: ( https://www.example.com/bot/bot.php )

<?php

$botToken = <token>;
$website = "https://api.telegram.org/bot".$botToken;

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

$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];

switch($message) {
    case "/test":
        sendMessage($chatId, "test");
        break;
    case "/hi":
        sendMessage($chatId, "hi there!");
        break;
    default:
        sendMessage($chatId, "default");
}

function sendMessage ($chatId, $message) {
    $url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
    url_get_contents($url);

}

function url_get_contents($Url) {
    if(!function_exists('curl_init')) {
        die('CURL is not installed!');
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

?>

But when I write anything to the bot I receive no answers...

Any ideas why?

Thanks

In your question it's not clear the script location. Seeing your code, it seems that you try to load a request through url_get_contents to retrieve telegram server response. This is the correct method if your bot works without webhook. Otherwise, after setting webhook, you have to process incoming requests.

Ie, if you set webhook to https://example.com/mywebhook.php , in your https://example.com/mywebhook.php script you have to write something like this:

<?php

$request = file_get_contents( 'php://input' );
#          ↑↑↑↑ 
$request = json_decode( $request, TRUE );

if( !$request )
{
    // Some Error output (request is not valid JSON)
}
elseif( !isset($request['update_id']) || !isset($request['message']) )
{
    // Some Error output (request has not message)
}
else
{
    $chatId  = $request['message']['chat']['id'];
    $message = $request['message']['text'];

    switch( $message )
    {
        // Process your message here
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM