【问题标题】:how to integrate dialogflow result to linebot (Node.js)?如何将对话流结果集成到 linebot (Node.js)?
【发布时间】:2019-09-25 04:33:48
【问题描述】:

我正在创建使用 node.js 集成 Google Dialogflow 的聊天机器人(Line)。

我只能根据用户输入的文本创建在线聊天机器人并回显一些文本。

我可以从用户输入发送命令创建代码到 Google Dialogflow,并使用 Dialogflow 给用户的 NLU 技术响应文本。

但我需要用户输入发送到对话框流的文本并响应文本(A),然后将文本(A)(在代码添加一些模板按钮的代码后)发送到 Line bot 创建向用户显示一些模板按钮。

如何整合两部分代码实现用户输入文本和通过对话流结果,使用结果发送到在线机器人服务器?

用户输入 -> 对话框流 ->mycode(添加一些模板按钮调用线) ->linbot ->bot 向用户显示模板按钮

谢谢。

//------------------------------------------------

我的对话流代码:

var express = require('express');
var bodyParser = require('body-parser'); 
var app = express();
app.use(
    bodyParser.urlencoded({
        extended: true
    })
)

app.use(
    bodyParser.json()
)



app.post("/webhook", function(req,res){
    console.log(JSON.stringify(req.body, null, 2))
    var intent = req.body.queryResult.intent.displayName;
    var entityCity =  req.body.queryResult.parameters["geo-city"];

    if(intent === 'myIntent')
    {
       //  here I need call bot.on method, but I don't known how to do.
       // return res.json({
            fulfillmentText: `I known your mean.`
        });
    }
    else
    {
        return res.json({
            fulfillmentText: `i am not sure your mean`
        });
    }
})

app.listen(process.env.PORT || 5566, function(){
    console.log('server start ...');
})

//------------------------------------------------

My Line 聊天机器人代码:

var linebot = require('linebot');
var express = require('express');
var app = express();

const bot = linebot({
    channelId: 'mychannelId',
    channelSecret: 'mychannelSecret',
    channelAccessToken: 'mychannelAccessToken'
});

bot.on('message',function(event) {
    console.log('bot');
  console.log(event); 
  var msg = event.message.text;
  // here can add some template button code and reply to user.
 });

 const linebotParser = bot.parser();
app.post('/webhook', linebotParser);

var server = app.listen(process.env.PORT || 8080, function() {
  var port = server.address().port;

});

//--------------------

My Line 聊天机器人代码其他版本:

const line = require('@line/bot-sdk');
const express = require('express');
const lineConfig = {
  channelAccessToken: process.env.HEROKU_LINE_CHANNEL_ACCESS_TOKEN,
  channelSecret: process.env.HEROKU_LINE_CHANNEL_SECRET
};
const client = new line.Client(lineConfig);
const app = express();
app.post('/webhook', line.middleware(lineConfig), function(req, res) {
  Promise
    .all(req.body.events.map(handleEvent))
    .then(function(result) {
      res.json(result);
    });
});
function handleEvent(event) {
  switch (event.type) {
    case 'join':
    case 'follow':
      return client.replyMessage(event.replyToken, {
        type: 'text',
        text: 'hello~'
      });   
    case 'message':
      switch (event.message.type) {
        case 'text':
          return client.replyMessage(event.replyToken, {
            type: 'text',
            text: (event.message.text+'~yu')
          });
      }
  }
}
app.listen(process.env.PORT || 3000, function(){
  console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});

【问题讨论】:

  • template codetemplate button 是什么意思。你能给出任何相关例子的简短例子或截图吗
  • 模板按钮是[按钮模板] 使用按钮模板发送带有图像、标题、文本和多个操作按钮的消息。除了拥有按钮之外,您还可以指示当用户点击图像、标题或文本区域中的任意位置时要执行的单个操作。]ref:developers.line.biz/en/docs/messaging-api/message-types/…
  • 我的目的是将文本发送到对话流并响应我的代码,我可以处理结果然后使用结果发送到 line bot。

标签: javascript node.js express bots dialogflow-es


【解决方案1】:
const line = require('@line/bot-sdk');
const express = require('express');

const dialogflow = require('dialogflow');
const uuid = require('uuid');
const lineConfig = {
  channelAccessToken: process.env.HEROKU_LINE_CHANNEL_ACCESS_TOKEN,
  channelSecret: process.env.HEROKU_LINE_CHANNEL_SECRET
};
const client = new line.Client(lineConfig);
const app = express();
app.post('/webhook', line.middleware(lineConfig), function(req, res) {
  Promise
    .all(req.body.events.map(handleEvent))
    .then(function(result) {
      res.json(result);
    });
});
async function handleEvent(event) {
  switch (event.type) {
    case 'join':
    case 'follow':
      return client.replyMessage(event.replyToken, {
        type: 'text',
        text: 'hello~'
      });   
    case 'message':
      switch (event.message.type) {
          case 'text':
              const response = await queryDF(event.message.text)
              // you will get response from DF here
          return client.replyMessage(event.replyToken, {
            type: 'text',
            text: (event.message.text+'~yu')
          });
      }
  }
}


async function queryDF(message, projectId = 'your-project-id') {
    // A unique identifier for the given session
    const sessionId = uuid.v4();

    // Create a new session
    const sessionClient = new dialogflow.SessionsClient();
    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: message,
                // The language used by the client (en-US)
                languageCode: 'en-US',
            },
        },
    };

    // Send request and log result
    const responses = await sessionClient.detectIntent(request);
    return responses[0].queryResult;

}
app.listen(process.env.PORT || 3000, function(){
  console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});

你需要用户dialogflow npm检测Intent方法

【讨论】:

  • 如果我得到对话流响应,如何调用 replayMessage(Line) 给用户?谢谢。您的代码是 user->line bot get message -> send to dialog flow -> response message => line replay message(how to do?)
  • ``` return client.replyMessage(event.replyToken, { type: 'text' // 这里你可以放你的对话流响应, text: (event.message.text+'~yu') } )```
  • 非常感谢!!但是我遇到了其他问题,您能在其他文章中回复我吗?(stackoverflow.com/questions/58203512/…)再次感谢您。
  • 我发现代码有问题,相同用户响应下一个内容时会话ID总是更新,如何在同一用户中保持相同的会话ID?不同的会话ID不同?谢谢。
  • 您可以为同一用户分配您的线路机器人 ID
猜你喜欢
  • 2019-11-05
  • 1970-01-01
  • 2018-12-09
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 1970-01-01
相关资源
最近更新 更多