首页 > 解决方案 > 电报机器人 - sendMessage 文本

问题描述

我在使用 PHP 编程电报机器人时遇到了 2 个问题。

  1. 问题:请,当我尝试使用电报 API 发送更多行的文本时。通过此代码:
<?php
$update = file_get_contents('php://input');
$update = json_decode($update, true);
$chatId= $update["message"]["from"]["id"]?$update["message"]["from"]["id"]:null;
$mess= "here is my text.";
$mess = $mess. "\n";
$mess = $mess. " this is new line".;
send($mess, $chatId);

function send($text,$chat){
   if(strpos($text, "\n")){
        $text = urlencode($text);
    }

    $parameters = array(
        "chat_id" => $chat,
        "text" => $text,
        "parse_mode" => "Markdown"
    );

    api("sendMessage?", $parameters)
}

function api($method,$command){
$token = "******";
$api = "https://api.telegram.org/bot$token/$method";

    if(!$curld = curl_init()){
       echo $curld; 
    }
    curl_setopt($curld, CURLOPT_VERBOSE, true);
    curl_setopt($curld, CURLOPT_POST, true);
    curl_setopt($curld, CURLOPT_POSTFIELDS, $command);
    curl_setopt($curld, CURLOPT_URL, $api);
    curl_setopt($curld, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curld, CURLOPT_TIMEOUT, 30);
    curl_setopt($curld, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curld, CURLOPT_SSL_VERIFYHOST, FALSE);
    $apiRequest = curl_exec($curld);
    curl_close($curld);
    return $apiRequest;
}

我在电报机器人中的文字如下所示:

“这里+是+我的+文本。+这个+是+新+行。”

  1. 问题,也许是问题:当用户来到我的电报机器人时,我希望用户看到我创建的键盘按钮。现在我只有新用户,他必须点击“开始”按钮。但是我希望用户在他有时返回时看到键盘的按钮。

你能帮我解决这个问题吗?

谢谢

标签: phptelegramtelegram-bot

解决方案


文本中的特殊字符是由urlencode()调用引起的。

由于您将数据作为POSTFIELD传递,因此无需使用urlencode()

此外,还有一些语法错误,比如.后面的$mess = $mess. " this is new line".;.

更新脚本:

<?php
    $update = file_get_contents('php://input');
    $update = json_decode($update, true);
    $chatId= $update["message"]["from"]["id"]?$update["message"]["from"]["id"]:null;
    $mess= "here is my text.";
    $mess = $mess. "\n";
    $mess = $mess. " this is new line";

    send($mess, $chatId);

    function send($text,$chat){

        $parameters = array(
            "chat_id" => $chat,
            "text" => $text,
            "parse_mode" => "Markdown"
        );

        api("sendMessage", $parameters);
    }

    function api($method, $command){

        $token = "!!";
        $api = "https://api.telegram.org/bot{$token}/{$method}";

        if(!$curld = curl_init()){
           echo $curld;
        }
        // curl_setopt($curld, CURLOPT_VERBOSE, true);
        curl_setopt($curld, CURLOPT_POST, true);
        curl_setopt($curld, CURLOPT_POSTFIELDS, $command);
        curl_setopt($curld, CURLOPT_URL, $api);
        curl_setopt($curld, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curld, CURLOPT_TIMEOUT, 30);
        curl_setopt($curld, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curld, CURLOPT_SSL_VERIFYHOST, FALSE);
        $apiRequest = curl_exec($curld);
        curl_close($curld);
        return $apiRequest;
    }

在此处输入图像描述


推荐阅读