Webhook全局变量 [英] Webhook Global Variable

查看:130
本文介绍了Webhook全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的Facebook Messenger机器人创建了一个node.js Webhook.该漫游器内置在对话框流中,并且数据库已连接到Firebase.我的问题是在Webhook中调用某个函数进行登录时,登录后,我从数据库中获取了一个userID,我想将其存储在代码中的某个位置,以便在整个用户会话中都可以使用该userID信息.我将其存储在全局变量中.但是,如果只有一个用户正在使用该漫游器,则此方法可以正常工作.如果另一个用户同时使用该漫游器,则该用户ID信息将在用户之间共享,因为它存储在全局变量中.我该如何解决?请帮忙.

var loggedIn = true;
        for (i = 0; i < contexts.length; i++) {
            console.log("Inside contexts for loop");
            //Check for login details context. 
            if (contexts[i].name == "logindetails") {
                if (contexts[0].parameters.loggedIn == "true") {
                    //set this true if found.
                    loggedIn = true;
                }
            }
        }
        if (loggedIn) {
            showUserAccountOptions(sender);
        }   //else start the login flow and once logged in create the 'logindetails' contexts and set the loggedIn parameter as true.
        else {
            //Login 
            login(email, password);

            //Post the logindetails contexts 
            console.log("Not found");
            let url = "https://api.dialogflow.com/v1/contexts?sessionId=" + response.sessionId;
            console.log("URL", url);
            var con = {
                method: 'POST',
                url: url,
                qs: { access_token: '****' },
                headers: {
                    'content-type': 'application/json',
                    'Authorization': 'Bearer' + ' ****'
                },
                body:
                    [
                        {
                            "lifespan": 25,
                            "name": "logindetails",
                            "parameters": {
                                "loggedIn": "true"
                            }
                        }
                    ],
                json: true
            };

            request(con, function (error, response, body) {
                console.log("Inside api request");
                if (error) {
                    console.log("Inside Error", error);
                }
                else{
                    //show user options
                    showUserAccountOptions(sender);
                }

            });

        }

发送上下文更新到dialogflow:

    let apirespone = let apirespone = {
                "contexts": [
                    {
                      "name": "logindetails",
                      "parameters": {},
                      "lifespan": 5
                    }
                  ]
                }
                    sendToApiAi(sender,apirespone);

function sendToApiAi(sender, text) {

    sendTypingOn(sender);
    let apiaiRequest = apiAiService.textRequest(text, {
        sessionId: sessionIds.get(sender)
    });

    apiaiRequest.on('response', (response) => {
        if (isDefined(response.result)) {
            handleApiAiResponse(sender, response);
        }
    });



    apiaiRequest.on('error', (error) => console.error(error));
    apiaiRequest.end();
}

解决方案

好的通话!您绝对不要 要将其存储在全局变量中.

幸运的是,Dialogflow为此提供了一个很好的解决方案.

在您的Webhook中,您可以将用户ID和任何其他会话信息保存为上下文的一部分参数.您可以在履行代码中将其设置为具有较长使用寿命的传出上下文,并且/或者在每次调用Webhook时重新保存该上下文.您没有提供有关Webhook中当前正在使用的代码的任何信息,但是您可以查看有关上下文如何成为您的响应JSON 或使用库.

要明确-您可以在响应中将Context作为JSON的一部分返回.您不需要进行设置的REST调用.上下文的生存期与生存期一样长,因此,一旦您设置了上下文,就可以在会话期间进行生存期"调用,也可以每次作为返回的JSON的一部分来设置新的(或更新其生存期)./p>

在下一个呼叫中,将向您传递当前有效的所有上下文.您可以找到一个存储先前保存状态的状态,然后从参数中获取值.

更新以回复您的代码

不需要需要您正在执行的REST调用.

您可以返回并更新JSON中的上下文.您没有显示它,但是我想您正在创建响应,并且添加上下文可能看起来像这样:

{
  "displayText": "Show something",
  "contextOut":[
    "name": "logindetails",
    "lifespan": 25,
    "parameters": {
      "loggedIn": "true"
    }
  ]
}

在对话的稍后一点,您可以在回复中重新发送该信息以更新信息.您可能会这样:

在获取信息的循环中,您可以保存整个上下文:

        var logindetails;
        if (contexts[i].name == "logindetails") {
            logindetails = contexts[i];
            if (logindetails.parameters.loggedIn == "true") {
                //set this true if found.
                loggedIn = true;
            }
        }

