Skip to content

Instantly share code, notes, and snippets.

@bryan-rojas-liquor
Last active August 1, 2016 15:21
Show Gist options
  • Save bryan-rojas-liquor/aea55d45675a2ed4112dd40414fd43a0 to your computer and use it in GitHub Desktop.
Save bryan-rojas-liquor/aea55d45675a2ed4112dd40414fd43a0 to your computer and use it in GitHub Desktop.
FB Messenget Chat Bot Extension
<?php
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
require_once(dirname(__FILE__) . '/lid/autoload.php');
use pimax\FbBotApp;
use pimax\Messages\Message;
use pimax\Messages\MessageButton;
use pimax\Messages\StructuredMessage;
use pimax\Messages\MessageElement;
use pimax\Messages\MessageReceiptElement;
use pimax\Messages\Address;
use pimax\Messages\Summary;
use pimax\Messages\Adjustment;
use pimax\Messages\MessageImg;
if ( get_option("nj_fb_bot_chat_enable") == 1 ) :
$cr = strtotime(current_time( "H:i", $gmt = 0 ) );
$enable = false;
if ( get_option("nj_fb_bot_chat_custom_time") == 1 ) {
$time_to = get_option("nj_fb_bot_chat_time_to");
$time_from = get_option("nj_fb_bot_chat_time_from");
if ( is_array($time_to) ){
$i=0;
foreach ( $time_to as $vl ) {
if( $cr >= strtotime($vl) && $cr <= strtotime($time_from[$i])){
$enable = true;
break;
}
$i++;
}
}
}else{
$enable = true;
}
if( $enable ) :
global $wpdb;
$table_name = $wpdb->prefix . "facebook_bot_chat";
$verify_token = get_option("nj_fb_bot_chat_verify_token"); // Verify token
$token = get_option("nj_fb_bot_chat_token"); // Page token
// Make Bot Instance
$bot = new FbBotApp($token);
// Receive something
if (!empty($_REQUEST['hub_mode']) && $_REQUEST['hub_mode'] == 'subscribe' && $_REQUEST['hub_verify_token'] == $verify_token) {
// Webhook setup request
echo $_REQUEST['hub_challenge'];
} else {
// Other event
$data = json_decode(file_get_contents("php://input"), true);
if (!empty($data['entry'][0]['messaging'])) {
foreach ($data['entry'][0]['messaging'] as $message) {
// Skipping delivery messages
if (!empty($message['delivery'])) {
continue;
}
$command = "";
$postback = false;
// 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'];
$postback = true;
}
$sender = $message['sender']['id'];
$rs = false;
$command = strtolower($command);
if ( strstr($command,'latest posts') ) {
$rs = true;
nj_bot_chat_send_messenger("posts","",$bot,$sender);
}
elseif ( strstr($command,'search categories') ) {
$rs = true;
nj_bot_chat_send_messenger("list_cat","",$bot,$sender,false,$command);
}
elseif ( strstr($command,'list categories') ) {
$rs = true;
nj_bot_chat_send_messenger("list_cat",apply_filters("fb_bot_category_list",__("Category List","nj_fb_bot")),$bot,$sender);
}elseif ( strstr($command,'search posts') ) {
nj_bot_chat_send_messenger("posts","",$bot,$sender,false,$command);
}elseif ( strstr($command,'list pages') ) {
$rs = true;
nj_bot_chat_send_messenger("pages","",$bot,$sender);
}
elseif ( strstr($command,'search recipes') ) {
$rs = true;
nj_bot_chat_send_messenger("recipes","",$bot,$sender,false,$command);
}
else{
if( $postback ) {
$my_bot = $wpdb->get_row( "SELECT * FROM {$table_name} WHERE postback = 1 AND keyword='{$command}'" );
if( $my_bot->type ) {
$type = ninj_bot_chat_cover_type( $my_bot->type );
nj_bot_chat_send_messenger($type, $my_bot->messenger, $bot, $sender);
$rs = true;
}
}else{
$lists = $wpdb->get_results("SELECT * FROM {$table_name} WHERE postback = 0");
foreach( $lists as $list ){
$keywork = strtolower(stripslashes($list->keyword));
$list_key_work = explode(",",$keywork);
foreach ( $list_key_work as $vl ){
$value = trim($vl);
$logic = $list->logic;
$messager = do_shortcode(stripslashes($list->messenger));
$type = ninj_bot_chat_cover_type( $list->type );
switch ( $logic ) {
case 1;
if ( $command == $value) {
nj_bot_chat_send_messenger($type, $messager, $bot, $sender);
$rs = true;
}
break;
case 2;
if ( preg_match("#^{$value}#i",$command)){
nj_bot_chat_send_messenger($type, $messager, $bot, $sender);
$rs = true;
}
break;
case 3;
if ( preg_match("#^(.*){$value}#i",$command)){
nj_bot_chat_send_messenger($type, $messager, $bot, $sender);
$rs = true;
}
break;
default;
if ( strstr($command,$value)){
nj_bot_chat_send_messenger($type, $messager, $bot, $sender);
$rs = true;
}
break;
}
if( $rs ) {
break;
}
}
}
}
}
/*
* Default messenger bot
*/
if ( !$rs ) {
if( get_option("nj_fb_bot_chat_enable_messages") == 1 ){
if( get_option("nj_fb_bot_chat_support_bot") == 1 ){
$rt = true;
}else{
$rt = false;
}
nj_bot_chat_send_messenger("default", get_option("nj_fb_bot_chat_default"), $bot, $sender,$rt);
}
}
}
}else{
}
}
endif;
endif;
function nj_bot_chat_send_messenger($type, $messager, $bot, $sender, $rl = false, $keywork = false) {
switch ($type) {
case 'text':
if( preg_match("#\[client name\]#",$messager) ) {
$abc = $bot->getinfo($sender);
$name = $abc["first_name"] ." ". $abc["last_name"] ;
$messager = preg_replace("#\[client name\]#",$name,$messager);
}
$bot->send(new Message($sender, $messager));
break;
case 'image':
$bot->send(new MessageImg($sender, $messager));
break;
case 'posts':
/*
* List post
*/
$array_query= array();
$array_query["post_type"] = apply_filters("fb_bot_post_type", array("post") );
$array_query["posts_per_page"] = apply_filters("fb_bot_posts_per_page", 10 );
if ( $keywork ) {
$keywork_arr = explode(" posts ",$keywork);
$array_query["s"]=trim($keywork_arr[1]);
}
$new = new WP_Query($array_query);
if( $new->have_posts() ) :
while ( $new->have_posts() ) : $new->the_post();
$array_list[] = new MessageElement(get_the_title(),
get_the_excerpt(),
ninja_fb_bot_chat_get_src_thubnail(),
[
new MessageButton(MessageButton::TYPE_WEB, apply_filters("fb_bot_readmore",__('Readmore','nj_fb_bot')), get_the_permalink())
]
);
endwhile;
$bot->send(new StructuredMessage($sender,
StructuredMessage::TYPE_GENERIC,
[
'elements' => $array_list
]
));
else:
$bot->send(new Message($sender, __("Sorry, no results were found.","nj_fb_bot")));
endif;
wp_reset_postdata();
break;
case 'pages':
/*
* List post
*/
$array_query= array();
$array_query["post_type"] = apply_filters("fb_bot_post_type", array("page") );
$array_query["posts_per_page"] = apply_filters("fb_bot_posts_per_page", 10 );
$new = new WP_Query($array_query);
while ( $new->have_posts() ) : $new->the_post();
$array_list[] = new MessageElement(get_the_title(),
get_the_excerpt(),
ninja_fb_bot_chat_get_src_thubnail(),
[
new MessageButton(MessageButton::TYPE_WEB, apply_filters("fb_bot_readmore",__('Readmore','nj_fb_bot')), get_the_permalink())
]
);
endwhile;wp_reset_postdata();
$bot->send(new StructuredMessage($sender,
StructuredMessage::TYPE_GENERIC,
[
'elements' => $array_list
]
));
break;
case 'list_cat':
/*
* List category
*/
$array_query = array();
if( $keywork ) {
$keywork_arr = explode(" categories ",$keywork);
$terms = get_terms( 'category', array(
'orderby' => 'count',
'hide_empty' => 0,
'search' =>$keywork_arr[1]
) );
}else{
$terms = get_terms( 'category', array(
'orderby' => 'count',
'hide_empty' => 0
) );
}
foreach ( $terms as $term ) {
$array_list[] = new MessageElement( $term->name,
$term->description,
'',
[
new MessageButton(MessageButton::TYPE_WEB, apply_filters("fb_bot_catview",__('Views','nj_fb_bot')), esc_url( get_term_link( $term ) ))
]
);
}
$bot->send(new StructuredMessage($sender,
StructuredMessage::TYPE_GENERIC,
[
'elements' => $array_list
]
));
break;
case "button":
$array_bt = array();
$full = maybe_unserialize($messager);
$message = stripslashes($full["message"]);
foreach ( $full["data"] as $key => $value ) {
$array_bt[] = new MessageButton(MessageButton::TYPE_POSTBACK, $value, $key);
}
$bot->send(new StructuredMessage($sender,
StructuredMessage::TYPE_BUTTON,
[
'text' => $message,
'buttons' => $array_bt
]
));
break;
case 'recipes':
/*
* List recipes
*/
if ( $keywork ) {
$keywork_arr = explode(" recipes ",$keywork);
$query = ninja_fb_bot_chat_format_query($keywork_arr[1]);
}
#$bot->send(new Message($sender, 'Searching for: ' . $query ));
$results = false;
if ( strlen($query) >= 3 ) {
$sql = "SELECT * FROM My_Table WHERE MATCH(name) AGAINST('{$query}') LIMIT 0, {$limit};";
$sql = trim(preg_replace('/\s\s+/', ' ', $sql));
$mc_key = DB_NAME . ':mem-cached-recipe-chat-search:'.md5($sql);
$mc = MemcachedFactory::get_memcached();
$results = $mc->get( $mc_key );
if( $results == false ) {
$con = Propel::getConnection(RecipePeer::DATABASE_NAME);
$stmt = $con->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_OBJ);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$results = $stmt->fetchAll();
$mc->set( $mc_key, $results, 60 * 3 );
}
}
return $results;
}
if($results) {
foreach ($recipes as $key => $post) {
$postID = $post->wp_post_id;
$rubsPostID = $post->id;
if( !is_null($postID) && !is_null($rubsPostID) && get_the_permalink($postID) ):
$array_list[] = new MessageElement(get_the_title($postID), get_the_excerpt($postID), ninja_fb_bot_chat_get_src_recipe_thubnail($postID), [ new MessageButton( MessageButton::TYPE_WEB, apply_filters("fb_bot_readmore",__('Readmore','nj_fb_bot')), get_the_permalink($postID) ) ] );
endif;
}
$bot->send( new StructuredMessage($sender, StructuredMessage::TYPE_GENERIC, ['elements' => $array_list] ) );
} else {
$bot->send(new Message($sender, __("Sorry, no results were found.","nj_fb_bot")));
}
$bot->send(new Message($sender, 'End of search.' ));
break;
case 'default':
if( !$rl ) {
$bot->send(new Message($sender, $messager),$welcome);
}else{
$bot->send(new StructuredMessage($sender,
StructuredMessage::TYPE_BUTTON,
[
'text' => $messager,
'buttons' => [
new MessageButton(MessageButton::TYPE_POSTBACK, 'Latest Posts'),
new MessageButton(MessageButton::TYPE_POSTBACK, 'List Pages'),
new MessageButton(MessageButton::TYPE_POSTBACK, 'List Categories',"DEVELOPER_DEFINED_PAYLOAD"),
]
]
));
}
break;
}
}
function ninj_bot_chat_cover_type($type){
$return = null;
switch ( $type ) {
case 1:
$return ="text";
break;
case 2:
$return ="image";
break;
case 3:
$return ="button";
break;
}
return $return;
}
/* Recipe Search Integration */
function ninj_bot_chat_get_search_results($query, $limit, $bot, $sender) {
$bot->send(new Message($sender, 'Searching query...' ));
$recipes = ninj_bot_chat_search_recipe($query, $limit);
if($recipes) {
$bot->send(new Message($sender, 'Recipes true.' ));
#return ninj_bot_chat_search_response($recipes, $bot, $sender);
ninj_bot_chat_search_response($recipes, $bot, $sender);
}
#return false;
$bot->send(new Message($sender, 'Recipes empty.' ));
}
function ninja_fb_bot_chat_format_query($query) {
return preg_replace('!\s+!', ' ', trim($query) );
}
function ninj_bot_chat_search_recipe($query, $limit) {
$results = false;
if ( strlen($query) >= 3 ) {
$sql = "SELECT * FROM my_table WHERE MATCH(name) AGAINST('{$query}') LIMIT 0, {$limit};";
$sql = trim(preg_replace('/\s\s+/', ' ', $sql));
$mc_key = DB_NAME . ':mem-cached-recipe-chat-search:'.md5($sql);
$mc = MemcachedFactory::get_memcached();
$results = $mc->get( $mc_key );
if( $results == false ) {
$con = Propel::getConnection(RecipePeer::DATABASE_NAME);
$stmt = $con->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_OBJ);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$results = $stmt->fetchAll();
$mc->set( $mc_key, $results, 60 * 3 );
}
}
return $results;
}
if($results) {
foreach ($recipes as $key => $post) {
$postID = $post->wp_post_id;
$rubsPostID = $post->id;
if( !is_null($postID) && !is_null($rubsPostID) && get_the_permalink($postID) ):
$bot->send(new Message($sender, get_the_title($postID) ));
endif;
}
}
}
function ninj_bot_chat_search_response($recipes, $bot, $sender) {
$bot->send(new Message($sender, 'Inside Search Response.' ));
foreach ($recipes as $key => $post) {
$postID = $post->wp_post_id;
$rubsPostID = $post->id;
if( !is_null($postID) && !is_null($rubsPostID) && get_the_permalink($postID) ):
$bot->send(new Message($sender, get_the_title($postID) ));
endif;
}
}
function ninja_fb_bot_chat_get_src_recipe_thubnail($postID) {
$imgURL = 'http://liquor.assets.s3.amazonaws.com/fpo/no-photo-cocktail.png';
if (has_post_thumbnail($postID)) {
$image = wp_get_attachment_image_src(get_post_thumbnail_id($postID), 'full');
$imgURL = $image[0];
}
return $imgURL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment