Dialogflow easy way for authorization

后端 未结 5 917
孤独总比滥情好
孤独总比滥情好 2020-12-02 00:05

Does exist an easy way to connect Dialogflow agent to node.js code? When I use this code with the correct projectID taken from the Dialogflow agent\'s settings

5条回答
  •  一向
    一向 (楼主)
    2020-12-02 00:57

    I am writing the code, which worked for me. Please follow all the steps provided in Reference link 2 and for coding purpose you can use the snippet provided.

    I have also added the sample JSON of Google Cloud Oauth

    References:

    1. https://www.npmjs.com/package/dialogflow#samples
    2. https://medium.com/@tzahi/how-to-setup-dialogflow-v2-authentication-programmatically-with-node-js-b37fa4815d89

    //Downloaded JSON format
    
    {
      "type": "service_account",
      "project_id": "mybot",
      "private_key_id": "123456asd",
      "private_key": "YOURKEY",
      "client_email": "yourID@mybot.iam.gserviceaccount.com",
      "client_id": "098091234",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "token_uri": "https://oauth2.googleapis.com/token",
      "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
      "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/yourID%40mybot.iam.gserviceaccount.com"
    }
    
    
    //------*********************---------------------------
    //
    const projectId = 'mybot';
    
    //https://dialogflow.com/docs/agents#settings
    // generate session id (currently hard coded)
    const sessionId = '981dbc33-7c54-5419-2cce-edf90efd2170';
    const query = 'hello';
    const languageCode = 'en-US';
    
    // Instantiate a DialogFlow client.
    const dialogflow = require('dialogflow');
    let privateKey = 'YourKey';
    
    // as per goolgle json
    let clientEmail = "yourID@mybot.iam.gserviceaccount.com";
    let config = {
      credentials: {
        private_key: privateKey,
        client_email: clientEmail
      }
    }
    const sessionClient = new dialogflow.SessionsClient(config);
    
    // Define session path
    const sessionPath = sessionClient.sessionPath(projectId, sessionId);
    
    // 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);
      });

提交回复
热议问题