首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Telegram机器人Api:如何使用PHP发送照片?

Telegram机器人Api:如何使用PHP发送照片?
EN

Stack Overflow用户
提问于 2015-08-30 19:53:46
回答 7查看 54.1K关注 0票数 9

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

API文档告诉我们:

代码语言:javascript
运行
复制
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.

代码语言:javascript
运行
复制
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. 

所以我尝试了这个方法

代码语言:javascript
运行
复制
    $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);

curls被执行,但Telegram回复我:

代码语言:javascript
运行
复制
Error: Bad Request: Wrong persistent file_id specified: contains wrong
characters or have wrong length

我也尝试过用file_get_contents替换@/path...,但在本例中Telegram给了我一个空的回复( curl_error也是空的!)。

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

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2015-08-30 20:03:35

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

代码语言:javascript
运行
复制
$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);
票数 34
EN

Stack Overflow用户

发布于 2015-09-29 20:34:28

这段代码对我帮助很大,这些代码是从php.net网站上获得的,这里是

访问http://php.net/manual/en/class.curlfile.php#115161 (在php网站上投票支持这段代码)。

我只需在此代码中更改报头,让电报机器人发送图像,只需复制此函数

代码语言:javascript
运行
复制
function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {

          // invalid characters for "name" and "filename"
          static $disallow = array("\0", "\"", "\r", "\n");

          // build normal parameters
          foreach ($assoc as $k => $v) {
              $k = str_replace($disallow, "_", $k);
              $body[] = implode("\r\n", array(
                  "Content-Disposition: form-data; name=\"{$k}\"",
                  "",
                  filter_var($v),
              ));
          }

          // build file parameters
          foreach ($files as $k => $v) {
              switch (true) {
                  case false === $v = realpath(filter_var($v)):
                  case !is_file($v):
                  case !is_readable($v):
                      continue; // or return false, throw new InvalidArgumentException
              }
              $data = file_get_contents($v);
              $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
              $k = str_replace($disallow, "_", $k);
              $v = str_replace($disallow, "_", $v);
              $body[] = implode("\r\n", array(
                  "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
                  "Content-Type: image/jpeg",
                  "",
                  $data,
              ));
          }

          // generate safe boundary
          do {
              $boundary = "---------------------" . md5(mt_rand() . microtime());
          } while (preg_grep("/{$boundary}/", $body));

          // add boundary for each parameters
          array_walk($body, function (&$part) use ($boundary) {
              $part = "--{$boundary}\r\n{$part}";
          });

          // add final boundary
          $body[] = "--{$boundary}--";
          $body[] = "";

          // set options
          return @curl_setopt_array($ch, array(
              CURLOPT_POST       => true,
              CURLOPT_POSTFIELDS => implode("\r\n", $body),
              CURLOPT_HTTPHEADER => array(
                  "Expect: 100-continue",
                  "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
              ),
          ));
      }

Basic Try:现在只需通过发送带有路径和聊天id的照片名称来使用此代码,这是如何实现的:-

代码语言:javascript
运行
复制
$array1=array('chat_id'=><here_chat_id>);
$array2=array('photo'=>'index.jpg') //path
$ch = curl_init();       
curl_setopt($ch, CURLOPT_URL,"https://api.telegram.org/<bot_token>/sendPhoto");
curl_custom_postfields($ch,$array1,$array2);//above custom function
$output=curl_exec($ch);
close($ch);

用于发送png或其他方法的根据需要更改curl_custom函数。

票数 4
EN

Stack Overflow用户

发布于 2015-09-08 20:00:29

我在网上找了很多,但没有找到答案。但是,你的问题解决了我的问题。我刚刚修改了你的代码,这为我解答了这个问题...我将您的代码更改为:

代码语言:javascript
运行
复制
$chat_id=chat Id Here;

$bot_url    = "https://api.telegram.org/botYOUR_BOT_TOKEN/";
$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("path/to/image.png"));
$output = curl_exec($ch);
print$output;
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32296272

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档