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

Dom*_*ica 2 php post curl file-upload telegram-bot

我有一个 Telegram 机器人,在第三方托管服务器上设置了 webhook。我可以使用任何URL 查询字符串,并且它们工作得很好。

现在我试图让我的机器人发送一个文本文件。如果我理解正确,我需要使用 发出 POST 请求multipart/form-data,并且我正在努力使其在托管服务器上工作。

$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);
Run Code Online (Sandbox Code Playgroud)

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

显然我没有收到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"}
Run Code Online (Sandbox Code Playgroud)

我也没有成功地尝试制作一个CURLFile ...这似乎比他需要的更难,考虑到我可以在我的机器上本地轻松地完成它。

0st*_*ne0 5

  • 无需设置内容标题

要发送本地文件,请创建一个文件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);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述