如何使用Diagflow识别唯一用户 [英] How to identify unique users with Diagflow

查看:80
本文介绍了如何使用Diagflow识别唯一用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个助手应用程序,并且正在使用Firebase的云Firestore服务使用webhook作为实现将响应发送回我的应用程序。我已根据此文档在请求JSON中使用了会话参数,并发送了fulfilmentText作为对用户的响应。但是,每当用户启动该应用程序时,都会创建一个我不需要的新会话。我只想为数据库中的每个用户提供一个条目,以便如何使用dialogflow来实现。

I am trying to make an assistant app and was using the cloud firestore service of firebase to send the response back to my app using webhook as fulfilment. I have used 'session' parameter in request JSON according to this documentation and sending fulfilmentText as response to the user. But whenever user launches the app, a new session is created which I don't want. I simply want, just a single entry for each user in my database so how to achieve that using dialogflow.

在Alexa Skill中,我们将deviceId作为参数,通过它我们可以与会话ID无关地唯一标识用户,但dialogflowRequest JSON中是否有任何参数。如果没有,那么如何在没有它的情况下完成此任务。

In Alexa Skill, we have deviceId as parameter by which we can uniquely identify the user irrespective of the session id but is there any parameter in the dialogflow request JSON. If not, then how to achieve this task without it.

我从Dialogflow收到的请求JSON中包含一个userID,因此我可以使用userId还是应该使用与userStorage一起使用,前提是请求JSON中不提供userStorage参数。

The request JSON I am getting from Dialogflow has a userID in it, so can I use the userId or should I go with userStorage provided the userStorage parameter is not available in the request JSON.

request.body.originalDetectIntentRequest { source: 'google',   version: '2',   payload:     { surface: { capabilities: [Object] },
     inputs: [ [Object] ],
     user: 
      { locale: 'en-US',
        userId: 'ABwppHG5OfRf2qquWWjI-Uy-MwfiE1DQlCCeoDrGhG8b0fHVg7GsPmaKehtxAcP-_ycf_9IQVtUISgfKhZzawL7spA' },
     conversation: 
      { conversationId: '1528790005269',
        type: 'ACTIVE',
        conversationToken: '["generate-number-followup"]' },
     availableSurfaces: [ [Object] ] } }

编辑:谢谢@Prisoner的回答,但我无法发送响应中生成的随机ID,并在其中设置有效载荷。以下是我生成uuid并将其存储在firestore中的代码。我在下面的代码中做错了,由于生成了新的uuid用于返回用户,因此响应显示为在数据库中找不到文档。我想我没有适当地发送uuid。请帮助。

EDIT : Thank You @Prisoner for the answer but I am unable to send the random ID generated in the response and set in in the payload. Below is the code where I am generating the uuid and storing it in firestore. What I am doing wrong in the below code due to which new uuid is generated for returning user and therefore response is shown as No document found in the database. I suppose I am not sending uuid appropriately. Please help.

