gist.github.com/LakshayNagpal/0c68a90173ccc8a072ef6a03d3d1f8ff

аюсь создать приложение-помощник и использую облачный сервис firestore для firebase, чтобы отправить ответ обратно в мое приложение, используя webhook в качестве выполнения. Я использовал параметр «сеанс» в запросе JSON в соответствии с этимдокументация и отправка executeilmentText в качестве ответа пользователю. Но всякий раз, когда пользователь запускает приложение, создается новый сеанс, который мне не нужен. Я просто хочу, просто одну запись для каждого пользователя в моей базе данных, чтобы узнать, как этого добиться с помощью диалогового потока.

В Alexa Skill у нас есть deviceId как параметр, с помощью которого мы можем однозначно идентифицировать пользователя независимо от идентификатора сеанса, но есть ли какой-либо параметр в запросе диалогового потока JSON. Если нет, то как решить эту задачу без нее.

В запросе JSON, который я получаю из Dialogflow, есть userID, поэтому я могу использовать userId или использовать userStorage, если параметр userStorage недоступен в 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 за ответ, но я не могу отправить случайный идентификатор, сгенерированный в ответе и введенный в полезную нагрузку. Ниже приведен код, где я генерирую UUID и храню его в FireStore. Что я делаю не так в приведенном ниже коде, из-за чего генерируется новый uuid для возвращающегося пользователя, и поэтому ответ отображается как Нет документа в базе данных. Я полагаю, я не отправляю UUID надлежащим образом. Пожалуйста помоги.

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;
        }

Ответы на вопрос(1)

Ваш ответ на вопрос