Telegram Bot sendDocument(php 在托管服务器上)

Telegram Bot sendDocument (php on hosted server)

我在第三方托管服务器上设置了带有网络挂接的 Telegram 机器人。 我可以使用任何 URL query string,它们工作正常。

现在我正在尝试制作我的机器人 send a text file。如果我理解正确,我需要使用 multipart/form-data 发出 POST 请求,并且我正在努力使其在托管服务器上运行。

$url = "https://api.telegram.org/bot<myToken>/sendDocument?chat_id=$<myId>";
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$post = array( 'document' => '@'.realpath('data.txt'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

$headers = array();
$headers[] = 'Content-Type: multipart/form-data';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

//DEBUGGING-------------------------------
$info = curl_getinfo($ch);
$buffer = "";
foreach ($info as $key => $value) {
    $buffer .= "$key => $value\n";
}
sendMessage($buffer, $<myId>);
//----------------------------------------

$result = curl_exec($ch);

//DEBUGGING-------------------------------
sendMessage($result, $<myId>);
//----------------------------------------

curl_close($ch);

sendMessage 是我用于调试的函数,因为我无法在 webhooked php 页面上使用 echo

显然我没有收到 data.txt 两条调试消息是:

url => https://api.telegram.org/bot<myToken>/sendDocument?chat_id=$<myId>
content_type => 
http_code => 0
header_size => 0
request_size => 0
filetime => 0
ssl_verify_result => 0
redirect_count => 0
total_time => 0
namelookup_time => 0
connect_time => 0
pretransfer_time => 0
size_upload => 0
size_download => 0
speed_download => 0
speed_upload => 0
download_content_length => -1
upload_content_length => -1
starttransfer_time => 0
redirect_time => 0
redirect_url =>
----------------------------------------------------------------------------
{"ok":false,"error_code":400,"description":"Bad Request: URL host is empty"}

我也试过 CURLFile... It seems harder than he needs to, considerig that I can do it very easily .

但没有成功
  • 无需设置内容headers

To send a local file, create a new CURLFile(),并将其添加到 CURL 请求中;

<?php

    CONST CHAT_ID = '~~';
    CONST BOT = '~~';

    CONST FILENAME = './data.txt';

    // Create CURL object
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot".BOT."/sendDocument?chat_id=" . CHAT_ID);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);

    // Create CURLFile
    $finfo = finfo_file(finfo_open(FILEINFO_MIME_TYPE), FILENAME);
    $cFile = new CURLFile(FILENAME, $finfo);

    // Add CURLFile to CURL request
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        "document" => $cFile
    ]);

    // Call
    $result = curl_exec($ch);

    // Show result and close curl
    var_dump($result);
    curl_close($ch);