电报webhook php机器人没有回答

时间:2016-03-28 14:25:00

标签: php webhooks telegram telegram-bot

我正在尝试使用webhook设置电报机器人。我可以使用getUpdates,但我希望它能与webhook一起使用。

我的网站(托管机器人php脚本)的SSL证书正常工作(我在地址栏中获得了绿色锁定):

我用

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

我得到了:{“ok”:true,“result”:true,“description”:“Webhook已设置”}

(我不知道这是否重要,但我已经给了文件夹和脚本的rwx权限)

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

?>

但是当我向机器人写任何东西时,我没有得到答案......

任何想法为什么?

由于

1 个答案:

答案 0 :(得分:3)

在您的问题中,不清楚脚本位置。看到您的代码,您似乎尝试通过url_get_contents加载请求以检索电报服务器响应。如果您的机器人没有 webhook,这是正确的方法。否则,在设置webhook后,您必须处理传入请求。

即,如果您将webhook设置为https://example.com/mywebhook.php,则在https://example.com/mywebhook.php脚本中必须编写如下内容:

<?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
    }
}
相关问题