gpt4 book ai didi

php - Telegram Bot API : how to send a photo using PHP?

转载 作者:可可西里 更新时间:2023-11-01 12:40:29 29 4
gpt4 key购买 nike

sendPhoto命令需要定义为 InputFile 或 String 的参数 photo

API 文档告诉我们:

Photo to send. You can either pass a file_id as String to resend a photo
that is already on the Telegram servers, or upload a new photo using
multipart/form-data.

InputFile

This object represents the contents of a file to be uploaded. Must be
posted using multipart/form-data in the usual way that files are
uploaded via the browser.

于是我尝试了这个方法

    $bot_url    = "https://api.telegram.org/bot<bot_id>/";
$url = $bot_url . "sendPhoto?chat_id=" . $chat_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"photo" => "@/path/to/image.png",
));
curl_setopt($ch, CURLOPT_INFILESIZE, filesize("/root/dev/fe_new.png"));
$output = curl_exec($ch);

卷发已执行,但 Telegram 回复我:

Error: Bad Request: Wrong persistent file_id specified: contains wrong
characters or have wrong length

我还尝试用 file_get_contents 替换 @/path...,但在这种情况下,Telegram 给我一个空回复(和 curl_error 是空的!)。

使用 php + curl 将照片发送到 Telegram 的方法是什么?

最佳答案

这是我的工作解决方案,但它需要 PHP 5.5:

$bot_url    = "https://api.telegram.org/bot<bot_id>/";
$url = $bot_url . "sendPhoto?chat_id=" . $chat_id ;

$post_fields = array('chat_id' => $chat_id,
'photo' => new CURLFile(realpath("/path/to/image.png"))
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);

关于php - Telegram Bot API : how to send a photo using PHP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32296272/

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