Sending voice to Telegram through PHP app - php-telegram-bot

Here is the situation.
I have an Android app, which can send voice file with HTTP POST anywhere I specify. Also I would like to download these voice files to Telegram bot automatically. I wrote a PHP bot and I can accept and translate to Telegram any fields that come in said POST. One thing I miss is the file itself.
I don't know how to "say" to telegram API I download a file.
So what do I have: present file in $_FILE stream (I can read the name of it), I throw it in sendVoice function as $voice, also I do know I have to use simple multipart/form-data POST method to send file.
My question is: is it possible to use something but CURL to POST right from PHP? If not, what am I missing then? Other methods I use are messages and photo sending via file_get_contents(), I wonder if it's still suitable for voice file?
Here is the code I have now, which I found somewhere (I have 0 cURL knowledge):
function sendVoice($chat_id, $voice, $caption) {
$boundary = uniqid();
$delimiter = '-------------' . $boundary;
$fields = array(
"chat_id" => $chat_id,
"caption" => $caption
);
$post_data = build_data_files($boundary, $fields, $voice);
$ch = curl_init($GLOBALS['api'].'/sendVoice');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
//"Authorization: Bearer $TOKEN",
"Content-Type: multipart/form-data; boundary=" . $delimiter,
"Content-Length: " . strlen($post_data))
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_exec($ch);
curl_close($ch);
}
function build_data_files($boundary, $fields, $files){
$data = '';
$eol = "\r\n";
$delimiter = '-------------' . $boundary;
foreach ($fields as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . "\"".$eol.$eol
. $content . $eol;
}
foreach ($files as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $name . '"' . $eol
//. 'Content-Type: image/png'.$eol
. 'Content-Transfer-Encoding: binary'.$eol
;
$data .= $eol;
$data .= $content . $eol;
}
$data .= "--" . $delimiter . "--".$eol;
return $data;
}

This was actally much easier. Since we have file present in $_FILES, we can do all of the cURL in just sendVoice() function without any hassle of rebinding boundaries or specifying content types.
Here is the final code which worked for me:
function sendVoice($chat_id, $voice, $caption) {
$filepath = realpath($_FILES['file']['tmp_name']);
$post_data = array(
'chat_id' => $chat_id,
'voice' => new CURLFile($filepath),
'caption' => $caption
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GLOBALS['api'].'/sendVoice');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_exec($ch);
curl_close($ch);
}
That will download an .OGG file as voice message (because I do not want any files to appear in my music player). Later it is possible to just add more fields such as duration in $post_data array and Telegram would eat them accordingly.

Related

push notification not working on ios 9 devices

