Facebook messenger bot - receives single and very first message - facebook

Facebook messenger bot - receives single and very first message continuously at every 2 minutes.
I have created bot in PHP and set webhook. But I am receiving webhook trigger at every two minutes no matter I have added/received new message or not.
One more thing is that we are receiving only very first messages. There are so many new messages after that message but we are receiving single message only.
Where am I incorrect? I have followed this article :
http://blog.adnansiddiqi.me/develop-your-first-facebook-messenger-bot-in-php/

We got the solution:
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = isset($input['entry'][0]['messaging'][0]['message']['text']) ? $input['entry'][0]['messaging'][0]['message']['text'] : '';
if (!empty($input['entry'][0]['messaging'])) {
foreach ($input['entry'][0]['messaging'] as $message) {
$command = "";
// When bot receive message from user
if (!empty($message['message'])) {
$command = $message['message']['text'];
}
// When bot receive button click from user
else if (!empty($message['postback'])) {
$command = $message['postback']['payload'];
}
}
}
$pagetoken = "PAGE TOKEN"; // Facebook TOKEN
if ($command) {
if ($command == "hii") {
$message_to_reply = "test_response";
} else if ($command == "need more info") {
$message_to_reply = "Please fill form at link ";
} else if ($command == "\ud83d\ude00") {
$message_to_reply = "smiley";
}
if ($message_to_reply != "") {
$url = "https://graph.facebook.com/v2.6/me/messages?access_token=$pagetoken";
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text":"' . $message_to_reply . '"
}
}';
$jsonDataEncoded = $jsonData;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
$result = curl_exec($ch);
}
curl_close($ch);
}
}
header('HTTP/1.1 200 OK'); // This line needs to be added
die;

Related

Facebook Graph Api error "An unexpected error has occurred. Please retry your request later"

I'm trying to retrieve all members in a Facebook group getting this error:
array(5) {
["message"]=>
string(66) "An unexpected error has occurred. Please retry your request later."
["type"]=>
string(14) "OAuthException"
["is_transient"]=>
bool(true)
["code"]=>
int(2)
["fbtrace_id"]=>
string(11) "AnfsXcdgM"
}
Here is my code:
$this->_facebook = new Facebook\Facebook(array('app_id' => "$app_id",'app_secret' => "$secret",'default_graph_version' => 'v2.10'));
$this->_facebook->setDefaultAccessToken($_SESSION['facebook_access_token']);
$query = "/".$groupID."/members?fields=id,name,link,picture,first_name,last_name";
try{
$response = $this->_facebook->get($query);
while($pagesEdge)
{
$pageDecoded = json_decode($pagesEdge);
foreach($pageDecoded as $key => $member)
{
$id = $member->id;
}
}
}catch (Facebook\Exceptions\FacebookResponseException $e) { echo 'Graph returned an error: ' . $e->getMessage(); }
It works for groups with few hundreads of people (even once for a group with 10.000 members) but randomly I'm occurring to this.
This might be caused by a server side timeout. I get this error every now and then when I request a huge amount of data. Maybe you should try to limit your request by using the limit parameter (default should be 25).
I solved this by doing a cron that takes 100 data at the time and putting into a file text the value of the token for the next call.
I add this string on the query and when the fields inside $url are empty I quit my execution
<?php
public function updateGroupMembers($groupID)
{
$tempNext = file_get_contents($this->dirM); //check if the next string token is in the file
if (!empty($tempNext))
{
$queryUntil = $tempNext;
}
// Sets the default fallback access token so we don't have to pass it to each request
$this->_facebook->setDefaultAccessToken($_SESSION['facebook_access_token']);
// Create table name
$tableName = $groupID . "_Members";
// Query the Graph API to get all current member's ID and name
try
{
$query = "/".$groupID."/members?fields=id,name,link,picture,first_name,last_name".$queryUntil; //add the next string to my query
$response = $this->_facebook->get($query);
$pagesEdge = $response->getGraphEdge();
// Index for the elements fetched from the API below
$i = 0;
// Get current time
$pageDecoded = json_decode($pagesEdge);
foreach($pageDecoded as $key => $member)
{
/* ...get data and process them... */
}
$temp = $pagesEdge->getMetaData();
$next = parse_url($temp['paging']['next']);
parse_str($next['query'], $url);
$access_token = '&access_token='.$url['access_token'];
$fields = '&fields='.$url['fields'];
$limit = '&limit=100';
$after = '&after='.$url['after'];
$res['until'] = $access_token.$fields.$limit.$after;
file_put_contents($this->dirM, $res['until'], LOCK_EX);
if ( empty($url['access_token']) || empty($url['fields']) || empty($url['limit']) || empty($url['after']) )
{
file_put_contents($this->dirM, '', LOCK_EX); //clean my txt file that contains my next string
die('FINE');
}
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'm2Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'm2Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}

Using php mail() to do simple checks

I am using php mail() (Via piped to program) and my goal is to simply get the email and scan the "from" header to filter it and then if it passes my "rules" or "checks" pass it along to the intended receiver. I have been able to use a sample code to get the mail and I can actually get my "test check" done. The problem I am having is that I cannot get the php mail() function to resend the mail as it was (plain or html). Every time i get my test mail, it comes with all the headers exposed and code. Not a nice and neat email. I also found out that I could encounter problems with this if there are attachments to the mail. I have seen alot of suggestions about going thru PHPMailer and I am willing to entertain that option. I just don't need this to get to complicated. here is the code I am using -
#!/usr/bin/php -q
<?php
$notify= 'myemail#mydomain.com'; // an email address required in case of errors
function mailRead($iKlimit = "")
{
if ($iKlimit == "") {
$iKlimit = 1024;
}
$sErrorSTDINFail = "Error - failed to read mail from STDIN!";
$fp = fopen("php://stdin", "r");
if (!$fp) {
echo $sErrorSTDINFail;
exit();
}
$sEmail = "";
if ($iKlimit == -1) {
while (!feof($fp)) {
$sEmail .= fread($fp, 1024);
}
} else {
while (!feof($fp) && $i_limit < $iKlimit) {
$sEmail .= fread($fp, 1024);
$i_limit++;
}
}
fclose($fp);
return $sEmail;
}
$email = mailRead();
$lines = explode("\n", $email);
$to = "";
$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
$headers .= $lines[$i]."\n";
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
$tst = substr($subject, -3);
if ($tst == "win" | $tst == "biz" | $tst == "net"){
$subject = $subject . "BAD ADDRESS";
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
$to = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
mail('noreply#mydomain.com', $subject, $message);
?>
I am interested in learning, I am code savvy. Somewhat new to email formatting, but very understanding of PHP. Any help is appreciated. Thanx.

PayPal sends multiple IPN's

I have this code, everything works fine. It's just that PayPal keeps resending multiple IPNs. I have read the forum of PayPal and they say that PayPal isn't getting a HTTP/1.1 200 OK from me, so it keeps resending the IPN. How would I go about this?
function sql_execute($sql){
$sql_connect = #mysql_connect($_SERVER['HTTP_HOST'].':3306','root', '****') or
die('Could not connect: ' . mysql_error());
mysql_select_db('4bkk');
mysql_query($sql);
$rows = mysql_affected_rows($sql_connect); //mysql_insert_id();
mysql_close();
return $rows;
}
function sql_query($sql){
// echo $sql;
$sql_connect = #mysql_connect($_SERVER['HTTP_HOST'].':3306','****', 'zzz111') or
die('Could not connect: ' . mysql_error());
mysql_select_db('4bkk');
$rs = mysql_query($sql) or die(mysql_error());
mysql_close();
return $rs;
}
function logtrace($o){
$q = "INSERT INTO log (trace, trace_time) VALUES ('$o', NOW() )";
sql_query($q);
}
function send_email($t,$s,$m,$h){
//mail($t, $s, $m, $h);
$fh = fopen('result_ipn_test.txt', 'w');
fwrite($fh, $t.' '.$s.' '.$m.' '.$h);
fclose($fh);
logtrace('Mail is sent and exit called');
exit();
}
logtrace('__________NEW SESSION__________');
$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
$postFields = 'cmd=_notify-validate';
foreach($_POST as $key => $value)
{
$postFields .= "&$key=".urlencode($value);
}
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postFields
));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
logtrace($info['url']);
curl_close($ch);
//get buyers information from PAYPAL checkout
$email = $_POST['payer_email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$amount = $_POST['amount3'];
$plan = $_POST['option_selection1'];
logtrace($email.' -- '.$active);
$q = "SELECT * FROM users WHERE email='$email' AND user_level='' AND active='unverified'"; //Unprocessed record = no user_level and active = 'unverified'
$ex = sql_execute($q);
//logtrace("THIS ".$q." => ".$ex);
if(sql_execute($q)){
logtrace('IT IS TRUE');
$flag = TRUE;
}
else{
logtrace('FALSE');
$flag = FALSE;
}
logtrace($result.' RESPONSE FROM PAYPAL');
if(($result=='VERIFIED') && $flag){ //Checks first if PayPal is valid, email address exists in
//records and checks if user_level='' and active='unverified',
//if not enters.
logtrace('USER IS READY FOR VERIFICATION');
$q = "SELECT * FROM users WHERE email='$email'";
$data = sql_query($q);
$con = mysql_fetch_array($data);
//Get buyers information from the database
$email2 = $con['email'];
$first_name = $con['first_name'];
$last_name = $con['last_name'];
$active = $con['active'];
$user_level = $con['user_level'];
logtrace('Emails match');
$u = "UPDATE users SET active='verified', user_level='$plan' WHERE email='$email' LIMIT 1";
if (sql_query($u)) { //Successful verification
logtrace('|| Update was sucessful');
}
else{ // Unsuccessful verification.
logtrace('|| Something went wrong with update.');
}
}
else{ // The user doesn't have any record in the database.
$q = "SELECT * FROM users WHERE email='$email' AND (user_level='Monthly' OR user_level='Quarterly' OR user_level='Yearly')";
if(sql_execute($q)){ // The user is already verified
logtrace('THE USER IS ALREADY VERIFIED');
}
else{ // The user does not exist.
logtrace('THE USER HAS NO RECORD ON DATABASE');
}
}
Please refer the sample code https://www.x.com/instant-payment-notification-4
Based on the above code you can try setting curl options for
CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1
CURLOPT_HTTPHEADER, array('Connection: Close')
in your above code where you set as curl_setopt_array ...
This should resolve your HTTP/1.1 200 OK issue I think.

check if facebook URL redirected or not?

i want to check if the url's in my database are reaching the facebook page they should or redirected to "www.facebook.com".
this is the code i use:
<?php
$conn = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('database');
?>
<?php
$query = "SELECT data_txt FROM jos_sobi2_fields_data WHERE fieldid=8 ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$url = $row['data_txt'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
foreach($row as $url) {
curl_setopt($ch, CURLOPT_URL, $url);
$out = curl_exec($ch);
$out = str_replace("\r", "", $out);
$headers_end = strpos($out, "\n\n");
if( $headers_end !== false ) {
$out = substr($out, 0, $headers_end);
}
$headers = explode("\n", $out);
foreach($headers as $header) {
if( substr($header, 0, 10) == "Location: " ) {
$target = substr($header, 10);
echo "[$url] redirects to [$target]<br>";
continue 2;
}
}
echo "[$url] does not redirect<br>";
}
?>
the result is this:
[http://www.facebook.com/shanibakshi.grooming.dogtraining] redirects to [http://www.facebook.com/common/browser.php]
[http://www.facebook.com/shanibakshi.grooming.dogtraining] redirects to [http://www.facebook.com/common/browser.php]
and this url -> http://www.facebook.com/common/browser.php is a facebook page that says my browser is old...probably because of some function in the code.....
anyway all i want to do is to check if the url in my database stays in their place with any redirection.
thanks :)
ronen.
Are you saying that you want to detect redirection, but the problem is you are always getting redirected to browser.php so you get nothing but "false positives"? In that case you probably just need to set the USERAGENT option, something like:
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.2; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');

Graph API: How to grab current user's information?

I'm trying to get some basic information about a user in a PHP script (id and name).
I have tried the following methods:
$retrieve = curl_init("https://graph.facebook.com/me?access_token=$accesstoken");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($retrieve, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($retrieve);
curl_close($retrieve);
and
$user = json_decode(file_get_contents(
"https://graph.facebook.com/me?access_token=$accesstoken"))->me;
The cURL method (former) just times out. The file_get_contents (latter) method just doesn't return anything at all...
What could be causing this? Am I using cURL correctly?
for graph api you can use graph api methods rahter than curl
the following code grabs information of current user
define('FACEBOOK_APP_ID', 'Your API ID');
define('FACEBOOK_SECRET', 'YOUR SECRET');
function get_facebook_cookie($app_id, $application_secret)
{
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value)
{
if ($key != 'sig')
{
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig'])
{
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
$user=json_decode(file_get_contents('https://graph.facebook.com/me?access_token='.$cookie['access_token']));
its prettey easy
Facebook will not let you use curl. They have the api for that.
copy your link and paste it to browser. It will work. In Mozilla you will see the result in browser, IE will save the result as a file. So it is not about invalid access token etc. It is just because Facebook does not respond to your query when it does not come 1-from a web browser, 2-from Facebook APIs.
here is the relevant PHP call to Facebook.
$attachment = array('access_token' => $access_token);
$result=$facebook->api('/me', 'GET', $attachment);
$id = $result['id'];
$name=$result['name'];