2015-08-30 2 views
4

Команда sendPhoto требует аргумента photo, определяемого как InputFile or String.Telegram BOT Api: как отправить фотографию с помощью PHP?

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

Кудри выполняется, но Телеграмма ответить мне это:

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

Я также попытался заменить @/path... на file_get_contents, но в этом случае Telegram дайте мне пустой ответ (и curl_error пуст!).

Какой способ отправить фотографию в телеграмму с помощью php + curl?

ответ

22

Это мое рабочее решение, но оно требует 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); 
+0

Работал для меня отлично !! Легко и элегантно! спасибо – azerafati

+0

@CeceXX: почему вы отредактировали мой ответ? – realtebo

+0

@realtebo Я удалил пух. Откат, если вы считаете, что мое редактирование не имеет значения. – Cesare

1

Вы можете использовать этот API: https://github.com/mgp25/Telegram-Bot-API

пример:

$tg->sendPhoto($chat_id, $image, $caption); 

Вы можете использовать либо хранимая изображения или URL.

+0

привет, почему, когда я использовал этот код, вы увидите следующее: file_get_contents (https://api.telegram.org/bot266009680:AAEvufrOSAdLIxoXKtfgcfgfc/sendPhoto?chat_id=2189411828&photo=maldini.jpg): не удалось открыть поток: запрос HTTP не выполнен ! HTTP/1.1 400 Bad Request в C: \ xampp \ htdocs \ mgp25 \ Telegram-Bot-API-master \ src \ Telegram.php в строке 466 –

2

Я искал много онлайн, но не нашел ответа. Но ваш вопрос решить мою проблему ... Я просто изменил код, и что ответил мне ... я изменил код так:

$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; 
4

Этот код помогает мне много, которые я получаю от PHP .net сайт здесь

Визит http://php.net/manual/en/class.curlfile.php#115161 (Голосовать за этот код на веб-сайте PHP).

Я просто изменить заголовки в этом коде для телеграмм бота отправить изображение просто скопировать эту функцию

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 здесь является его как: -

$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 функции в соответствии с вашими потребностями.

+0

это работает, но как добавить reply_markup? –

0

Это плохая идея, но вы можете использовать некоторые так:

#!/bin/bash 

set -x 
set -e 

BDIR=/tmp/${RANDOM} 
TG_TOKEN="" 
TG_CHAT_ID= 

mkdir -p ${BDIR} 
chmod -R 777 ${BDIR} 
su postgres -c "pg_dumpall -f ${BDIR}/postgre.sql" 
tar czf ${BDIR}/${HOSTNAME}.tar.gz /var/lib/grafana/ /etc/grafana/ ${BDIR}/postgre.sql 


curl -F caption="$(date)" -F chat_id="${TG_CHAT_ID}" -F [email protected]"${BDIR}/${HOSTNAME}.tar.gz" https://api.telegram.org/bot${TG_TOKEN}/sendDocument 

rm -rf ${DBIR}