in function input $files = $_FILES
Don't get what Telegram wants from me.
It says: "{"ok":false,"error_code":400,"description":"Bad Request: group send failed"}". HIELPLEAS!
function sendMediaGroup($files)
{
$url = "https://api.telegram.org/bot" . $this->token . "/" . __FUNCTION__;
$media = [];
$ch = curl_init();
$type = "photo";
$caption = "";
foreach ($files as $file)
{
$media[] = [
'type' => $type,
'media' => $file['tmp_name'],
'caption' => $caption
];
}
$disable_notification = false;
$reply_to_message_id = null;
$parameters = [
'chat_id' => $this->chat_id,
'media' => json_encode($media),
'disable_notification' => $disable_notification,
'reply_to_message_id' => $reply_to_message_id,
];
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, $parameters);
return $output = curl_exec($ch);
}
In order for Telegram to create a media group from photo URL in the Internet, a file link you pass as media attribute value must be accessible by Telegram's servers. Sometimes it is not the case and sendMediaGroup API call fails with the cryptic error message Bad Request: group send failed. In this case you can try another approach to send photos, e.g. in text field using sendMessage method or go to #webpagebot and send him a link to your file - this will update preview for the link and you will be able to send that link inside of the media group.
Note to moderators: this answer does not 100% targets original question, but link to this question pops up in first ten while searching using words from the caption.
You should name your files and attach files to the request according their name. So change your code like this:
function sendMediaGroup($files)
{
$url = "https://api.telegram.org/bot" . $this->token . "/" . __FUNCTION__;
$media = [];
$ch = curl_init();
$type = "photo";
$caption = "";
$parameters = array();
foreach ($files as $file)
{
$media[] = [
'type' => $type,
'media' => "attach://" . $file['tmp_name'],
'caption' => $caption
];
$parameters[] = [
$file['tmp_name'] => $file
];
}
$disable_notification = false;
$reply_to_message_id = null;
$parameters[] = [
'chat_id' => $this->chat_id,
'media' => json_encode($media),
'disable_notification' => $disable_notification,
'reply_to_message_id' => $reply_to_message_id,
];
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, $parameters);
return $output = curl_exec($ch);
}
If you are setting URL for media, you URL should work on :80 or :443 port. For example: https:examplesite.com/image1.jpg is OK, https:examplesite.com:8443/image1.jpg is not OK!
Related
I need your help to get a smartsheet as excel and put it to cloudinary in PHP.
I use the code bellow.
/**
* #param $sheetId
*/
public function getSheetAsExcel($sheetId)
{
$url = self::SMART_SHEET_BASE_URL . '/sheets/' . $sheetId;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = 'Authorization: Bearer ' . $this->smartsheetCredentials;
$headers[] = 'Accept: application/vnd.ms-excel';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
return $result;
}
A file is created in cloudinary but when I donwload it, I have a wrong format.
screenshot of the message shown
$outStream = $this->smartsheetClient->getSheetAsExcel($smart_sheet_id);
$file_name = 'filename.xlsx';
$cloudinarySignature = (new CloudinayClient())->getCloudinarySignature();
$temp = tmpfile();
$path = stream_get_meta_data($temp)['uri'];
fwrite($temp, file_put_contents($path, $outStream));
fseek($temp, 0);
$cloudinaryResponse = \Cloudinary\Uploader::upload($path, [
"public_id" => $file_name,
"resource_type" => "auto",
"signature" => $cloudinarySignature,
"version" => time()
]);
fclose($temp);
I updated my code with following. The problem was probably the tmpfile().
$file = $this->smartsheetClient->getSheetAsExcel($smart_sheet_id);
$file_name = 'filename.xlsx';
$cloudinarySignature = (new CloudinayClient())->getCloudinarySignature();
$path = self::TMP_FOLDER ."/$file_name";
file_put_contents($path, $file);
$cloudinaryResponse = \Cloudinary\Uploader::upload($path, [
"public_id" => $file_name,
"resource_type" => "auto",
"signature" => $cloudinarySignature,
"version" => time()
]);
unlink($path);
when user allow permission & script start processing every data is shown perfectly but i get error
PHP Notice: Undefined index: gd$email in
here is my php code
if (!empty($contacts['feed']['entry']))
{
foreach($contacts['feed']['entry'] as $contact)
{
// retrieve user photo
if (isset($contact['link'][0]['href']))
{
$url = $contact['link'][0]['href'];
$url = $url . '&access_token=' . urlencode($accesstoken);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$image = curl_exec($curl);
curl_close($curl);
}
if ($image === 'Photo not found')
{
// retrieve Name and email address
$return[] = array(
'name' => $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
'img_url' => '//cdn.twkcdn.com/profile/image/avatar.png?w=40&h=40&cf',
);
}
else
{
// retrieve Name and email address
$return[] = array(
'name' => $contact['title']['$t'],
'email' => $contact['gd$email'][0]['address'],
'img_url' => $url,
);
}
}
$google_contacts = $return; //returning all d
}
This is just example of half script & i don't know why fetching contacts from google take about 15 to 20 seconds everytime i visit this page
Google doesn't check that all entry has email address.
Add that immediatly after Foreach :
if (!array_key_exists('gd$email', $contact)){
continue;
}
I have a problem with sendAudio() function in php telegram bot.
if (strtoupper($text) == "MUSIC") {
$voice = curl_file_create('audio.ogg');
$content = array('chat_id' => $chat_id, 'audio' => $voice);
$telegram->sendAudio($content);
}
This don't work with an audio lenghtof 9 or more seconds. I also tried with .mp3 but nothing. Same function with an audio lenght of 6 or less seconds works. I looked in the documentation and it says only 50MB files are restricted. Help pls.
Here's my $telegram.
include("Telegram.php");
$bot_id = "xxxxxxx:yyyyyyyy_mytoken";
$telegram = new Telegram($bot_id);
And here Telegram.php:
class Telegram {
private $bot_id = "mytoken";
private $data = array();
private $updates = array();
public function __construct($bot_id) {
$this->bot_id = $bot_id;
$this->data = $this->getData();
}
public function endpoint($api, array $content, $post = true) {
$url = 'https://api.telegram.org/bot' . $this->bot_id . '/' . $api;
if ($post)
$reply = $this->sendAPIRequest($url, $content);
else
$reply = $this->sendAPIRequest($url, array(), false);
return json_decode($reply, true);
}
public function sendAudio(array $content) {
return $this->endpoint("sendAudio", $content);
}
I am using this code to send mp3 audio file to telegram from my php application and It's working fine for me.
$BOT_TOKEN = 'yourBotToken';
$chat_id = '#yourChannel';
$filePath = 'your/path/file';
define('BOTAPI', 'https://api.telegram.org/bot' . $BOT_TOKEN . '/');
$cfile = new CURLFile(realpath($filePath));
$data = [
'chat_id' => $chat_id,
'audio' => $cfile,
'caption' => $message
];
$ch = curl_init(BOTAPI . 'sendAudio');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_exec($ch);
curl_close($ch);
Have you tried to use sendVoice for ogg file instead of sendAudio?
Next code did work for me well:
<?php
exec( "curl -i -F 'chat_id=1234567890' -F 'voice=#audio.ogg' 'https://api.telegram.org/bot1234567890:AABBCCDDEEFFGGHH/sendVoice' 2>&1", $output , $return );
print_r( json_decode( end( $output ) ) );
you can use this code to send your audio file
function sendmessage($url, $post_params) {
$cu = curl_init();
curl_setopt($cu, CURLOPT_URL, $url);
curl_setopt($cu, CURLOPT_POSTFIELDS, $post_params);
curl_setopt($cu, CURLOPT_RETURNTRANSFER, true); //get result
$result = curl_exec($cu);
curl_close($cu);
return $result;
}
$telsite = "https://api.telegram.org/bot"."$your_token_id";
$sendAudio_url = $telsite."sendAudio";
$post_parameters = array('chat_id' => $chat_user_id , 'audio' => $dir_of_audio);
sendmessage($sendAudio_url , $post_parameters);
Example using westacks/telebot library:
<?php
use WeStacks\TeleBot\TeleBot;
require 'vendor/autoload.php';
$bot = new TeleBot('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11');
$bot->sendAudio([
'chat_id' => 1111111111,
'audio' => 'https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3'
]);
$bot->sendAudio([
'chat_id' => 1111111111,
'audio' => './path/to/local/file.mp3'
]);
I'm using PHP to config a webhook for a BOT.
I'd like to send picture from another server.
I've tried this way
function bot1($chatID,$sentText) {
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$this->sendPhoto($botUrl,$chatID,$img);
}
function sendPhoto($botUrl,$chatID, $img){
$this->sendMessage($botUrl,$chatID,'This is the pic'.$chatID);
$this->sendPost($botUrl,"sendPhoto",$chatID,"photo",$img);
}
function sendMessage($botUrl,$chatID, $text){
$inserimento = file_get_contents($botUrl."/sendMessage?chat_id=".$chatID."&text=".$text."&reply_markup=".json_encode(array("hide_keyboard"=>true)));
}
function sendPost($botUrl,$function,$chatID,$type,$doc){
$response = $botUrl. "/".$function;
$post_fields = array('chat_id' => $chatID,
$type => new CURLFile(realpath($doc))
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $response);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);
}
But I receive only the message.
What is the problem?
I've tried to change in http but the problem persists
Well, I've done a workaround because my cUrl version seems to have a bug in uploading file.
Now I use Zend FW
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$realpath = realpath($doc);
$url = $botUrl . "/sendPhoto?chat_id=" . $chatID;
$client = new Zend_Http_Client();
$client->setUri($url);
$client->setFileUpload($realpath, "photo");
$client->setMethod('POST');
$response = $client->request();
You have to send a file, not a URL.
So:
function bot1( $chatID,$sentText )
{
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$data = file_get_contents( $img ); # <---
$filePath = "/Your/Local/FilePath/Here"; # <---
file_put_contents( $data, $filePath ); # <---
$this->sendPhoto( $botUrl, $chatID, $filePath ); # <---
}
This is as raw example, without checking success of file_get_contents().
In my bot I use this schema, and it works fine.
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 ?
This is my working solution, but it requires 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);
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
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:Now just use this code by sending photo name with path and chat id
here is it how:-
$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);
For sending png or other methods change curl_custom function according to your need.
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:
$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;
You can use this API: https://github.com/mgp25/Telegram-Bot-API
example:
$tg->sendPhoto($chat_id, $image, $caption);
You can use either a stored image or URL.
<?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);
?>
This a bad idea, but you can use some like that:
#!/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}
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.
$bot_url = "https://api.telegram.org/bot<bot_id>/";
$url = $bot_url . "sendPhoto?chat_id=" . $chat_id ;
$caption = 'Telegram Image SendPhoto function';
$img = '/path/to/save_image.png'; //local path where image should be saved
/* Get the image from the URL and save to your own path. You need to add
allow_url_fopen=On to your php.ini file for the below code to work */
file_put_contents($img, file_get_contents("https://your_image.com/pic.jpg"));
$post_fields = array('chat_id' => $chat_id,
'photo' => new CURLFile(realpath($img)),
'caption' => $caption
);
$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);
curl_close($ch); //close curl
That's all!