然后您可以在logindetails中更改所需的内容,并在创建响应时执行以下操作:

{
  "displayText": "Show something",
  "contextOut":[
    loginDetails
  ]
}

I have created a node.js webhook for my facebook messenger bot. The bot is built in dialog flow and the database is connected to firebase. My question when a function is invoked in the webhook to log in, after logging in, I get a userID from the database, which I want to store it somewhere in the code so that userID info is available throughout the user session. I am storing it in a global variable. However, this works fine if only one user is using the bot. If another user is using the bot at the same time, this userID info is shared between users since this is stored in a global variable. How do I solve this? Please help.

var loggedIn = true;
        for (i = 0; i < contexts.length; i++) {
            console.log("Inside contexts for loop");
            //Check for login details context. 
            if (contexts[i].name == "logindetails") {
                if (contexts[0].parameters.loggedIn == "true") {
                    //set this true if found.
                    loggedIn = true;
                }
            }
        }
        if (loggedIn) {
            showUserAccountOptions(sender);
        }   //else start the login flow and once logged in create the 'logindetails' contexts and set the loggedIn parameter as true.
        else {
            //Login 
            login(email, password);

            //Post the logindetails contexts 
            console.log("Not found");
            let url = "https://api.dialogflow.com/v1/contexts?sessionId=" + response.sessionId;
            console.log("URL", url);
            var con = {
                method: 'POST',
                url: url,
                qs: { access_token: '****' },
                headers: {
                    'content-type': 'application/json',
                    'Authorization': 'Bearer' + ' ****'
                },
                body:
                    [
                        {
                            "lifespan": 25,
                            "name": "logindetails",
                            "parameters": {
                                "loggedIn": "true"
                            }
                        }
                    ],
                json: true
            };

            request(con, function (error, response, body) {
                console.log("Inside api request");
                if (error) {
                    console.log("Inside Error", error);
                }
                else{
                    //show user options
                    showUserAccountOptions(sender);
                }

            });

        }

Sending contexts updates to dialogflow:

    let apirespone = let apirespone = {
                "contexts": [
                    {
                      "name": "logindetails",
                      "parameters": {},
                      "lifespan": 5
                    }
                  ]
                }
                    sendToApiAi(sender,apirespone);

function sendToApiAi(sender, text) {

    sendTypingOn(sender);
    let apiaiRequest = apiAiService.textRequest(text, {
        sessionId: sessionIds.get(sender)
    });

    apiaiRequest.on('response', (response) => {
        if (isDefined(response.result)) {
            handleApiAiResponse(sender, response);
        }
    });



    apiaiRequest.on('error', (error) => console.error(error));
    apiaiRequest.end();
}

解决方案

Good call! You definitely don't want to store it in a global variable.

Fortunately, Dialogflow offers a good solution for this.

In your webhook, you can save the userID and any other session information you want as part of a Context parameter. You can set this as an Outgoing Context in your fulfillment code with a long lifespan and/or re-save this Context each time your webhook is called. You don't provide anything about the code you're currently using in your webhook, but you can see the documentation for how the Context can be part of your response JSON or using libraries.

To be clear - you can return the Context as part of the JSON in the response. You don't need to make a REST call to set it. Contexts live as long as their lifetime, so once you have set one, it will live for "lifetime" calls during the session, or you can set new ones (or update their lifespan) each time as part of the JSON you return.

On the next call, you'll be passed all the Contexts that are currently valid. You can find the one that stores the state you've previously saved and get the values from the parameters.

Update to respond to your code

You do not need the REST call you're making.

You can return and update the context in your JSON. You don't show it, but I assume you're creating a response, and adding the context might look something like this:

{
  "displayText": "Show something",
  "contextOut":[
    "name": "logindetails",
    "lifespan": 25,
    "parameters": {
      "loggedIn": "true"
    }
  ]
}

At a later point in the conversation, you can resend this in your response to update the information. You might do it like this:

In your loop where you get the info, you might save the entire context:

        var logindetails;
        if (contexts[i].name == "logindetails") {
            logindetails = contexts[i];
            if (logindetails.parameters.loggedIn == "true") {
                //set this true if found.
                loggedIn = true;
            }
        }

You can then change whatever you want in logindetails and when you create the response, do something like this:

{
  "displayText": "Show something",
  "contextOut":[
    loginDetails
  ]
}

这篇关于Webhook全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