Search code examples
dialogflow-eschatbotdialogflow-es-fulfillment

In Google Dialogflow, How to save variable till session end


I am not able to save token as a variable till the session end. this token will be used for further APIs. here is my code

'use strict';
const axios = require('axios'); 
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const {Payload} = require('dialogflow-fulfillment');
var token = "";
  function login(agent) {
    const email = agent.parameters.email;
    const password = agent.parameters.password;
    const baseurl = "http://demo:3000/login/buyerlogin";
    var data = { email: email, password: password };
    return axios
      .get(baseurl, { data: { email: email, password: password } })
      .then((result) => {
        if (result.data.status == 200) {
          agent.add("Login Successfully 😊");
          agent.add("Select an option to proceed with other queries 👇");
          token = result.data.token; //token will be used for further APIs
          agent.add(
            new Payload(agent.UNSPECIFIED, payloadlog, {
              rawPayload: true,
              sendAsMessage: true,
            })
          );
        } 
      })
      .catch((error) => {
        agent.add("else " + error.message);
      });
  }

I want to save token till the session end. Please help me out on this. Thank You


Solution

  • You can save these values in the parameters of a long-lasting Context that you set and later read in your webhook.

    Setting the token value in a parameter in the Context might look something like

    agent.context.set('info', 99, {
      token: token
    });
    

    you can later get that Context and the token value with something like

    const infoContext = agent.context.get('info');
    const token = infoContext.parameters.token;