首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用agent.add()发送动态数据作为响应

使用agent.add()发送动态数据作为响应
EN

Stack Overflow用户
提问于 2018-07-10 17:04:25
回答 1查看 1.8K关注 0票数 0

我的需求是使用Dialogflow的Nodejs实现库beta来发送动态数据和响应。

我的问题是知道发送动态数据的可能性,以及我们从外部api获得的响应。在某些情况下,我们需要通过调用API将实时数据发送到dialogflow代理(进而发送到客户端)。我尝试了下面的代码来实现它,但它不起作用,这里的“value”是我们从api响应中获得的数据,同样的数据已经被解析/导航以提取json值。

Agent.add(股票价格为+ JSON.parse(value).IRXML.StockQuotes.Stock_Quote.Trade)

在上面的代码执行之前,我使用提升进行了一个同步的外部API调用,以便在agent.add部分中替换结果。

目前,我无法在promotion then函数内部执行agent.add函数。请帮助我实现这一点,或者让我知道有任何替代方法来做到这一点。

我正在进行一个外部api调用来获取数据,这样我就可以将相同的结果发送回代理。我可以拨打电话,但我真的不确定如何将收到的数据传递给代理。在下面的代码中可以看到,我调用了externalCall()来进行api调用,而这个函数是从SpineDay()中调用的。从externalCall()返回的结果在SpineDay()中被替换,但仍然不会使用agent.add()将结果传递给代理。"externalCall(req,res).then“中的任何agent.add()指令都不起作用。

代码语言:javascript
复制
    function SpineDay(agent){



        externalCall(req,res).then((output,agent) => {

                //res.json({ 'fulfillmentText':  JSON.parse(output).IRXML.StockQuotes.Stock_Quote[0].Trade }); 
                 agent.add(new Card({
                        title: output,
                        imageUrl: 'https://dialogflow.com/images/api_home_laptop.svg',
                        text: `This is the body text of a card.  You can even use line\n  breaks and emoji!`,
                        buttonText: 'Se rendre sur XXX',
                        buttonUrl: 'https://XXX/'
                        })
                    );
                    agent.add(new Suggestion(`Quelles sont les dernière sorties à la demande?`));
                    agent.add(new Suggestion(`Quel est le programme de ce soir?`));
              }).catch(() => {
                res.json({ 'fulfillmentText': `Error calling the weather API!` });
              });

          /*agent.add("Quelles sont les dernière sorties à la demande?");
            agent.add("`Quel est le programme de ce soir?");*/
  } 



var  externalCall = function(mainreq, mainres) { 
      return new Promise(function(resolve, reject){
        // Create the path for the HTTP request to get the weather
          var jsonObject = JSON.stringify(mainreq.body);
          const agent = new WebhookClient({request: req, response: res});
          console.log('In side post code' + Buffer.byteLength(jsonObject, 'utf8'))
          // An object of options to indicate where to post to
          var options = {
              port: '443',
              uri: 'https://xxxx.xxx.xxx//ticker/quote/stock?compid=22323&reqtype=quotes',
              method: 'POST',
              headers: {
                  'Content-Length' : Buffer.byteLength(jsonObject, 'utf8'),
                  'X-MDT-API-KEY': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'    
              }
          };

        // Make the HTTP request to get the weather
        request(options, function(err, res, body) { 

          if (!err && res.statusCode == '200'){
            // After all the data has been received parse the JSON for desired
            // data
            let response = JSON.parse(body).IRXML.StockQuotes.Stock_Quote[0].Trade;


            // Create response
            let output = "xxxx stock price is " +response;

            // Resolve the promise with the output text
            console.log(body);
            resolve(output,agent);
          }else{
              console.log(`Error calling the weather API: ${error}`)
                reject("Error calling the weather API");
          }


        });
      });
    }
EN

回答 1

Stack Overflow用户

发布于 2018-07-17 03:58:52

问题是您的SpineDay函数正在进行asyc调用,但没有返回Promise。尽管externalCall (正确地)使用了Promise,但SpineDay并非如此。该库假定,如果您进行异步调用,您将返回一个Promise,该Promise将在响应准备发送时被填满。

幸运的是,您可以通过在函数中添加几行代码来实现这一点,这些代码行在总体上返回一个promise,并将Promise作为promise链的一部分返回。

代码语言:javascript
复制
    function SpineDay(agent){
        return externalCall(req,res)
             .then((output,agent) => {

                 agent.add(new Card({
                        title: output,
                        imageUrl: 'https://dialogflow.com/images/api_home_laptop.svg',
                        text: `This is the body text of a card.  You can even use line\n  breaks and emoji!`,
                        buttonText: 'Se rendre sur XXX',
                        buttonUrl: 'https://XXX/'
                    })
                 );
                 agent.add(new Suggestion(`Quelles sont les dernière sorties à la demande?`));
                 agent.add(new Suggestion(`Quel est le programme de ce soir?`));
                 return Promise.resolve();
              }).catch(() => {
                 res.json({ 'fulfillmentText': `Error calling the weather API!` });
                 return Promise.resolve();
              });
  } 

因此,首先,您需要返回.then().catch()链的结果,这将是一个承诺。然后,在链中,您还需要返回结果,这是最好的承诺。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51261209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档