exports.webhook = functions.https.onRequest((request, response) => {


    console.log("request.body.queryResult.parameters", request.body.queryResult.parameters);
    console.log("request.body.originalDetectIntentRequest.payload", request.body.originalDetectIntentRequest.payload);

    let userStorage = request.body.originalDetectIntentRequest.payload.user.userStorage || {};
    let userId;
    console.log("userStorage", userStorage);

    if (userId in userStorage) {
      userId = userStorage.userId;
    } else {
      var uuid = require('uuid/v4');
      userId = uuid();
      userStorage.userId = userId
    }

    console.log("userID", userId);

    switch (request.body.queryResult.action) {
      case 'FeedbackAction': {

            let params = request.body.queryResult.parameters;

            firestore.collection('users').doc(userId).set(params)
              .then(() => {

              response.send({
                'fulfillmentText' : `Thank You for visiting our ${params.resortLocation} hotel branch and giving us ${params.rating} and your comment as ${params.comments}.` ,
                'payload': {
                  'google': {
                    'userStorage': userStorage
                  }
                }

                });
                return console.log("resort location", params.resortLocation);
            })
            .catch((e => {

              console.log('error: ', e);

              response.send({
             'fulfillmentText' : `something went wrong when writing to database`,
             'payload': {
               'google': {
                 'userStorage': userStorage
               }
             }
                });
            }))

        break;
      }
        case 'countFeedbacks':{

          var docRef = firestore.collection('users').doc(userId);

          docRef.get().then(doc => {
              if (doc.exists) {
                  // console.log("Document data:", doc.data());
                  var dat = doc.data();
                  response.send({
                    'fulfillmentText' : `You have given feedback for ${dat.resortLocation} and rating as ${dat.rating}`,
                    'payload': {
                      'google': {
                        'userStorage': userStorage
                      }
                    }
                  });

              } else {
                  // doc.data() will be undefined in this case
                  console.log("No such document!");

                  response.send({
                    'fulfillmentText' : `No feedback found in our database`,
                    'payload': {
                      'google': {
                        'userStorage': userStorage
                      }
                    }
                  });

              }
              return console.log("userStorage_then_wala", userStorage);
          }).catch((e => {
              console.log("Error getting document:", error);
              response.send({
                'fulfillmentText' : `something went wrong while reading from the database`,
                'payload': {
                  'google': {
                    'userStorage': userStorage
                  }
                }
              })
          }));

          break;
        }


推荐答案

您有两种选择,具体取决于您的实际需求。

You have a couple of options, depending on your exact needs.

简单:userStorage

Google提供了一个 userStorage 可以在会话中持久保存的对象可以识别用户。这样,您就可以在需要跟踪用户何时返回时存储自己的标识符。

Google provides a userStorage object which is persisted across conversations when it can identify a user. This lets you store your own identifier when you need to track when a user returns.

最简单的方法是检查 userStorage 对象,用于在调用Webhook时的标识符。如果它不存在,则使用v4 UUID之类的内容创建一个并将其保存在 userStorage 对象中。

The easiest way to do this is to check the userStorage object for the identifier when your webhook is called. If it doesn't exist, create one using something like a v4 UUID and save it in the userStorage object.

如果您使用的是Google行动库,则代码可能看起来像这样:

If you are using the actions-on-google library, the code might look something like this:

let userId;
// if a value for userID exists un user storage, it's a returning user so we can
// just read the value and use it. If a value for userId does not exist in user storage,
// it's a new user, so we need to generate a new ID and save it in user storage.
if (userId in conv.user.storage) {
  userId = conv.user.storage.userId;
} else {
  // Uses the "uuid" package. You can get this with "npm install --save uuid"
  var uuid = require('uuid/v4');
  userId = uuid();
  conv.user.storage.userId = userId
}

如果使用dialogflow库,您可以使用上面的方法,但是首先需要使用以下行:

If you are using the dialogflow library, you can use the above, but you'll need this line first:

let conv = agent.conv();

如果您使用的是 multivocal 库,它将为您完成上述所有操作,并将在环境中的路径 User / Id 。

If you're using the multivocal library, it does all of the above for you and will provide a UserID in the environment under the path User/Id.

如果直接处理JSON,并且使用的是Dialogflow v2协议,则可以通过检查 originalDetectIntentRequest来获取userStorage对象。 JSON请求对象中的.payload.user.userStorage 。您将在JSON响应中设置 payload.google.userStorage 对象。代码类似于上面的代码,可能看起来像这样:

If you're handling the JSON directly, and you are using the Dialogflow v2 protocol, you can get the userStorage object by examining originalDetectIntentRequest.payload.user.userStorage in the JSON request object. You'll set the payload.google.userStorage object in the JSON response. The code is similar to the above and might look something like this:

let userStorage = body.originalDetectIntentRequest.payload.user.userStorage || {};
let userId;
// if a value for userID exists un user storage, it's a returning user so we can
// just read the value and use it. If a value for userId does not exist in user storage,
// it's a new user, so we need to generate a new ID and save it in user storage.
if (userId in userStorage) {
  userId = userStorage.userId;
} else {
  // Uses the "uuid" package. You can get this with "npm install --save uuid"
  var uuid = require('uuid/v4');
  userId = uuid();
  userStorage.userId = userId
}

// ... Do stuff with the userID

// Make sure you include the userStorage as part of the response
var responseBody = {
  payload: {
    google: {
      userStorage: JSON.stringify(userStorage),
      // ...
    }
  }
};

请注意代码的第一行-如果 userStorage 不存在,请使用空对象。在您发送包含第一次在其中存储内容的响应之前,它不会存在,这将在此代码的最后几行中发生。

Note the first line of the code - if userStorage doesn't exist, use an empty object. It won't exist until you send a response that includes storing something in it for the first time, which will happen in the last few lines of this code.

高级:帐户关联

您可以请求用户使用Google登录登录到您的操作。只需在最简单的情况下使用语音即可完成操作,并且只会在第一次时中断流程。

You can request users to sign in to your Action using Google Sign In. This can be done just using voice for the simplest of cases and would only interrupt the flow the first time.

在此之后,您的操作将获得一个JWT,其中包含他们的Google可以用作其标识符的ID。

After this, your Action is given a JWT which contains their Google ID which you can use as their identifier.

如果您使用的是Google动作库,则可以通过以下代码从解码的JWT中获取ID:

If you're using the actions-on-google library, you can get the ID from the decoded JWT with a line such as:

const userId = conv.user.profile.payload.sub;

在多声库中,来自已解码JWT的ID在环境中路径<$下可用。 c $ c>用户/个人资料/子

In the multivocal library, the ID from the decoded JWT is available in the environment under the path User/Profile/sub

不推荐使用:匿名用户ID

您将在StackOverflow上看到一些引用匿名用户ID的答案。 Google已弃用该标识符,该标识符并非始终是验证回访用户的可靠方法,并将于2019年6月1日将其删除。

You'll see some answers here on StackOverflow that reference an Anonymous User ID. Google has deprecated this identifier, which was not always a reliable way to verify returning users, and will be removing it 1 Jun 2019.

此代码目前仍在发送,但这将从2019年6月1日开始删除。

This code is currently still being sent, but this will be removed starting 1 Jun 2019.

这篇关于如何使用Diagflow识别唯一用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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