如何使用对话流程从RESTful API获取数据

时间:2018-11-29 10:59:44

标签: node.js action dialogflow actions-on-google assistant

我在Google助手操作中有点挣扎。现在我正在为我的webhook使用Dialogflow和Firebase。在我的代码中,我想从一个API中获取数据,例如:API。我正在用Node.js编码。由于Node是异步的,所以我不知道如何获取数据。当我尝试拨打电话时,例如:

app.intent(GetData, (conv) => {
  var test= "error";

  apicaller.callApi(answer =>
    {
      test = answer.people[0].name
      go()

    })
    function go ()
    {
    conv.ask(`No matter what people tell you, words and ideas change the world ${test}`)
    }

由于某种原因,当我在其他应用程序中对其进行测试时,此方法有效。使用Dialogflow无效

我还尝试对应用程序app.intent使用asynch,并在等待状态下尝试使用它,但这也行不通。

您是否知道我该如何解决?

在此先感谢您,

路卡

4 个答案:

答案 0 :(得分:1)

您需要像这样返回Promise

function dialogflowHanlderWithRequest(agent) {
  return new Promise((resolve, reject) => {
    request.get(options, (error, response, body) => {
      JSON.parse(body)
      // processing code
      agent.add(...)
      resolve();
    });
  });
};

有关详情,请参见以下内容:

Dialogflow NodeJs Fulfillment V2 - webhook method call ends before completing callback

答案 1 :(得分:1)

如果这在其他应用程序中有效,那么我认为您会收到错误消息,因为您在尝试使用Firebases免费Spark计划时尝试访问外部资源,该计划仅将您限制为Google服务。您将需要升级到Blaze plan时付费才能执行出站网络任务。

答案 2 :(得分:0)

由于异步性,执行callapi的回调后将调用函数go()

尽管您说过尝试使用异步,但我还是建议您进行以下更改以使其更适合您的情况:

app.intent(GetData, async (conv) => {
    var test= "error";

    apicaller.callApi(async answer =>
      {
        test = answer.people[0].name
        await go()

      })
      async function go ()
      {
      conv.ask(`No matter what people tell you, words and ideas change the world ${test}`)
      }

答案 3 :(得分:0)

首先按照其Github存储库中给出的步骤进行操作

https://github.com/googleapis/nodejs-dialogflow

在这里您可以找到README文件中已经提供的工作模块。 您必须使 keyFilename 对象存储在SessionsClient对象创建中(在文章末尾转到以了解如何生成作为keyFileName的凭据文件)。在工作模块下方。

const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

//////////////////////////////////////////////////////////////////
const dialogflow = require("dialogflow");
const uuid = require("uuid");

/**
 * Send a query to the dialogflow agent, and return the query result.
 * @param {string} projectId The project to be used
 */
async function runSample(projectId = "<your project Id>") {
  // A unique identifier for the given session
  const sessionId = uuid.v4();

  // Create a new session
  const sessionClient = new dialogflow.SessionsClient({
    keyFilename: "<The_path_for_your_credentials_file>"
  });
  const sessionPath = sessionClient.sessionPath(projectId, sessionId);

  // The text query request.
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        // The query to send to the dialogflow agent
        text: "new page",
        // The language used by the client (en-US)
        languageCode: "en-US"
      }
    }
  };

  // Send request and log result
  const responses = await sessionClient.detectIntent(request);
  console.log("Detected intent");
  console.log(responses);
  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.`);
  }
}

runSample();

在这里您可以使用Google Cloud Platform使用以下方式获取作为凭证文件的keyFileName文件

https://cloud.google.com/docs/authentication/getting-started

有关完整的教程(印地语),请观看youtube视频:

https://www.youtube.com/watch?v=aAtISTrb9n4&list=LL8ZkoggMm9re6KMO1IhXfkQ