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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32296272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:53:34  来源:igfitidea点击:

Telegram BOT Api: how to send a photo using PHP?

phpcurltelegramtelegram-bot

提问by realtebo

The sendPhotocommand require an argument photodefined as InputFile or String.

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

The API doc tells:

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.

And

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. 

So I tried this method

所以我尝试了这个方法

    $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:

卷发已执行,但 Telegram 回复我:

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

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

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

What the way to send a photo to telegram using php + curl ?

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

回答by realtebo

This is my working solution, but it requires PHP 5.5:

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

回答by Ars

This code helps me alot which I get from php.net website here

这段代码对我有很大帮助,我从 php.net 网站获得了这里

Visit http://php.net/manual/en/class.curlfile.php#115161(Vote Up this code in php website).

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

I just change headers in this code for telegram bot to send image just copy this function

我只是更改此代码中的标题,以便电报机器人发送图像只需复制此功能

function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {

          // invalid characters for "name" and "filename"
          static $disallow = array("
$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);
", "\"", "\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:Now just use this code by sending photo name with path and chat id here is it how:-

基本尝试:现在只需通过发送带有路径和聊天 ID 的照片名称来使用此代码,方法如下:-

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

For sending png or other methods change curl_custom function according to your need.

对于发送 png 或其他方法,请根据需要更改 curl_custom 函数。

回答by Amir Pakdel

I searched a lot online but didn't find the answer. But, your question solved my problem ... I just changed your code and that answered it for me ... I changed your code to this:

我在网上搜索了很多,但没有找到答案。但是,你的问题解决了我的问题......我只是改变了你的代码并为我回答了......我将你的代码改为:

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

回答by jedi

You can use this API: https://github.com/mgp25/Telegram-Bot-API

你可以使用这个 API:https: //github.com/mgp25/Telegram-Bot-API

example:

例子:

<?php

$BASH_Command='curl -s -X POST "https://api.telegram.org/bot<YourToken>/sendPhoto?chat_id=<YourID>" -F photo="@/path/to/imagefile.jpeg" -F caption="TheImage" > /dev/null &';

echo exec($BASH_Command);
?>

You can use either a stored image or URL.

您可以使用存储的图像或 URL。

回答by CMP

#!/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 document=@"${BDIR}/${HOSTNAME}.tar.gz" https://api.telegram.org/bot${TG_TOKEN}/sendDocument

rm -rf ${DBIR}

回答by Neg

This a bad idea, but you can use some like that:

这是一个坏主意,但您可以使用类似的方法:

##代码##