从 Dialogflow 创建缓慢的回复

Creating a slow reply from Dialogflow

我想创建一个响应用户缓慢的 Dialogflow webhook,这样更像是有人在另一端,需要几秒钟才能回复。

我正在使用内置的代码编辑器,并且可以创建一个 Intent 处理程序(参见代码),但我只是不知道如何让它回复得更慢。

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });

  function welcome (agent) {
    agent.add(`I'm replying too quickly!`);
  }

  function fallback (agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  agent.handleRequest(intentMap);
});

老实说,很少需要回复得慢一点。但最简单的方法是使用 setTimeout() 并稍微延迟一下。 (不要延迟太久 - 超过 5 或 10 秒,Dialogflow 将超时。)

然而,使用 setTimeout() 的问题是处理程序将需要 return Promise。因此,您需要将对 setTimeout()agent.add() 的调用包装在 Promise 处理程序中。执行此操作的函数可能类似于:

function respondSlowly( agent, msg, ms ){
  return new Promise( resolve => {
    setTimeout( () => {
      agent.add( msg );
      resolve();
    }, ms );
  });
}

然后您将从您的处理程序中调用它,提供代理、消息以及等待回复的毫秒数:

function welcome( agent ){
  return respondSlowly( agent, `Hi there, slowly`, 2000 );  // Wait 2 seconds to reply
}

处理此问题的最佳方法是在 UI 代码中添加延迟。 保持 Dialogflow Intent 不变,一旦在前端收到机器人响应,就延迟显示它。

下面是我们在 Kommunicate 如何处理它的示例 Dialogflow 响应没有任何延迟,然后在 Javascript 代码上,我们显示一个打字指示器动画,在显示它之前使用 Javascript 添加一些延迟。