php telegram sendAudio - php

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

Related

How can I get a smartsheet as excel file and put it to cloudinary in PHP?

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

group send failed. telegram api bot, sendMediaGroup function

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!

Telegram Send image from external server

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.

Telegram sendDocument api, change Title

I have created a bot, and i want to send file (document) using my bot to my clients, after sending document using following code, title will be full path of my file on my own device ( my pc ), how can I change title to file name only? is that even possible?
Sending code:
protected function perform($method, $params) {
$url = new Url(TELEGRAM_API_URL . $this->bot->tokken . "/" . $method);
$fields = [];
foreach($params as $param => $val)
if($val != NULL && !cnull::is($val) && substr($param, 0, 1) != '_')
$fields[$param] = $val;
#
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url->getUrl());
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:multipart/form-data']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$out = curl_exec($ch);
curl_close($ch);
#
$content = json_decode($out);
return $content;
}
public function sendDocument($chat_id,$_document,$_is_file_id=false,$reply_to_message_id = NULL, $reply_markup = NULL) {
if($_is_file_id)
$document = $_document;
else
$document = new CURLFile(realpath($_document));
return self::perform(__FUNCTION__, get_defined_vars());
}
// ......
$tg->sendDocument(USER_CHAT_ID,"filename.mp4");
This is result:
I've found a solution by using ->setPostFilename() for CURLFile
here it is:
change this method:
public function sendDocument($chat_id,$_document,$_is_file_id=false,$reply_to_message_id = NULL, $reply_markup = NULL) {
if($_is_file_id)
$document = $_document;
else
$document = new CURLFile(realpath($_document));
return self::perform(__FUNCTION__, get_defined_vars());
}
to:
public function sendDocument($chat_id,$_document,$_title=null,$_is_file_id=false,$reply_to_message_id = NULL, $reply_markup = NULL) {
if($_is_file_id)
$document = $_document;
else{
$document = new CURLFile(realpath($_document));
$document->setPostFilename($_title);
}
return self::perform(__FUNCTION__, get_defined_vars());
}
// ......
$tg->sendDocument(USER_CHAT_ID,"filename.mp4","title of file");

Google PageSpeed Insights API not working [PHP]

I'm a beginner in PHP, so maybe someone could help to fix this ?
My web application is showing Google PageInsights API error..
Here's the code, I tried to change version to /v2/, but it still didn't work..
public function getPageSpeed($domain, $api = "")
{
try
{
$callback_url = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?";
$data = array(
'url' => 'http://' . $domain,
'key' => (empty($api) ? $_SESSION['GOOGLEAPI_SERVERKEY'] : $api),
'fields' => 'score,pageStats(htmlResponseBytes,textResponseBytes,cssResponseBytes,imageResponseBytes,javascriptResponseBytes,flashResponseBytes,otherResponseBytes)'
);
$curl_response = $this->curl->get($callback_url . http_build_query($data, '', '&'));
if ($curl_response->headers['Status-Code'] == "200") {
$content = json_decode($curl_response, true);
$response = array(
'status' => 'success',
'data' => array(
'pagespeed_score' => (int)$content['score'],
'pagespeed_stats' => $content['pageStats']
)
);
} else {
$response = array(
'status' => 'error',
'msg' => 'Google API Error. HTTP Code: ' . $curl_response->headers['Status-Code']
);
}
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
<?php
function checkPageSpeed($url){
if (function_exists('file_get_contents')) {
$result = #file_get_contents($url);
}
if ($result == '') {
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
}
return $result;
}
$myKEY = "your_key";
$url = "http://kingsquote.com";
$url_req = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY;
$results = checkPageSpeed($url_req);
echo '<pre>';
print_r(json_decode($results,true));
echo '</pre>';
?>
The code shared by Siren Brown is absolutely correct, except that
while getting the scores we need to send the query parameter &strategy=mobile or &strategy=desktop to get the respective results from Page speed API
$url_mobile = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=mobile';
$url_desktop = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=desktop';

Categories