iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 5
0
AI & Data

Voice App 開發實務:使用Diagflow+firebase開發Google home App (google assistant action)系列 第 5

如何使用Dialogflow建立Chatbot #4 使用fulfilment串API

本章將繼續完成的將我們的桃園市路邊停車資訊的chatbot。

如何使用Dialogflow建立Chatbot
#1 介紹
#2 建立agent
#3 對話流程設計
#4 使用fulfilment串API
#5 使用fulfilment webhook串API
#6 部屬至 Line bot 上
fulfilment概觀:

  1. 不只可以回傳純文字,可以寫ssml調整語速等,也可以設audio標籤播放音樂,或是 messenger app 的 card 應用
  2. 使用webhook
  3. 內建是Firebase function
  4. 其他cloud function如 AWS lambdas … 都可以。

快速複習:

Fulfilment
程式撰寫的地方。例如 訂飛機 還得串飛機公司的API才有可能完成訂購,所以程式邏緝就是寫在這裡。

那我們繼續完成 Intent CanParking 的部份,如果你還留著上一章follow-up intent的設定,先刪除吧!

至Intent CanParking的Fulfillment Enable這個並Save

Fulfillment
在Fulfillment下有看到 Webhook 及 Inline Editor兩個實作方式。

  1. Webhook:你可以將程式呼叫的部份寫在外部伺服器,通常會用serverless 的架構來做,例如gcp cloud function , firebase cloud function AWS lambda 等,但看你啦。
  2. Inline Editor:內建的Firebase function,建議用這個,99%表現完美,只有一個問題,Firebase function 的 http request 要收費,請斟酌開啟。但串外部API一定要用到…
    就直接以Inline Editor開始。Enable

    dialogflow-fulfillment可以用大多數的平台,但還有一個actions-on-google這個才會對google home支援較完整,但先不管,第6章再來玩。

桃園停車資訊的說明
https://data.tycg.gov.tw/api/v1/rest/datastore/27d2edc9-890e-4a42-bcae-6ba78dd3c331?format=json

目前不支援query單一路名,一下來就是271條路,不過沒差,因為好像沒什麼人在用,很快。

'use strict';

const functions = require('firebase-functions');
const http = require('http');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
    var s = "";
    const RoadName = request.body.queryResult.parameters.RoadName;
    console.log(RoadName);
    if (RoadName === undefined) {
        response.json({ 'fulfillmentText': "不清楚你說的路喔!" });
        return
    }
    callRoadApi(RoadName).then(obj => {
        let s = "";
        if (obj.length > 0) {
            obj.map(i => {
                s += `${i.rd_name} 有${i.rd_count}格停車位。`
            })
        } else {
            s = `${RoadName} 沒有停車位了`
        }
        console.log(s)
        response.json({ 'fulfillmentText': s });

    }).catch(() => {
        response.json({ 'fulfillmentText': `出問題囉!晚點再試` });
    })

});


var callRoadApi = (roadName) => {
    return new Promise((resolve, reject) => {
        // let path = "http://data.tycg.gov.tw/api/v1/rest/datastore/27d2edc9-890e-4a42-bcae-6ba78dd3c331?format=json";
        http.get({ host: "data.tycg.gov.tw", path: "/api/v1/rest/datastore/27d2edc9-890e-4a42-bcae-6ba78dd3c331?format=json" }, (res) => {
            // http.get(path, res => {
            let body = ''; // var to store the response chunks
            res.on('data', (d) => { body += d; }); // store each response chunk
            res.on('end', () => {
                let response = JSON.parse(body);
                let records = response.result.records;
                let r = records.filter((n) => {
                    if (n.rd_name.indexOf(roadName) > -1) {
                        return n
                    }
                })
                if (r.length > 0) {
                    resolve(r)
                } else {
                    console.log("fail it")
                    reject()
                }
            });
            res.on('error', (error) => {
                console.log(`Error calling the weather API: ${error}`)
                reject();
            });
        })
    })
}

var wait = async () => {
    let obj = await callRoadApi("文化二路")
    if (obj.length > 0) {
        let s = "";
        obj.map(i => {
            s += `${i.rd_name} 有${i.rd_count}格停車位。`
        })
        console.log(s)
    } else {
        s = `${roadName} 沒有停車位了`
    }

}
wait()

你可以在本機試試看,在台灣應該沒什麼問題才對。

下一章來實作 webhook 好了。先休息一下,浪費一天.泣.


上一篇
如何使用Dialogflow建立Chatbot #3 對話流程設計
下一篇
如何使用Dialogflow建立Chatbot #5 使用fulfilment webhook串API
系列文
Voice App 開發實務:使用Diagflow+firebase開發Google home App (google assistant action)31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言