电报 webhook 不使用数据库数据

telegram webhook not working with database data

我创建了一个电报机器人。但是我没有对回复进行硬编码,而是决定从数据库中提取它们……下面……问题是机器人没有 return 我从数据库中提取的数据。它return在电报中为空..但是如果我回显变量 $mes['message'] 在我的浏览器中,它 return 是有效数据。可能是什么问题?

 $message1 = $db->prepare("SELECT message FROM about where id=1 ");
    $message1->execute();
    $mes = $message1->fetch();
    if (isset($message['text'])) {
        // incoming text message
        $text = $message['text'];

        if ((strpos($text, "/start") === 0) || (strpos($text, "/start") === 0) ) {
            apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array(
                'keyboard' => array(array('Hello', 'Hi')),
                'one_time_keyboard' => true,
                'resize_keyboard' => true)));
        } else if ($text === "Hello" || $text === "Hi") {
            apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you'));
        } else if (strpos($text, "/stop") === 0) {
            apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Did i do anything wrong?', 'reply_markup' => array(
                'keyboard' => array(array('Yes', 'No')),
                'one_time_keyboard' => true,
                'resize_keyboard' => true)));
        }else if ($text === "No") {
            apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you'));
        }else if ($text === "Tell me more") {
            apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => '<?php echo $mes2["message"];?>'));
        } else {
            apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => '<?php echo $mes1["message"]; ?>'));
        }


    } else {
        apiRequestJson("sendMessage", ['chat_id' => $chat_id, "text" => $me2 , 'reply_markup' => [
            'keyboard' => [['Tell me more', 'Got it']],
            'one_time_keyboard' => true,
            'resize_keyboard' => true]]);
    }

您不需要对函数中的参数使用

看看你的其他变量,比如 $chat_id, $me2...你应该使用 "text" => $mes1["message"]"text" => $mes2["message"]

它已经被 PHP 处理了。你不需要再嵌入一次

     }else if ($text === "Tell me more") {
        apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => $mes2["message"]));
    } else {
        apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => $mes1["message"]));
    }

我发现了问题。 数据库对象 $text 在包含 if 语句的函数中不可用。 我不得不在函数中将其声明为全局的。 例如

    function sendMessage () {
    global $text;
    //if statements here
    }

现在可以正常使用了