【问题标题】:Telegram webhook php bot doesn't answerTelegram webhook php bot 不响应
【发布时间】:2016-07-15 19:55:52
【问题描述】:

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

我的网站(托管 bot 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 机器人:(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;
}

?>

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

有什么想法吗?

谢谢

【问题讨论】:

    标签: php webhooks telegram telegram-bot


    【解决方案1】:

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

    即,如果您将 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
        }
    }
    

    【讨论】:

    • 感谢您的帮助。我完全按照您的示例设置了 webhook,并按照您的建议进行了更改,但机器人仍然像以前一样保持沉默。
    • 如果您知道自己的聊天ID,请进行一些测试向您发送消息。您确定 webhook 设置正确吗?
    • 拿到了聊天ID,现在试试
    • 好的,我可以在知道 chat_id 的情况下给自己发送消息。我认为我的 webhook 设置正确(我完全按照我在问题中写的那样做),但必须打破某些东西,因为它似乎不起作用。
    • 将用于向您发送“ok”之类的消息的代码放在脚本的顶部。然后在电报上写一些东西:如果你收到“OK”,你的 webhook 就可以了,否则就不行。
    猜你喜欢
    • 1970-01-01
    • 2015-09-24
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 2020-09-22
    • 2017-08-03
    • 2018-03-12
    相关资源
    最近更新 更多