Skip to content

Instantly share code, notes, and snippets.

@LifeofGeek
Last active April 19, 2018 01:21
Show Gist options
  • Save LifeofGeek/f2fb10100496cb62359394e132236b69 to your computer and use it in GitHub Desktop.
Save LifeofGeek/f2fb10100496cb62359394e132236b69 to your computer and use it in GitHub Desktop.
Gist to Integrate Facebook Messenger bot with Program O Chatbot. Read the complete Guide/Tutorial @ https://www.lifeofgeek.com/build-responsive-facebook-messenger-bot/
<?php
/**
* Webhook for Facebook Messenger Bot with Program O
* Tutorial Link: https://www.lifeofgeek.com/build-responsive-facebook-messenger-bot/
*/
$access_token = "EAAT06zIHufkBAHewZCWZCBYAWKGJlS5uVOS3aEoIqSROiKZAuR8"; //Replace with your page access token
$verify_token = "lifeofgeek"; //Replace with your app verify token
$hub_verify_token = null;
// Program O Params
$bot_id = '1'; //Program O bot ID
$siteurl = 'https://www.lifeofgeek.com/bot'; // Site url where program o installed
$convo_id = 'bot1'; //Any string to save conversation log
if(isset($_REQUEST['hub_challenge'])) {
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token === $verify_token) {
echo $challenge;
}
$input = json_decode(file_get_contents('php://input'), true);
/**
* Saving Logs
* Remove Comment line below to Record Logs
*/
//file_put_contents("botlog.txt", json_encode( $input ) . PHP_EOL, FILE_APPEND | LOCK_EX);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$message_to_reply = '';
/**
* Some Basic rules to validate incoming messages
*/
$msg = trim($message);
$result = file_get_contents("" .$siteurl. "/chatbot/conversation_start.php?bot_id=" . $bot_id . "&say=" . urlencode($msg) . "&convo_id=" . $convo_id . "&format=json");
$jsonop = json_decode($result);
if($result != '') {
$message_to_reply = $jsonop->botsay;
}
//Facebook API Url
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message_to_reply.'"
}
}';
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment