gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:55:16 25 4
gpt4 key购买 nike

我有一个 Telegram 机器人,其 Webhook 设置在第三方托管服务器上。我可以使用任何 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 是我用于调试的函数,因为我无法在 webhook 的 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,但没有成功。 ...这似乎比他需要的更难,考虑到我可以很容易地做到locally on my machine .

最佳答案

  • 无需设置内容标题

To send a local file ,创建一个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);

enter image description here

关于php - Telegram Bot sendDocument(托管服务器上的 php),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66244747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com