How to make Facebook Messenger Chatbot

20.08.2017
By

You need to install Program0-O free chatbot and follow this instruction https://www.lifeofgeek.com/build-responsive-facebook-messenger-bot/

Some important items of installation:

1. do not forget that limit of symbols in one bot message reply is 640 – need to crop message ore prepare solution what to to with other symbols over 640.

2. images, video, audio files is used inside but You neet to prepare template for it.

link to the developer documentation is here - https://developers.facebook.com/docs/messenger-platform/send-api-reference/templates

this is my fppagebot.php file for example...
<?php
/**
 * Webhook for Facebook Messenger Bot with Program O
 * Tutorial Link: https://www.lifeofgeek.com/build-responsive-facebook-messenger-bot/
 */

$access_token = "afdlkasjjl"; //Replace with your page access token
$verify_token = "sdasdf,snd"; //Replace with your app verify token
$hub_verify_token = null;

// Program O Params
$bot_id = '1'; 					        //Program O bot ID
$siteurl = 'http://agronom..asdfsdlfsajdljlsda.skadfldasjf'; 	// Site url where program o installed
$convo_id = 'sdaaskdjflskd';    		    //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 = '';
$flag_long_answer = false; // if answer bigger then 640 symbols calling button form

/**
 * 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;
	//$message_to_reply_normalized = strtr($message_to_reply, array("["=>"<", "]"=>">"));
	$message_to_reply_normalized = strtr($message_to_reply, array("[br]"=>" ", "]"=>"", "[img src="=>" Ссылка на изображение-"));
	//$message_to_reply_normalized1 = strtr($message_to_reply, array("[br]"=>" "));
	//$message_to_reply_normalized = delete_all_between("[img src=", "]", $message_to_reply_normalized1);
	//only 640 symbols at the message...
	$message_to_reply_mid = mb_substr($message_to_reply_normalized, 0, 600, 'UTF-8');
	//if answer is longer then 600 symbols trim it and put link to the site
	if (mb_strlen($message_to_reply) > 600){
		$message_to_reply_short = $message_to_reply_mid." ... ";
		$flag_long_answer = true;
		}
	else{
		$message_to_reply_short = $message_to_reply_mid;
		$flag_long_answer = false;
	}
}

//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.
if ($flag_long_answer){
	$jsonData = '{
			"recipient":{
				"id":"'.$sender.'"
			},
			"message":{
				"attachment":{
					"type":"template",
					"payload":{
					"template_type":"button",
					"text":"'.$message_to_reply_short.'",
					"buttons":[
						{
						"type":"web_url",
						"url":"http://---boturl---/gui/plain/index.php?bot_id='. $bot_id .'&say=' . urlencode($msg) .'&convo_id=' . $convo_id . '&format=html",
						"title":"Продолжить на сайте..."
						}
					]
					}
			    }
            }
		    }';
	}
	else{

		$jsonData = '{
			"recipient":{
				"id":"'.$sender.'"
			},
			"message":{
				"text":"'.$message_to_reply_short.'"
			}
		}';
	}
//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);
	//result can be sended again and again... TODO...
	//$result = curl_exec($ch);
}

//function to delete not used substrings - under development
  function delete_all_between($beginning, $end, $string) {
  $beginningPos = mb_strpos($string, $beginning);
  $endPos = mb_strpos($string, $end);
  if ($beginningPos === false || $endPos === false) {
    return $string;
  }

  $textToDelete = mb_substr($string, $beginningPos, ($endPos + mb_strlen($end)) - $beginningPos);

  return mb_str_replace($textToDelete, '', $string);
 }
?>

 

Добавить комментарий