加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 13:19:16 所属栏目:PHP教程 来源:网络整理
导读:sendPhoto命令需要一个定义为InputFile或String的参数照片. API文档告诉: Photo to send. You can either pass a file_id as String to resend a photothat is already on the Telegram servers,or upload a new photo usingmultipart/form-data. 和 InputF
sendPhoto命令需要一个定义为InputFile或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);

卷发被执行,但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将照片发送到电报的方式是什么?

这是我的工作解决方案,但它需要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,array(
    "Content-Type:multipart/form-data"
));
curl_setopt($ch,$url); 
curl_setopt($ch,1); 
curl_setopt($ch,$post_fields); 
$output = curl_exec($ch);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读