I want to send message via telegram api but it's not working, and not send any message. this is what i tried so far:
function sendTelegram($chatID, $msg) {
echo "sending message to " . $chatID . "\n";
$token = "botxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$getUpdate = "http://api.telegram.org/" . $token . "/getUpdates";
$url = "https://api.telegram.org/" . $token . "/sendMessage?chat_id=" . $chatID;
$url = $url . "&text=" . urlencode($msg);
$ch = curl_init();
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $optArray);
$result = curl_exec($ch);
curl_close($ch);
}
$msg = "Hi";
$chatID = "88132232";
sendTelegram($chatID, $msg);
My progress:
I made a new bot via #botfather and got a token.
Then sent a message to this bot with my telegram.
I got chat id in getUpdates.
https://api.telegram.org/botxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/getUpdates
and also send message via:
https://api.telegram.org/botxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/sendMessage?chat_id=88132232&text=hi
It works find when i go to this url but when i want to do this dynamically it give me nothing just echo sending message to 88132232 with no error. I searched and read many topics but no success, any idea what i missed? Before using curl i used get_file_contents but it also not worked.
You set CURLOPT_RETURNTRANSFER
CURLOPT_RETURNTRANSFER: TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
Please return $result in sendTelegram() function, and echo it.
function sendTelegram($chatID, $msg) {
// ...
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = sendTelegram($chatID, $msg);
echo $result; // JSON String
Probably you have error but in curl you should get curl error like this:
if(curl_error($ch)){
echo 'error:' . curl_error($ch);
}
And most problem is SSL. get your error and back. but i tested your code, as #Sean said, your code working fine, try it on php fiddle website. if you get SSL error, read this.
Related
I am using the following code and am not able to display amazon.com using php and curl. Im using curl_error and getting no errors, so I'm not sure what im doing wrong
<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://www.amazon.com');
curl_exec($curl);
curl_close ($curl);
I'm doing this on local host
just display amazon then use this
echo file_get_contents("https://www.amazon.com");
You should use the following:
$response = curl_exec($curl);
$result is an array. You can get for example the body of the request by using:
$header_size = curl_getinfo($curl,CURLINFO_HEADER_SIZE);
$result['header'] = substr($response, 0, $header_size);
$result['body'] = substr( $response, $header_size );
$result['http_code'] = curl_getinfo($curl,CURLINFO_HTTP_CODE);
$result['last_url'] = curl_getinfo($curl,CURLINFO_EFFECTIVE_URL);
echo $result['body'];
For more information: http://php.net/manual/de/function.curl-exec.php
when debugging curl code, use CURLOPT_VERBOSE, and post the CURLOPT_VERBOSE log when asking for help. also when debugging, do not ignore the return values of curl_setopt, because it returns bool(false) if there was an error, and if there was an error, that error would probably explain why the code isn't working. also do not ignore the return value of curl_exec, because it returns bool(false) if there was an error, which goes unnoticed if you ignore the return value (and your code does)
here is a version of your code that doesn't ignore any errors and enable CURLOPT_VERBOSE logging, it should reveal where your code fails:
<?php
$curl = curl_init();
if (! is_resource($curl)) {
throw new \RuntimeException('curl_init() failed!');
}
ecurl_setopt($curl, CURLOPT_URL, 'https://www.amazon.com');
ecurl_setopt($curl, CURLOPT_VERBOSE, 1);
$curlstderr = etmpfile();
$curlstdout = etmpfile();
ecurl_setopt($curl, CURLOPT_STDERR, $curlstderr);
ecurl_setopt($curl, CURLOPT_FILE, $curlstdout);
if (true !== curl_exec($curl)) {
throw new \RuntimeException("curl_exec failed! " . curl_errno($curl) . ": " . curl_error($curl));
}
rewind($curlstderr); // https://bugs.php.net/bug.php?id=76268
rewind($curlstdout); // https://bugs.php.net/bug.php?id=76268
$verbose = stream_get_contents($curlstderr);
$output = stream_get_contents($curlstdout);
curl_close($curl);
fclose($curlstderr);
fclose($curlstdout);
var_dump($verbose, $output);
function ecurl_setopt ( /*resource*/$ch, int $option , /*mixed*/ $value): bool
{
$ret = curl_setopt($ch, $option, $value);
if ($ret !== true) {
// option should be obvious by stack trace
throw new RuntimeException('curl_setopt() failed. curl_errno: ' . return_var_dump(curl_errno($ch)) . '. curl_error: ' . curl_error($ch));
}
return true;
}
function etmpfile()
{
$ret = tmpfile();
if (false === $ret) {
throw new \RuntimeException('tmpfile() failed!');
}
return $ret;
}
also, it appears that https://www.amazon.com has a bug, see is it a bug to send response gzip-compressed to clients that doesn't specify Accept-Encoding: gzip?
in any case, to make curl automatically decompress the gzip-compressed response from amazon, add ecurl_setopt($curl,CURLOPT_ENCODING,''); , that tells libcurl to add the Accept-Encoding: gzip,deflate header, and automatically decompress the result.
I would like to write messenger bot based on this script:
<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
// Set this Verify Token Value on your Facebook App
if ($verify_token === 'testtoken') {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
// Get the Senders Graph ID
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
// Get the returned message
$message = $input['entry'][0]['messaging'][0]['message']['text'];
//API Url and Access Token, generate this token value on your Facebook App Page
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<ACCESS-TOKEN-VALUE>';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text":"The message you want to return"
}
}';
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request but first check if the message is not empty.
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
?>
All works correctly but i receive two responses to variable $message, for example:
Send "Hello";
$message = "Hello";
Receive message: "Hi";
$message = "Hi";
I would like to skip 3 and 4 points and receive only "Hello" message because i have to check if $message is my question or answer. Is it possible?
Greetings
You should skip any read and delivery messages, like this:
if (!empty($input['entry'][0]['messaging'])) {
foreach ($input['entry'][0]['messaging'] as $message) {
// Skipping delivery messages
if (!empty($message['delivery'])) {
continue;
}
// Skipping read messages
if (!empty($message['read'])) {
continue;
}
}
}
Or, you can deselect message_reads & message_deliveries checkboxes in Page Subscription section of your Facebook Page Settings/Webhooks.
I'm trying to set up a fb messenger chatbot but don't seem to be able to get the webhook callback url verified. Every time I try to verify it I get this error message - The URL couldn't be validated. Response does not match challenge, expected value = '1596214014', received=''
Here's the screenshot:
Screenshot
Here's the php I'm using -
<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'token_my_token') {
echo $challenge;
}
I've also tried
echo $_GET['hub_challenge'];
and just
echo file_get_contents('php://input');
All of these result in the same error message as above. Basically, as far as I can tell facebook isn't sending a GET request to my server or if it is it doesn't include any data. Can anyone tell if I am doing something wrong or if there is a setting I need to change to ensure facebook is sending the data correctly?
Edit - When checking the access logs this is what I find, which looks like facebook isn't sending any data in the get request.
2a03:2880:1010:dffb:face:b00c:0:8000 - - [19/Apr/2016:20:50:06 +0000] "GET /wp-content/plugins/applications/fbmessenger.php HTTP/1.0" 200 - "-" "facebookplatform/1.0 (+http://developers.facebook.com)
Thanks
just try my code and it's gonna work.
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'Your's app token') {
echo $challenge;
}
//Token of app
$row = "Token";
$input = json_decode(file_get_contents('php://input'), true);
//Receive user
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
//User's message
$message = $input['entry'][0]['messaging'][0]['message']['text'];
//Where the bot will send message
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$row;
$ch = curl_init($url);
//Answer to the message adds 1
if($message)
{
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message. ' 1' .'"
}
}';
};
$json_enc = $jsonData;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_enc);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
you have to return Challenges so Facebook can verify its correct Url and Token Match
<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'token_my_token') {
echo $challenge;
}
Facebook Docs Link ( In Node.js ) You can see challenge return after verifying the token
https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup
Could you try my API? https://github.com/Fritak/messenger-platform
If you set it like in example, it should work:
// This is just an example, this method of getting request is not safe!
$stream = file_get_contents("php://input");
$request = empty($stream)? $_REQUEST : $stream;
$bot = new \fritak\MessengerPlatform(
['accessToken' => 'token_for_app',
'webhookToken' => 'my_secret_token',
'facebookApiUrl' => 'https://graph.facebook.com/v2.6/me/' //2.6 is minimum
], $request);
if($bot->checkSubscribe())
{
print $bot->request->getChallenge();
exit;
}
If not, problem is somewhere between Facebook and script, not in PHP itself. Go check apache settings etc.
Well issue might be on facebook side, they had some issues over past few days...
Have only this code in your php file: (fbmessenger.php)
<?php
// header('HTTP/1.1 200 OK');
/* GET ALL VARIABLES GET & POST */
foreach ($_REQUEST AS $key => $value){
$message .= "$key => $value ($_SERVER[REQUEST_METHOD])\n";
}
$input = file_get_contents("php://input");
$array = print_r(json_decode($input, true), true);
file_put_contents('fbmessenger.txt', $message.$array."\nREQUEST_METHOD: $_SERVER[REQUEST_METHOD]\n----- Request Date: ".date("d.m.Y H:i:s")." IP: $_SERVER[REMOTE_ADDR] -----\n\n", FILE_APPEND);
echo $_REQUEST['hub_challenge'];
You will have requests saved in a file called "fbmessenger.txt" in the same directory.
Note that for some strange reason you may need to submit few times to
get it approved & saved! (I had to hit "save" 8-9 times before fb
approved link)
Make sure you use https (SSL) connection and once your connection is done, verify your token with "hub_verify_token" to make sure request is coming from fb.
Hi there i am having a strange problem with downloading a remote file. I am using Flurry Data API to download some Reports. Thing is when first time we call the Flurry API it gives us XML/JSON response which contains the path of the Report for Download. It takes like 2 minutes for the report to get ready. I am having Problem with that thing. I wrote a Script which download the remote file if i just paste the link of Report directly to function which is already ready to download. It works like a charm but i have to automate the process of Downloading. So for that i First call the API and get the Report Download Link then i use sleep() function of PHP to stop execution for like 3 Minutes(Tried it with 2 also). Then i call the same function which i uses to download the report successfully doesn't work this time. Here is the File Download Method:
function get_file_and_save($file, $local_path, $newfilename) {
$err_msg = '';
$out = fopen($local_path . $newfilename . ".gz", 'wb');
if ($out == FALSE) {
print "File is not available<br>";
exit;
}
$ch = curl_init();
$headers = array('Content-type: application/x-gzip', 'Connection: Close');
curl_setopt($ch, CURLOPT_FILE, $out);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_exec($ch);
echo "<br>Error Occured:" . curl_error($ch);
curl_close($ch);
}
i also have tried giving the CURLOPT_TIMEOUT but it wasn't working either.
The code to Request to the Flurry note that download_path is working properly it just get the report link:
$query_url = 'http://api.flurry.com/rawData/Events?apiAccessCode=' . $ACCESS_CODE . '&apiKey=' . $API_KEY . '&startTime=' . $start_time . '&endTime=' . $end_time;
$response = download_path($query_url);
if ($response) {
$response_obj = json_decode($response, true);
if (isset($response_obj['report']['#reportUri'])) {
$report_link = $response_obj['report']['#reportUri'];
}
if (isset($response_obj['report']['#reportId'])) {
$report_id = $response_obj['report']['#reportId'];
}
if(isset($report_link) && !empty($report_link)){
echo "<br >Report Link: ".$report_link."<br >";
sleep(240);
$config = array(
'http' => array(
'header' => 'Accept: application/json',
'method' => 'GET'
)
);
$stream = stream_context_create($config);
$json= file_get_contents($report_link,false,$stream);
echo "<pre>";
print_r($http_response_header);
echo "</pre>";
if($http_response_header[3] == "Content-Type: application/octet-stream"){
get_file_and_save($report_link, "data-files/gz/", $current_time);
}
}
else{
echo "There was some error in downloading report";
}
} else {
$error = true;
echo "There was some error in genrating report";
}
is there something problem with sleep() or what i am stuck its been 2nd night i am unable to achieve it.
Check if your PHP script is timing out and being killed off. Both the webserver and PHP have max execution limits to prevent runaway scripts, and if your sleep surpasses that limit, it'll never continue beyond that.
http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time
http://php-fpm.org/wiki/Configuration_File - request_terminate_timeout
http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_read_timeout
http://httpd.apache.org/docs/2.0/mod/core.html#timeout
Am using Curl to send sms using a gateway , a, getting 200 when everything is ok and 400 if its not send now , i should get other things from the gateway such as phone number and other information , so am i missing something ?
// if the Form is submited
//if (isset($_POST['PhoneNumber'])) {
if ($_SERVER['REQUEST_METHOD'] == "POST"){
// Fetch Phone Number and escape it for security
$Phone = mysql_real_escape_string($_POST['PhoneNumber']);
// Fetch Text and escape it for security
$Text = mysql_real_escape_string($_POST['Text']);
// Structure the URl
$url = "http://xxxxxxxxxxx:xxxx?PhoneNumber=".urlencode($Phone)."&Text=".urlencode($Text)."&User=xxx&Password=xxx";
// Handeling the Curl
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($httpCode=="200"){
// if everything is okey , the gateway returns 200 which means OK
echo "Massage Was Sent , Thank you ";
} elseif ($httpCode=="400"){
// if there was an error , the form returns a 400 which means that the sms Failed
echo "Massage was not sent , Please Try Again";
}
// Cloase the Curl Connection
curl_close($handle);
Thank you Best regards,
$response should contain the response, try:
echo '<pre>';
print_r($response);
echo '</pre>';
to show its content