The sendPhoto command require an argument photo
defined as InputFile or String
.
The API doc tells:
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:
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_error
is empty !).
What the way to send a photo to telegram using php + curl ?
7
Answers
This is my working solution, but it requires PHP 5.5:
You can use this API: https://github.com/mgp25/Telegram-Bot-API
example:
You can use either a stored image or URL.
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:
This code helps me alot which I get from php.net website here
Visit http://php.net/manual/en/class.curlfile.php#115161
(Vote Up this code in php website).
I just change headers in this code for telegram bot to send image just copy this function
Basic Try:Now just use this code by sending photo name with path and chat id
here is it how:-
For sending png or other methods change curl_custom function according to your need.
This a bad idea, but you can use some like that:
I thought I should extend the answer to include uploading from an external url but it still involves a process of saving the image to a folder first. Then I added a caption to the image.
That’s all!