Telegram Bot PHP:警告:file_get_contents无法打开流:400 Bad Request

时间:2015-07-18 19:02:12

标签: php telegram-bot

我正在为电报机器人编辑文件php。当我在电报上测试时,它根本没有响应。在PHP命令行上,它说:

  

警告:   的file_get_contents(https://api.telegram.org/bottoken/sendMessage):   未能打开       stream:HTTP请求失败!在G:\ xampp \ htdocs \ xbot \ file.php上的HTTP / 1.1 400错误请求       第39行

第39行:

 $result = file_get_contents(request_url('sendMessage'), false, $context);

但是,当我将函数create_response更改为:

时,它会起作用
function create_response($text)
{
    $conn = mysqli_connect("localhost","root","admintma","aq");
    $data = array();
    $sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
        "qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
        "qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
    $cari = mysqli_query($conn, $sql);
    //$hasil = '';

    if (mysqli_num_rows($cari) > 0) {
        // output data of each row
        while($row = mysqli_fetch_array($cari)) {
            $hasil = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" . 
                $row["ayat"]. ": " . $row["ayattext"]. ". ";
            var_dump($hasil);
        }
    } else {
        $hasil = "0 results";
    }
    return $hasil;
    mysqli_close($conn);
}

但它只显示最后的结果,而在php命令行显示完整的结果:

string(157) "Value1"
string(219) "Value2"
string(462) "Value3"
string(555) "Value4"
string(246) "Value5"
{
    "ok": true,
    "result": {
        "message_id": 197,
        "from": {
            "id": 107653xxx,
            "first_name": "x_bot",
            "username": "x_bot"
        },
        "chat": {
            "id": 2887198,
            "first_name": "xxx",
            "username": "xxx"
        },
        "date": 1437240345,
        "reply_to_message": {
            "message_id": 196,
            "from": {
                "id": 2887xxx,
                "first_name": "xxx",
                "username": "xxx"
            },
            "chat": {
                "id": 2887xxx,
                "first_name": "xxx",
                "username": "xxx"
            },
            "date": 1437240342,
            "text": "mengetahuinya"
        },
        "text": "Value5"
    }
}

我很困惑,如何解决这个问题?提前谢谢。

这是完整的代码:

<?php
include("token.php");
//include("db.php");

function request_url($method)
{
    global $TOKEN;
    return "https://api.telegram.org/bot" . $TOKEN . "/". $method;
}

function get_updates($offset)
{
    $url = request_url("getUpdates")."?offset=".$offset;
    $resp = file_get_contents($url);
    $result = json_decode($resp, true);
    if ($result["ok"]==1)
        return $result["result"];
    return array();
}

function send_reply($chatid, $msgid, $text)
{
    $data = array(
        'chat_id' => $chatid,
        'text'  => $text,
        'reply_to_message_id' => $msgid
    );
    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data),
        ),
    );
    $context  = stream_context_create($options);

    $result = file_get_contents(request_url('sendMessage'), false, $context);
    print_r($result);
}

function create_response($text)
{
    $conn = mysqli_connect("localhost","root","xxx","aq");
    $data = array();
    $sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
        "qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
        "qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
    $cari = mysqli_query($conn, $sql);
    //$hasil = '';

    if (mysqli_num_rows($cari) > 0) {
        $hasil = array();
        // output data of each row
        while($row = mysqli_fetch_array($cari)) {
            $hasil[] = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" . 
                $row["ayat"] . ": " . $row["ayattext"] . ". ";
            //var_dump($hasil);
        }
    } else {
        $hasil = "0 results";
    }
    return $hasil;
    mysqli_close($conn);
}

function process_message($message)
{
    $updateid = $message["update_id"];
    $message_data = $message["message"];
    if (isset($message_data["text"])) {
        $chatid = $message_data["chat"]["id"];
        $message_id = $message_data["message_id"];
        $text = $message_data["text"];
        $response = create_response($text);
        send_reply($chatid, $message_id, $response);
    }
    return $updateid;
}

function process_one()
{
    $update_id  = 0;

    if (file_exists("last_update_id")) {
        $update_id = (int)file_get_contents("last_update_id");
    }

    $updates = get_updates($update_id);

    foreach ($updates as $message)
    {
        $update_id = process_message($message);
    }
    file_put_contents("last_update_id", $update_id + 1);

}

while (true) {
    process_one();
}

?>

1 个答案:

答案 0 :(得分:2)

问题是你的函数process_message()期望create_response()返回一个字符串,而那些不起作用的代码在有结果时返回一个数组,在没有结果时返回一个字符串。最好是它总是返回相同类型的数据。

要解决此问题,请将create_response()函数更改为始终返回一个数组,然后让process_message()使用它,但需要将其转换为字符串。

顺便说一下,return命令必须是函数中执行的最后一个命令。你之后有mysqli_close($conn);,如果返回高于它,则永远不会被执行。

所以,这两个功能变为:

function create_response($text)
{
    $conn = mysqli_connect("localhost","root","xxx","aq");
    $data = array();
    $sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
        "qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
        "qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
    $cari = mysqli_query($conn, $sql);

    $hasil = array();
    if (mysqli_num_rows($cari) > 0) {
        // output data of each row
        while($row = mysqli_fetch_array($cari)) {
            $hasil[] = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" . 
                $row["ayat"] . ": " . $row["ayattext"] . ". ";
        }
    }
    mysqli_close($conn);
    return $hasil;
}

function process_message($message)
{
    $updateid = $message["update_id"];
    $message_data = $message["message"];
    if (isset($message_data["text"])) {
        $chatid = $message_data["chat"]["id"];
        $message_id = $message_data["message_id"];
        $text = $message_data["text"];
        $responseArr = create_response($text);
        if (count($responseArr) > 0) {
            $response = implode(". ", $responseArr) . ".";
        } else {
            $response = "0 results";
        }
        send_reply($chatid, $message_id, $response);
    }
    return $updateid;
}