电报BOT Api:如何使用PHP发送照片?

rea*_*ebo 7 php curl telegram telegram-bot

所述sendPhoto命令需要一个参数photo定义为InputFile or String.

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

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

所以我尝试了这种方法

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

卷发被执行,但电报回复给我:

Error: Bad Request: Wrong persistent file_id specified: contains wrong
characters or have wrong length
Run Code Online (Sandbox Code Playgroud)

我也尝试用@/path...a 代替file_get_contents,但在这种情况下,Telegram给我一个空的回复(并且curl_error是空的!).

使用php + curl将照片发送到电报的方式是什么?

rea*_*ebo 29

这是我的工作解决方案,但它需要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);
Run Code Online (Sandbox Code Playgroud)

  • 嘿! 完美的工作.快速提问:有没有办法从您自己的服务器旁边的URL发送图片? (3认同)