Ever since iOS 9.0 - 9.2 was implemented users of my app that are using it no longer receive push notifications.
My code works fine when sending to Android devices as I am separating the two platforms (iOS and Android) into 2 different arrays and processing them accordingly.
The result from the APNs server does not return an error at all.
Are there known issues documented on what could have changed on the push notification server? If so please provide links to them.
Below is the code that i am using to send the push notifications(PHP):
public function send_notification($message) {
$title = 'My App';
$platform = '';
$users = mysql_query("select * FROM push_devices");
$no_of_users = mysql_num_rows($users);
// Initialize the array for storing the platform specific tokens
$iOSusers = array();
$androidUsers = array();
if($no_of_users > 0){
// Seperate the tokens
while ($row = mysql_fetch_array($users)) {
$platform = $row['platform'];
if($platform == 'Android' || $platform == 'android'){
// Add to android list
$androidUsers[] = $row['push_id'];
}
if($platform == 'iOS' || $platform == 'ios'){
$iOSusers[] = $row['push_id'];
}
}// endwhile
}
if(!empty($androidUsers)){
$messageAndTitle = array(
'message' => $message,
'title' => $title
);
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $androidUsers,
'data' => $messageAndTitle,
);
$headers = array(
'Authorization: key=' . ***GOOGLE_API_KEY***,
'Content-Type: application/json'
);
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
// Increase the timeout
curl_setopt($ch, CUROPT_CONNECTTIMEOUT, 1000);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
echo $result . '<br/>';
// close the connection
curl_close($ch);
}
// Handle iOS push
if(!empty($iOSusers)){
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', **PUSH_CERT_FILE**);
stream_context_set_option($ctx, 'ssl', 'passphrase', **PUSH_PARAPHRASE**);
// Open a connection to the APNS server
$fp = stream_socket_client(
PUSH_SERVER, $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
//echo 'Connected to APNS' . PHP_EOL;
$badgeCount = 2;
$badge = (int)$badge;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'badge' => $badge,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
//Note: $deviceToken is an array for android push
foreach ($iOSusers as $token) {
$msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
//echo 'Device token: ' .$deviceToken[0];
if (!$result)
echo 'Message not delivered' . PHP_EOL . $token . '<br/>';
else
echo 'Message successfully delivered' . PHP_EOL . $token . '<br/>';
}
fclose($fp);
} // iOS
}
There are hundreds of thread over the Internet about notifications not working on iOS 9, but I think that the problem is server-side.
I noticed an issue with Push notifications on my iPhone 5 (iOS 7.1.2) in the last couple of weeks, and I discovered that the problem is originating from the Apple Push Notification Server.
I am now receiving about 10% of notifications on Whatsapp and 0% on Facebook Messenger, but I am sure other apps are involved too.
With another app (Bspotted), installed more recently, I'm receiving 100% of notifications.
So I've downloaded the profile PersistentConnectionLogging.mobileconfig in order to enable logging for push notifications.
Turns out that the Apple Push Server is sending notifications with TOKEN (null), so of course the apps can't handle them:
copyTokenForDomain push.apple.com (null)
Moreover, it seems that all notifications I received with token null (on Whatsapp and Messenger) came from Android devices. I received a message on Whatsapp from an iPhone, and it was the first notification I received in two weeks.
Maybe is a coincidence, because now I managed to receive 10% of notifications on Whatsapp also from Android devices (for two weeks it was 0%).
I tried all of this:
Reset in-app notifications
Reset iOS app notifications
Reinstall the app
Reset iOS network configuration
Forced iPhone restart
Uninstall the app, set the date 2 days forward, reinstall the app (in order to force the app to ask for permission on notifications)
I hope this will help.
Best Regards

executing multiple merge neo4j query via php

I was using the neo4j query as below till now but I am wondering if it's making neo4j out of memory as I am not committing anywhere(I guess its auto-commit) .But the query works fine only worried if neo4j will shutdown or slow down due to my query. I really appreciate any help.
sample.php
<?php
if (!empty($array)) {
if( get_magic_quotes_gpc() ) {
$array = stripslashes( $array );
}
$newstr = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $array), true );
if(!empty($newstr)){
$j=0;
foreach($newstr as $item) { //foreach element in $arr
$category_id = $item['category_id']; //etc
$category_name = $item['category_name'];
$category = $item['category'];
$data2 .=' MERGE (u'.$j.':Category {name:"'.$category_name.'",id:"'.$category_id.'",category:"'.$category
.'"}) ';
$j=$j+1;
}
$data2 = array("query" =>$data2);
$data_string = json_encode($data2);
$ch = curl_init('http://localhost:7474/db/data/cypher');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
}else{
echo "null";
}
}
?>
You are using the Legacy Cypher HTTP Endpoint, which automatically commits at the end of a successful query. So, there is no need to worry about losing your data.
However, the legacy endpoint is now deprecated, so you should consider changing over to the Transactional endpoint.
Also, as a suggestion, you can change this snippet:
' MERGE (u'.$j.':Category {name:"'
to:
' MERGE (:Category {name:"'
Your query never uses the uxxx identifiers, so there is no need to define them in the first place.

Can I schedule a Jenkins Build without CRON or REST API?

