Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make http call on DialogFlow v2 using Javascript ajax call

I found this example on the official site of DialogFlow using Node.js and it is working fine, but I dont know how do I integrate this into my web application.

Is it possible that I can integrate this into my other javascript jquery code? and here I need to run node index.js but do I still need to do this if I integrate with my code?

const projectId = 'xxx'; //https://dialogflow.com/docs/agents#settings
const sessionId = 'xxxxx';
const query = 'Hello';
const languageCode = 'en-US';

// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient();

// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
console.log(sessionPath);
// The text query request.
const request = {
  session: sessionPath,
  queryInput: {
    text: {
      text: query,
      languageCode: languageCode,
    },
  },
};

// Send request and log result
sessionClient
  .detectIntent(request)
  .then(responses => {
    console.log('Detected intent');
    const result = responses[0].queryResult;
    console.log(`  Query: ${result.queryText}`);
    console.log(`  Response: ${result.fulfillmentText}`);
    if (result.intent) {
      console.log(`  Intent: ${result.intent.displayName}`);
    } else {
      console.log(`  No intent matched.`);
    }
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Are there any alternative that we can use DialogFlow v2 using normal javascript jquery, ajax without me having to do node index.js everytime I want to use dialogflow.

DialogFlow v1 was quite simple to use. I had it something like this:

fetch(url, {
    body: JSON.stringify(data),
    // cache: 'no-cache',
    // credentials: 'same-origin',
    headers: {
        'content-type': 'application/json',
        "Authorization": "Bearer " + configs.accessToken,
    },
    method: 'POST',
    mode: 'cors',
    redirect: 'follow',
    referrer: 'no-referrer',
})
    .then(response => response.json()) // parses response to JSON
like image 785
Mizlul Avatar asked May 31 '18 14:05

Mizlul


People also ask

How to make Ajax call in JavaScript?

Ajax is a programming concept. Below are some ways to make Ajax call in JavaScript. Approach 1: In this approach, we will use the XMLHttpRequest object to make Ajax call. The XMLHttpRequest () method which create XMLHttpRequest object which is used to make request with server.

How do I get the Dialogflow API?

Browse the .NET reference documentation for the Dialogflow API. Read the Developer's guide for the Google API Client Library for .NET. Interact with this API in your browser using the APIs Explorer for the Dialogflow API. Install the NuGet package: Google.Apis.Dialogflow.v2.

How to make HTTP requests in JavaScript?

In this article, we are going to look at a few popular ways to make HTTP requests in JavaScript. Ajax is the traditional way to make an asynchronous HTTP request. Data can be sent using the HTTP POST method and received using the HTTP GET method. Let’s take a look and make a GET request.

How do I create a Dialogflow bot?

Visit the Dialogflow website and create a new account or log-in with your existing Google ID. Once you are logged in, you will be welcomed by a screen that consists of different Agents. Click on the Create Agent button to make one for yourself. Name it something similar to OMDBbot.


2 Answers

As others have said here before, the access token has a duration of one hour, after that time it becomes useless. So it's necessary to make a call (http call in my case) to the API in order to request an access token, one time each hour, and use it as explained by Satheesh thereafter. Instructions on how to generate the signature to make the call and use it later are given in https://developers.google.com/identity/protocols/OAuth2ServiceAccount.

Once you obtain the json file from the service account with the private key and the email you have to use (not your email, but the one generated by the service account), you can use the jsrsasign library (in pure javascript), that you can find in https://github.com/kjur/jsrsasign, to generate the JSON Web Signature (JWS) and thus the JSON Web Token (JWT), that will be needed to make the http call to get the access token.

Then you use it as described above by Satheesh to make the call to Dialogflow V2 via jQuery.

The code I have used to achieve this is the next one:

To generate the JWT (using the related library):

function _genJWS() {
    var header = '{"alg":"RS256","typ":"JWT"}';
    var claimSet = jwtClaimSet();
    var privateKey = jwtPrivateKey();

    var sHead = newline_toDos(header);
    var head = KJUR.jws.JWS.readSafeJSONString(sHead);
    var sPayload = newline_toDos(claimSet);
    var sPemPrvKey = privateKey;

    var jws = new KJUR.jws.JWS();
    var sResult = null;
    try {
        prv = KEYUTIL.getKey(sPemPrvKey);

        sResult = KJUR.jws.JWS.sign(head.alg, sHead, sPayload, prv);
    } catch (ex) {
        alert("Error: " + ex);
    }
    return sResult;
}

To request the access token:

function _requestAccessToken() {
    var access_token = accessToken;
    var assertion = _genJWS();
    console.log('Assertion: ' + assertion);
    jQuery.ajax({
        type: "POST",
        url: "https://www.googleapis.com/oauth2/v4/token",
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        data: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" + assertion,
        success: function(response) {
            console.log("success");
            console.log(response);
            access_token = response.access_token;
            console.log(access_token);
        },
        error: function() {
            console.log("Error");
        }
    });
    return access_token;
}

Then use that access token to make the HTTP call to Dialogflow.

Hope it helps.

like image 141
JDE10 Avatar answered Oct 26 '22 19:10

JDE10


You can easily call Dialogflow's V2 API detectIntent endpoint from jQuery.

The API docs show the URL and request formats:

POST https://dialogflow.googleapis.com/v2/{session=projects/*/agent/sessions/*}:detectIntent

{
  "queryParams": {
    object(QueryParameters)
  },
  "queryInput": {
    object(QueryInput)
  },
  "inputAudio": string
}

Authentication works slightly differently; instead of using an access token, you'll create a service account and key using the Cloud dashboard. This documentation page explains how.

like image 28
Daniel Situnayake Avatar answered Oct 26 '22 19:10

Daniel Situnayake