电报BOT Api:如何使用PHP发送照片? [英] Telegram BOT Api: how to send a photo using PHP?

查看:332
本文介绍了电报BOT Api:如何使用PHP发送照片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sendPhoto 命令需要一个参数照片定义为 InputFile或String

The sendPhoto command require an argument photo defined as 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.

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);

卷曲被执行,但电报将此回复给我:

The curls is executed, but Telegram reply this to me:

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

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

I also tried replacing @/path... with a file_get_contents, but in this case Telegram give me an empty reply (and curl_error is empty !).

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

推荐答案

工作解决方案,但它需要PHP 5.5:

This is my working solution, but it requires 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);

这篇关于电报BOT Api:如何使用PHP发送照片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