一段时间后,如何在没有用户响应的情况下触发状态更改?

时间:2019-08-14 13:09:25

标签: javascript chatbot gupshup

我正在通过Bot脚本和Flow Maker在Gupshup中构建潜在客户生成机器人。我是JS的新手,完全被Scripting Tool中提供的botscript语言所迷惑。我正在使用Quickresponse按钮创建一个小菜单。

如果用户没有任何响应(即检测到空的意图),是否可以在一段时间后触发状态更改(:call或:goto)?也许有一种已知的解决方法涉及使用漫游器输出状态?

非常感谢您。

我尝试使用处理程序,但是很快发现用户输入处理程序仅在用户做出响应后才触发。

function revie_menu_Handler (options, event, context, callback){

    console.log("user input is:" + event.message.toLowerCase())

    if(event.message.toLowerCase() === "") {
        options.next_state = 'if_silent';
    } else if (event.message.toLowerCase() === "make me an offer") {
        options.next_state = 'revie_UI_1'
    } else if (event.message.toLowerCase() === "i have a question") {
        options.next_state = 'revie_UI_2'
    } else {
        options.next_state = 'blank'
    }

对应于脚本:

revie_menu: Welcome to the menu! [[Make me an offer, I have a question]]
    revie_UI_1: Make me an offer:call default.menu_offer
    revie_UI_2: I have a question:call default.menu_question
    if_silent:silent:call default_revie_timeout
    blank: :onException
        Exception! What happened...?

1 个答案:

答案 0 :(得分:0)

您提到的用例无法使用bot脚本工具中的标签处理程序来实现。

解决您的问题的一种方法可能是cron服务。 假设您具有如下所示的机器人脚本:

revie_menu: Welcome to the menu! [[Make me an offer, I have a question]]
    revie_UI_1: Make me an offer
        :call default.menu_offer
    revie_UI_2: I have a question
        :call default.menu_question

用户在Facebook Messenger上发起与您的机器人的对话,EventHandler函数收到了 startchatting 事件。使用advance data persistence创建一个“发件人”对象,该对象具有唯一的用户发件人ID作为密钥。 EventHandler()调用MessageHandler()来存储传入用户消息的当前时间,从而调用ScriptHandler()来执行编写在项目文件夹的default.src中的机器人脚本。因此,用户会收到快速回复消息“欢迎使用菜单!”。

function EventHandler(context, event) {
    context.simpledb.roomleveldata = {};
    context.simpledb.doGet("Senders", function(c, e) {
        // console.log("e.dbval-----" + e.dbval);
        var senderData;
        senderData = e.dbval;
        // console.log("DATA-----" + JSON.stringify(senderData));
        senderData[event.sender] = {};
        context.simpledb.doPut("Senders", senderData, function(c_, e_) {
            MessageHandler(context, event);
        });
    });
};

开始聊天事件之后。无论如何,用户都会向机器人发送一条消息-MessageHandler()将接收传入的用户有效负载,更新当前时间(这是从用户收到的最后一条消息的时间),然后调用ScriptHandler()来执行机器人脚本。

 function MessageHandler(context, event) {
 {
        var userInitialObject = {
            "userAttemptCounter": 0,
            "contextObj": event.contextobj,
            "lastActiveTime": new Date().getTime()
        };  
        context.simpledb.doGet("Senders", function(c, e) {
            console.log("e.dbval-----" + e.dbval);
            var data;
            data = e.dbval;
            console.log("DATA-----" + JSON.stringify(data));
            data[event.sender] = userInitialObject;
            context.simpledb.doPut("Senders", data, function(c_, e_) {
                ScriptHandler(context, event);
            });

        });
}

现在,使用EndpointHandler()在漫游器中创建Web服务。该Web服务检索存储的发件人对象,并对照当前时间检查存储的上次用户活动时间的值。在下面的代码段中,这是45秒的差异检查。如果为true,则会使用sendMessage API将消息发送给用户。您可以使用https://www.gupshup.io/developer/bot/{Gupshup_bot_name}/public访问此Web服务。为此网络服务设置时间表。

var async = require("async");
function HttpEndpointHandler(context, event) {
    context.simpledb.doGet("Senders", function(c, e) {
        // console.log("e.dbval-----"+e.dbval);
        var users = e.dbval // get all Facebook user details basis message id which is contextObj, lastActiveTime and userAttemptCounter
        // console.log("DATA-----" + JSON.stringify(users));
        var userInitialObject;

        async.eachOf(users, function(user, key, callback) {

                // console.log(key + " = " + JSON.stringify(user));
                var userLastActiveTime = user["lastActiveTime"]; // extract last activity time from user JSON...
                var currentTime = new Date().getTime();
                var timeDifference = (currentTime - userLastActiveTime) / 1000;
                // console.log("timeDifference -- " + timeDifference);
                var userAttempts = parseInt(user["userAttemptCounter"]);
                // console.log("userAttempts -- " + userAttempts);
                context.simpledb.doGet("userAnswer", function(c_, e_) {
                    if (timeDifference > 45 && userAttempts == 0 ) // Check Survey Flag is not equal to 1(i.e survey completed) // check if 1 reminder is sent to user. *** visitEcom ** variable is true if user has clicked the 2cart link..
                    {
                        var contextObj = user["contextObj"];
                        // console.log(JSON.stringify(contextObj));
                        // var followUpMsg = "We were having so much fun. Let's keep the good times rolling!";
                        var followUpMsg = {
                            "type": "quick_reply",
                            "content": {
                                "type": "text",
                                "text": "Hello? We were having so much fun. Should we keep the good times rolling?"
                            },
                            "msgid": "reminderMessage",
                            "options": [{
                                "type": "text",
                                "title": "Yes",
                                "iconurl": "http://www.iconsplace.com/icons/preview/008342/record-256.png"
                            }, {
                                "type": "text",
                                "title": "No",
                                "iconurl": "http://www.iconsplace.com/icons/preview/red/record-256.png"
                            }]
                        };
                        context.simpledb.doGet("room:" + key, function(cs, evt) {
                            userAttempts = 1; //(userAttempts + 1); // 1
                            // --------------------------------------------------
                            // var roomLevelDataValues = evt.dbval;
                            // Logic to get fallback message + user last message....
                            // var lstmessage = roomLevelDataValues.userLastMessage;
                            // lstmessage.unshift(followUpMsg);
                            // Bot_Message(context, event.botname, JSON.stringify(contextObj), JSON.stringify(lstmessage));
                            // --------------------------------------------------
                            Bot_Message(context, event.botname, JSON.stringify(contextObj), JSON.stringify(followUpMsg));
                            // context.console.log("userAttemptsafterCondition" + userAttempts);
                            userInitialObject = {
                                "userAttemptCounter": userAttempts,
                                "contextObj": contextObj,
                                "lastActiveTime": new Date().getTime()
                            };
                            users[key] = userInitialObject;
                            // context.console.log("Wallah habibi for key " + key);
                            // context.console.log(JSON.stringify(users));
                            callback();
                        });
                    } //if 15 sec
                    else {
                        callback();
                    }
                }); //userAnswer doGet...
            },
            function(err) {

                // context.console.log(JSON.stringify(users));
                context.simpledb.doPut("Senders", users, function(c_, e_) {
                    context.sendResponse("Reminder message sent and userObject updated");
                });
            });
    });
});

SendMessage API,用于向用户发送消息。

function Bot_Message(context, botname, contextobj, message) {
    var done = "";
    var apikey = 'YOUR GUPSHUP ACCOUNT API KEY';
    botname = encodeURI(botname);
    contextobj = encodeURI(contextobj);
    apikey = encodeURI(apikey);
    message = encodeURIComponent(message);
    var url = "https://api.gupshup.io/sm/api/bot/" + botname + "/msg";
    var body = "botname=" + botname + "&context=" + contextobj + "&message=" + message;
    var headers = {
        "Accept": "application/json",
        "apikey": apikey,
        "Content-Type": "application/x-www-form-urlencoded"
    };
    context.simplehttp.makePost(url, body, headers, done);
}

参考文档可以更好地理解示例代码: