Advertisement
Guest User

Untitled

a guest
Jun 8th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 18.66 KB | None | 0 0
  1. <?php
  2. function sendText($ch, $body, $to, $token){
  3.     curl_setopt($ch, CURLOPT_URL,            "https://graph.facebook.com/v2.6/me/messages?access_token=$token");
  4.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0 );
  5.     curl_setopt($ch, CURLOPT_POST,           1 );
  6.  
  7.     // == Organize data ==
  8.     $stuffToSend = array(
  9.         'recipient' => array(
  10.            
  11.                 "id" => $to
  12.            
  13.         ),
  14.         'message' => array(
  15.            
  16.                 "text" => $body
  17.            
  18.         )
  19.     );
  20.  
  21.        
  22.     // == Encode data into JSON ==
  23.     $data = json_encode($stuffToSend);
  24.  
  25.     // == Add json to payload ==
  26.     curl_setopt($ch, CURLOPT_POSTFIELDS,     $data );
  27.     curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: application/json'));
  28.  
  29.     // == Send message ==
  30.     $result = curl_exec($ch);
  31.     return $result;
  32. }
  33.  
  34. function sendImage($ch, $image, $to, $token){
  35.     curl_setopt($ch, CURLOPT_URL,            "https://graph.facebook.com/v2.6/me/messages?access_token=$token");
  36.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0 );
  37.     curl_setopt($ch, CURLOPT_POST,           1 );
  38.  
  39.     // == Organize data ==
  40.     $stuffToSend = array(
  41.         'recipient' => array(
  42.             "id" => $to    
  43.         ),
  44.         'message' => array(
  45.             "attachment" => array(
  46.                 "type" => "image",
  47.                 "payload" => array(
  48.                     "url" => $image
  49.                 )
  50.             )            
  51.         )
  52.     );
  53.  
  54.     // == Encode data into JSON ==
  55.     $body = json_encode($stuffToSend);
  56.  
  57.     // == Add json to payload ==
  58.     curl_setopt($ch, CURLOPT_POSTFIELDS,     $body );
  59.     curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: application/json'));
  60.  
  61.     // == Send message ==
  62.     $result = curl_exec($ch);
  63.     return $result;
  64. }
  65.  
  66. function sendButton1($ch, $body, $to, $token, $b1, $bo1){
  67.     curl_setopt($ch, CURLOPT_URL,            "https://graph.facebook.com/v2.6/me/messages?access_token=$token");
  68.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0 );
  69.     curl_setopt($ch, CURLOPT_POST,           1 );
  70.  
  71.     // == Organize data ==
  72.     $stuffToSend = array(
  73.         'recipient' => array(
  74.             "id" => $to  
  75.         ),
  76.         'message' => array(
  77.             "attachment" => array(
  78.                 "type" => "template",
  79.                 "payload" => array(
  80.                     "template_type" => "button",
  81.                     "text" => $body,
  82.                     "buttons" => array(
  83.                         array(
  84.                             "type" => "postback",
  85.                             "title" => $b1,
  86.                             "payload" => $bo1
  87.                         )
  88.                     )
  89.                 )
  90.             )
  91.         )
  92.     );
  93.     // == Encode data into JSON ==
  94.     $body = json_encode($stuffToSend);
  95.  
  96.     // == Add json to payload ==
  97.     curl_setopt($ch, CURLOPT_POSTFIELDS,     $body );
  98.     curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: application/json'));
  99.  
  100.     // == Send message ==
  101.     $result = curl_exec($ch);
  102.     return $result;
  103. }
  104.  
  105. function sendButton2($ch, $body, $to, $token, $b1, $bo1,  $b2, $bo2){
  106.     curl_setopt($ch, CURLOPT_URL,            "https://graph.facebook.com/v2.6/me/messages?access_token=$token");
  107.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0 );
  108.     curl_setopt($ch, CURLOPT_POST,           1 );
  109.  
  110.     // == Organize data ==
  111.     $stuffToSend = array(
  112.         'recipient' => array(
  113.             "id" => $to  
  114.         ),
  115.         'message' => array(
  116.             "attachment" => array(
  117.                 "type" => "template",
  118.                 "payload" => array(
  119.                     "template_type" => "button",
  120.                     "text" => $body,
  121.                     "buttons" => array(
  122.                         array(
  123.                             "type" => "postback",
  124.                             "title" => $b1,
  125.                             "payload" => $bo1
  126.                         ),
  127.                         array(
  128.                             "type" => "postback",
  129.                             "title" => $b2,
  130.                             "payload" => $bo2
  131.                         )
  132.                     )
  133.                 )
  134.             )
  135.         )
  136.     );
  137.  
  138.        
  139.     // == Encode data into JSON ==
  140.     $body = json_encode($stuffToSend);
  141.  
  142.     // == Add json to payload ==
  143.     curl_setopt($ch, CURLOPT_POSTFIELDS,     $body );
  144.     curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: application/json'));
  145.  
  146.     // == Send message ==
  147.     $result = curl_exec($ch);
  148.     return $result;
  149. }
  150.  
  151. function sendButton3($ch, $body, $to, $token, $b1, $bo1,  $b2, $bo2, $b3, $bo3){
  152.     curl_setopt($ch, CURLOPT_URL,            "https://graph.facebook.com/v2.6/me/messages?access_token=$token");
  153.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0 );
  154.     curl_setopt($ch, CURLOPT_POST,           1 );
  155.  
  156.     // == Organize data ==
  157.     $stuffToSend = array(
  158.         'recipient' => array(
  159.             "id" => $to  
  160.         ),
  161.         'message' => array(
  162.             "attachment" => array(
  163.                 "type" => "template",
  164.                 "payload" => array(
  165.                     "template_type" => "button",
  166.                     "text" => $body,
  167.                     "buttons" => array(
  168.                         array(
  169.                             "type" => "postback",
  170.                             "title" => $b1,
  171.                             "payload" => $bo1
  172.                         ),
  173.                         array(
  174.                             "type" => "postback",
  175.                             "title" => $b2,
  176.                             "payload" => $bo2
  177.                         ),
  178.                         array(
  179.                             "type" => "postback",
  180.                             "title" => $b3,
  181.                             "payload" => $bo3
  182.                         )
  183.                     )
  184.                 )
  185.             )
  186.         )
  187.     );
  188.  
  189.        
  190.     // == Encode data into JSON ==
  191.     $body = json_encode($stuffToSend);
  192.  
  193.     // == Add json to payload ==
  194.     curl_setopt($ch, CURLOPT_POSTFIELDS,     $body );
  195.     curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: application/json'));
  196.  
  197.     // == Send message ==
  198.     $result = curl_exec($ch);
  199.     return $result;
  200. }
  201.  
  202. function sendButtonLink3($ch, $body, $to, $token, $b1, $bo1,  $b2, $bo2, $b3, $bo3){
  203.     curl_setopt($ch, CURLOPT_URL,            "https://graph.facebook.com/v2.6/me/messages?access_token=$token");
  204.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0 );
  205.     curl_setopt($ch, CURLOPT_POST,           1 );
  206.  
  207.     // == Organize data ==
  208.     $stuffToSend = array(
  209.         'recipient' => array(
  210.             "id" => $to  
  211.         ),
  212.         'message' => array(
  213.             "attachment" => array(
  214.                 "type" => "template",
  215.                 "payload" => array(
  216.                     "template_type" => "button",
  217.                     "text" => $body,
  218.                     "buttons" => array(
  219.                         array(
  220.                             "type" => "web_url",
  221.                             "url" => $bo3,
  222.                             "title" => $b3,
  223.                            
  224.                         ),
  225.                         array(
  226.                             "type" => "postback",
  227.                             "title" => $b1,
  228.                             "payload" => $bo1
  229.                         ),
  230.                         array(
  231.                             "type" => "postback",
  232.                             "title" => $b2,
  233.                             "payload" => $bo2
  234.                         ),
  235.                     )
  236.                 )
  237.             )
  238.         )
  239.     );
  240.  
  241.        
  242.     // == Encode data into JSON ==
  243.     $body = json_encode($stuffToSend);
  244.  
  245.     // == Add json to payload ==
  246.     curl_setopt($ch, CURLOPT_POSTFIELDS,     $body );
  247.     curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: application/json'));
  248.  
  249.     // == Send message ==
  250.     $result = curl_exec($ch);
  251.     return $result;
  252. }
  253.  
  254.  
  255. /* Sends buttons.  Building the $bodyArr must be precise or sending will fail
  256.  *  
  257.  * Require: $bodyArr is (arrayof (arrayof "type" => (oneof "postback", "web_url"),
  258.  *                                        "title" => 'text',
  259.  *                                        (oneof "payload", "url") => 'text'))
  260.  */
  261.  
  262. function sendGenButtons($ch, $body, $bodyArr, $to, $token){
  263.     curl_setopt($ch, CURLOPT_URL,            "https://graph.facebook.com/v2.6/me/messages?access_token=$token");
  264.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0 );
  265.     curl_setopt($ch, CURLOPT_POST,           1 );
  266.  
  267.     // == Organize data ==
  268.     $stuffToSend = array(
  269.         'recipient' => array(
  270.             "id" => $to  
  271.         ),
  272.         'message' => array(
  273.             "attachment" => array(
  274.                 "type" => "template",
  275.                 "payload" => array(
  276.                     "template_type" => "button",
  277.                     "text" => $body,
  278.                     "buttons" => $bodyArr
  279.                 )
  280.             )
  281.         )
  282.     );
  283.  
  284.        
  285.     // == Encode data into JSON ==
  286.     $body = json_encode($stuffToSend);
  287.  
  288.     // == Add json to payload ==
  289.     curl_setopt($ch, CURLOPT_POSTFIELDS,     $body );
  290.     curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: application/json'));
  291.  
  292.     // == Send message ==
  293.     $result = curl_exec($ch);
  294.     return $result;
  295. }
  296.  
  297. function getUser($ch, $id, $token){
  298.     curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v2.6/$id?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=$token");
  299.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  300.     curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  301.     $data = curl_exec($ch);
  302.     return json_decode($data);
  303. }
  304.  
  305. function execBot($conn, $ch, $user, $userLoc, $userData, $type, $rec, $token){
  306.     // == Finds the user location within the bot path ==
  307.    
  308.     switch ($type){
  309.         case "free":
  310.             sendText($ch, "Sorry, we don't recoginze that response.  We'll send that again to retry.", $user, $token);
  311.             goto free;
  312.             break;
  313.         case "struct":
  314.            
  315.             switch ($rec){
  316.            
  317.                 case "restart":
  318.                     $curId = $userLoc["botid"];
  319.                     $sql = "UPDATE tbl_fb_bot_loc SET prop1='NONE', prop2='NONE', prop3='NONE', prop4='NONE', botid=$curId WHERE user_id='$user'";
  320.                     mysqli_query($conn, $sql);
  321.                     $userLoc = array(
  322.                         "user_id" => $user,
  323.                         "prop1" =>  "NONE",
  324.                         "prop2" =>  "NONE",
  325.                         "prop3" =>  "NONE",
  326.                         "prop4" =>  "NONE",
  327.                         "botid" => $curId);
  328.  
  329.                     $sql = "SELECT * FROM tbl_bot_fb WHERE prop1='{$userLoc["prop1"]}' AND prop2='{$userLoc["prop2"]}' AND prop3='{$userLoc["prop3"]}' AND prop4='{$userLoc["prop4"]}' AND botid={$userLoc["botid"]}";
  330.                     $query = mysqli_query($conn, $sql);
  331.                     $newBot = mysqli_fetch_assoc($query);
  332.            
  333.                     goto message;
  334.  
  335.                     break;
  336.                 case "Set botid=0":
  337.                    
  338.                     $sql = "UPDATE tbl_fb_bot_loc SET prop1='NONE', prop2='NONE', prop3='NONE', prop4='NONE', botid=0 WHERE user_id='$user'";
  339.                     mysqli_query($conn, $sql);
  340.                     $userLoc = array(
  341.                         "user_id" => $user,
  342.                         "prop1" =>  "NONE",
  343.                         "prop2" =>  "NONE",
  344.                         "prop3" =>  "NONE",
  345.                         "prop4" =>  "NONE",
  346.                         "botid" => 0);
  347.  
  348.                     $sql = "SELECT * FROM tbl_bot_fb WHERE prop1='{$userLoc["prop1"]}' AND prop2='{$userLoc["prop2"]}' AND prop3='{$userLoc["prop3"]}' AND prop4='{$userLoc["prop4"]}' AND botid={$userLoc["botid"]}";
  349.                     $query = mysqli_query($conn, $sql);
  350.                     $newBot = mysqli_fetch_assoc($query);
  351.            
  352.                     goto message;
  353.                
  354.                     break;
  355.                 default:
  356.                     $action = substr($rec, 4, 5);
  357.                     $prop = substr($rec, 10);
  358.                     break;
  359.             }
  360.             break;
  361.     }
  362.    
  363.        
  364.     if(strlen($prop) == 1){
  365.         $prop = intval($prop);
  366.     }
  367.  
  368.     $sql = "UPDATE tbl_fb_bot_loc SET $action='$prop' WHERE user_id='$user'";
  369.     if(mysqli_query($conn, $sql)){
  370.         //success
  371.     } else {
  372.         //fail -> PANIC!
  373.     }
  374.    
  375.    
  376.    
  377.     $userLoc[$action] = $prop;
  378.     free:
  379.     $sql = "SELECT * FROM tbl_bot_fb WHERE prop1='{$userLoc["prop1"]}' AND prop2='{$userLoc["prop2"]}' AND prop3='{$userLoc["prop3"]}' AND prop4='{$userLoc["prop4"]}' AND botid={$userLoc["botid"]}";
  380.     $query = mysqli_query($conn, $sql);
  381.     $newBot = mysqli_fetch_assoc($query);
  382.    
  383.     message:
  384.    
  385.     sendText($ch, $newBot["response1"], $user, $token);
  386.     sleep(1);
  387.            
  388.     if($newBot["image"] != "X"){
  389.         sendImage($ch, $newBot["image"], $user, $token);
  390.         sleep(1);
  391.     }
  392.    
  393.    
  394.     if($newBot["link"] != "X"){
  395.         sendButtonLink3($ch, $newBot["response2"], $user, $token, $newBot["but1"], $newBot["but_opt1"], $newBot["but2"], $newBot["but_opt2"], $newBot["but3"], $newBot["link"]);    
  396.     } else if($newBot["but2"] == "X" && $newBot["but3"] == "X"){
  397.         sendButton1($ch, $newBot["response2"], $user, $token, $newBot["but1"], $newBot["but_opt1"]);
  398.     } else if($newBot["but3"] == "X"){
  399.         sendButton2($ch, $newBot["response2"], $user, $token, $newBot["but1"], $newBot["but_opt1"], $newBot["but2"], $newBot["but_opt2"]);      
  400.     } else {
  401.         sendButton3($ch, $newBot["response2"], $user, $token, $newBot["but1"], $newBot["but_opt1"], $newBot["but2"], $newBot["but_opt2"], $newBot["but3"], $newBot["but_opt3"]);
  402.     }
  403.    
  404.    
  405. }
  406.  
  407. // == First time settup ==
  408. $entityBody = file_get_contents('php://input');
  409. $decoded = json_decode($entityBody, true);
  410. $ch = curl_init();
  411. $token = "EAADZB54bKfIgBAHrrbZBUEsdRghd7W2JmkcZCuCcZCZBKRQufPjJf8CGbs1x8NUkiPLjbaKtO2oqz3CudNklnIX3szQa6OoVaezXRtlCczTBsS6W0LyQJZBijPoq64twHA2vE1m0rQJPZALVu6HsEJGj49Aeje96JxZCnMCx81XhwgZDZD";
  412.  
  413. // == Connect to the MySQL Database ==
  414. $servername = "localhost";
  415. $username = "satisfi_bot";
  416. $password = "BotsAreFun21";
  417. $dbname = "satisfi_bot";
  418.  
  419. // Create connection
  420. $conn = mysqli_connect($servername, $username, $password, $dbname);
  421.  
  422. // Check connection
  423. if (!$conn) {
  424.     \file_put_contents("output.txt", "Connection failed: " . mysqli_connect_error(). "\n", FILE_APPEND);
  425. }
  426.  
  427.  
  428.  
  429. // == Pull data from convoluted JSON payload ==
  430. $body = $decoded["entry"][0]["messaging"][0]["message"]["text"];                //these will be empty strings if they are not the correct message type
  431. $payload = $decoded["entry"][0]["messaging"][0]["postback"]["payload"];         // ^^ ditto
  432. $from = $decoded["entry"][0]["messaging"][0]["sender"]["id"];
  433.  
  434. \file_put_contents("output.txt", "test\n", FILE_APPEND);
  435. //sendText($ch, "YOU PRESSED A BUTTON! CONGRATULATIONS!", $from, $token);
  436.  
  437.  
  438. $sql = "SELECT * FROM tbl_fb_user_data WHERE user_id='$from'";
  439. $query = mysqli_query($conn, $sql);
  440.  
  441. if(mysqli_num_rows($query) >= 1){
  442.     // == We already have this user on record ==
  443.     $userData = mysqli_fetch_assoc($query);
  444. } else {
  445.     // == We have no record of this user, add them to the database ==
  446.     $userData = getUser($ch, $from, $token);
  447.     $firstName = $userData->first_name;
  448.     $lastName = $userData->last_name;
  449.     $gender = $userData->gender;
  450.     $picture = $userData->profile_pic;
  451.     $locale = $userData->locale;
  452.     $timeZone = $userData->timezone;
  453.    
  454.     $sql = "INSERT INTO tbl_fb_user_data (user_id, first_name, last_name, gender, profile_pic, locale, timezone) VALUES ('$from', '$firstName', '$lastName', '$gender', '$picture', '$locale', '$timeZone')";
  455.     mysqli_query($conn, $sql);
  456. }
  457.  
  458.  
  459.  
  460. // == Find the user's location in the bot path, decide what to send ==
  461.        
  462.     $sql = "SELECT * FROM tbl_fb_bot_loc WHERE user_id='$from'";
  463.     $query = mysqli_query($conn, $sql);
  464.     if(mysqli_num_rows($query) >= 1){
  465.         // == This a user who has used the bot before ==
  466.         $userRow = mysqli_fetch_assoc($query);      //gets user's location in the bot
  467.        
  468.         //execBot($conn, $userRow, $ch, $type, $body, $from, $chatId, $firstName, $lastName);
  469.         //$result = LogDebugMsg("&Note=ExecutedBot1&Body=".$body."&From=".$from."&chatID=".$chatId."&Type=".$type);
  470.  
  471.  
  472.     } else {
  473.         // == This user has never used the bot ==
  474.         $sql = "INSERT INTO tbl_fb_bot_loc (user_id, prop1, prop2, prop3, prop4, botid) VALUES ('$from', 'NONE' ,'NONE', 'NONE', 'NONE', 0)";
  475.         if(mysqli_query($conn, $sql) == TRUE){
  476.             // == We successfully added the user to the bot, now start them off ==
  477.             $userRow = array(
  478.                 "chatId" => $from,
  479.                 "prop1" =>  "NONE",
  480.                 "prop2" =>  "NONE",
  481.                 "prop3" =>  "NONE",
  482.                 "prop4" =>  "NONE",
  483.                 "botid" => 0);
  484.  
  485.         } else {
  486.             // == We failed at adding the new record ==
  487.             //TODO: PANIC!
  488.  
  489.         }
  490.     }
  491.  
  492.  
  493.  
  494. // == Workaround for the infinite message glitch ==
  495. if($body != ""){
  496.  
  497.     execBot($conn, $ch, $from, $userRow, $userData, "free", $body, $token);
  498.  
  499. //free text was sent
  500. //    if($body == "Who am I?"){
  501. //        // == Proof that we can grab user profile data ==
  502. //        $userData = getUser($ch, $from, $token);
  503. //        // == This is all the data we can grab for a user ==
  504. //        $firstName = $userData->first_name;
  505. //        $lastName = $userData->last_name;
  506. //        $gender = $userData->gender;
  507. //        $picture = $userData->profile_pic;
  508. //        $locale = $userData->locale;
  509. //        $timeZone = $userData->timezone;
  510. //        // == ensure we read the data correctly by sending some of it as a message
  511. //        sendText($ch, "You are $firstName $lastName. I believe you are $gender.", $from, $token);
  512. //    } else if ($body == "What do I look like?"){
  513. //        $image = $row["profile_pic"];
  514. //        sendImage($ch, $image, $from, $token);
  515. //    } else {
  516. //        sendButtons($ch, "These are some buttons", $from, $token);
  517. //    }
  518.    
  519.    
  520. } else if ($payload != "") {
  521. //    // a button was pressed
  522.     execBot($conn, $ch, $from, $userRow, $userData, "struct", $payload, $token);
  523.    
  524. //    sendText($ch, "YOU PRESSED A BUTTON! CONGRATULATIONS!", $from, $token);
  525. //    
  526. }else {
  527.     //someother message type occured, discard it
  528.     exit();
  529. }
  530.  
  531. // == Store data in text file for debug purposes ==
  532. \file_put_contents("output.txt", "$from : $body\n", FILE_APPEND);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement