簡體   English   中英

如何將對話流結果集成到 linebot (Node.js)?

[英]how to integrate dialogflow result to linebot (Node.js)?

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

我只能從用戶輸入的文本創建線路聊天機器人並回顯一些文本。

我可以從用戶輸入發送命令創建代碼到 Google 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 ...');
})

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

我的 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;

});

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

我的 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);
});
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 方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM