php - 电报机器人 PHP : Warning: file_get_contents failed to open stream: 400 Bad Request

标签 php telegram-bot

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

Warning: file_get_contents(https://api.telegram.org/bottoken/sendMessage): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in G:\xampp\htdocs\xbot\file.php on line 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();
}

?>

最佳答案

问题是您的函数 process_message() 期望 create_response() 返回一个字符串,而不起作用的代码是在存在以下情况时返回一个数组:结果和没有结果时的字符串。最好始终返回相同类型的数据。

要修复此问题,请将 create_response() 函数更改为始终返回数组,并让 process_message() 根据需要使用它,即将其转换为一个字符串。

顺便说一句,您的return命令必须是函数中执行的最后一个命令。在它后面有 mysqli_close($conn); ,如果 return 在它上面,则永远不会执行。

因此,这两个函数变为:

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

关于php - 电报机器人 PHP : Warning: file_get_contents failed to open stream: 400 Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31494561/

相关文章:

php - 电报机器人找不到从(截断...)开始的实体的结尾

php - 尝试安装 homebrew php 时 OSX 不尊重 PATH

php - 在php中获取x的y根,例如8的3根是2

php - 单选按钮显示悬停在两个单选按钮之间使用 jquery

telegram - 如何从 Telegram 组下载所有共享媒体文件?

python-3.x - 电报机器人 : how to ask for user input on button click

php - Codeigniter form_helper 将数据库行作为选择菜单中的值

php - Magento V2 API 覆盖产品信息模型 V2(属性未显示)

java - 如何在用户单击时更改 InlineKeyboardButton 标签?

telegram-bot - 为什么我不能通过它的 id 发送贴纸