To schedule a build in Jenkins I need to add a "cron" parameter then all works well. But I have a lot of donkey users and they didn't know how to schedule with cron.
Is there a way to schedule a Jenkins build without the API itself (http://jenkins/job/jobname/build?delay=4000 I don't want this) or cron? Maybe some Jenkins Plugin...
Solved it this way:
<?php
if($_POST) {
$fields = array(
"POST_PARAMETERS" => $_POST['params']
);
$delay = (int) $_POST['delay'];
$username = "my_username";
$password = "my_password";
$token = "MY_JENKINS_TOKEN_NAME";
$job = "JOB_NAME";
$url = "http://jenkins_host/jenkins/job/".$job."/buildWithParameters?token=".$token."&delay=".$delay;
$process = curl_init($url);
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($process, CURLOPT_POST, count($fields));
$return = curl_exec($process);
echo http_build_query($fields);
echo curl_error($process);
curl_close($process);
die;
}
?>
I give the JOB_NAME and the build parameters and it work well. cURL did the trick for me with the authorization token.
Thanks everyone who tried to help.

CURL - no url set

$param = 'get.php';
$url = 'http://mysite.org/'. $param;
$__post = 'option=1&option2=225';
mysite.org/get.php - exists for 100%, when I open them in browser everything works.
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $__post);
$result = curl_exec($c);
curl_close($c);
print_r($result); // show 404 o_O
I test it using sniffer and CURL pass URL :
http://mysite.org
not
http://mysite.org/get.php
when I do somethink like that :
curl_setopt($c, CURLOPT_URL,'http://mysite.org/get.php');
everything works fine... so... please help me :D What I do wrong, certainly it is a small error but I don't see where he is :/

Push Notification in Blackberry

Hi I want to have push notification in blackberry.I have already googled for the answer and got the Push Services Guide.i read this guide .This guide does not give any code information for the client side application.It talks push server sdk and its installation but does not give any idea of how to write client code to have push notification. So is there any sample code that provides the concept of push notification.
thanks
For client side code, refer this link Blackberry push.
Use this as server side code -
<?php
ini_set('display_errors','1');
error_reporting(E_ALL);
// APP ID provided by RIM
$appid = '';
// Password provided by RIM
$password = '';
//Deliver before timestamp
$deliverbefore = gmdate('Y-m-d\TH:i:s\Z', strtotime('+15 minutes'));
//An array of address must be in PIN format or "push_all"
$addresstosendto[] = 'push_all';
$addresses = '';
foreach ($addresstosendto as $value) {
$addresses .= '<address address-value="' . $value . '"/>';
}
// create a new cURL resource
$err = false;
$ch = curl_init();
$messageid = microtime(true);
$data = '--mPsbVQo0a68eIL3OAxnm'. "\r\n" .
'Content-Type: application/xml; charset=UTF-8' . "\r\n\r\n" .
'<?xml version="1.0"?>
<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.1//EN" "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd">
<pap>
<push-message push-id="' . $messageid . '" deliver-before-timestamp="' . $deliverbefore . '" source-reference="' . $appid . '">'
. $addresses .
'<quality-of-service delivery-method="confirmed"/>
</push-message>
</pap>' . "\r\n" .
'--mPsbVQo0a68eIL3OAxnm' . "\r\n" .
'Content-Type: text/plain' . "\r\n" .
'Push-Message-ID: ' . $messageid . "\r\n\r\n" .
stripslashes('This is my message') . "\r\n" .
'--mPsbVQo0a68eIL3OAxnm--' . "\n\r";
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://pushapi.eval.blackberry.com/mss/PD_pushRequest");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT, "Hallgren Networks BB Push Server/1.0");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $appid . ':' . $password);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/related; boundary=mPsbVQo0a68eIL3OAxnm; type=application/xml", "Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", "Connection: keep-alive"));
// grab URL and pass it to the browser
echo $xmldata = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
//Start parsing response into XML data that we can read and output
$p = xml_parser_create();
xml_parse_into_struct($p, $xmldata, $vals);
$errorcode = xml_get_error_code($p);
if ($errorcode > 0) {
echo xml_error_string($errorcode);
$err = true;
}
xml_parser_free($p);
echo 'Our PUSH-ID: ' . $messageid . "<br \>\n";
if (!$err && $vals[1]['tag'] == 'PUSH-RESPONSE') {
echo 'PUSH-ID: ' . $vals[1]['attributes']['PUSH-ID'] . "<br \>\n";
echo 'REPLY-TIME: ' . $vals[1]['attributes']['REPLY-TIME'] . "<br \>\n";
echo 'Response CODE: ' . $vals[2]['attributes']['CODE'] . "<br \>\n";
echo 'Response DESC: ' . $vals[2]['attributes']['DESC'] . "<br \> \n";
} else {
echo '<p>An error has occured</p>' . "\n";
echo 'Error CODE: ' . $vals[1]['attributes']['CODE'] . "<br \>\n";
echo 'Error DESC: ' . $vals[1]['attributes']['DESC'] . "<br \>\n";
}
?>

Resources