【问题标题】:Telegram request "fopen failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request"电报请求“fopen 无法打开流:HTTP 请求失败!HTTP/1.1 400 错误请求”
【发布时间】:2020-12-18 05:01:13
【问题描述】:

我正在尝试向我的电报机器人发送消息。确切的名称变量不能让我这样做。

    $arr = array(
      $phoneFieldset => $phone,
      $nameFieldset => $name,
      $messageFieldset => $message,
    );
    foreach($arr as $key => $value) {
      $txt .= "<b>".$key."</b> ".$value."%0A";
    };
    
    $request = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}";
    
    echo $request;
    
    $sendToTelegram = fopen($request,"r");

请求回显输出,当脚本失败时:

https://api.telegram.org/botMYTOKEN/sendMessage?chat_id=-449128489&parse_mode=html&text=Телефон: 123%0AИмя: de%0AСообщение: 123213%0A

警告:fopen(https://api.telegram.org/botMYTOKEN/sendMessage?chat_id=-449128489&parse_mode=html&text=Телефон: 123%0AИмя: de%0AСообщение: 123213%0A): 失败打开流:HTTP 请求失败!第 61 行 C:\nginx\html\scripts\php\send-message-to-telegram.php 中的 HTTP/1.1 400 错误请求 Ошибка。 Сообщение не отправлено!

第 61 行是包含 fopen() 的行。

脚本运行时的请求回显输出:

https://api.telegram.org/botMYTOKEN/sendMessage?chat_id=-449128489&parse_mode=html&text=Телефон: 123123%0AСообщение: 1213123%0A

【问题讨论】:

  • 您的“文本”参数中似乎有一些未编码的字符。您可以尝试在使用请求字符串中的值之前添加$txt = rawurlencode($txt)
  • 另外,是我,还是您的两个输出字符串示例相同?
  • Ty,它解决了我的问题。我使用 urlencode() 来处理俄语字符串。

标签: javascript php telegram


【解决方案1】:

这里的主要问题是您需要将西里尔字符编码为 URL 实体。您可以使用rawurlencode($txt) 做到这一点。请参阅下面的完整代码:

    $arr = array(
      $phoneFieldset => $phone,
      $nameFieldset => $name,
      $messageFieldset => $message,
    );
    foreach($arr as $key => $value) {
      $txt .= "<b>".$key."</b> ".$value."%0A";
    };

    $txt = rawurlencode($txt)  // To encode cyrillic entities

    $request = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}";
    
    echo $request;
    
    $sendToTelegram = fopen($request,"r");

附:取自 @ed-lucas 评论,供其他将搜索答案的人使用。

【讨论】:

    猜你喜欢
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 2017-08-07
    • 2015-04-10
    相关资源
    最近更新 更多