iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 20
0
AI & Data

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

actions-on-google 建置 Google Home App #19 actions-on-google 撰寫 接 intent 撈api 回傳 google home

  • 分享至 

  • xImage
  •  

如果還不熟 dialogflow 建立agent 請看本篇:#2 建立agent本人就不贅述了。

app.fallback((conv) => {
    // intent contains the name of the intent
    // you defined in the Intents area of Dialogflow
    const intent = conv.intent;
    switch (intent) {
        case WELCOME_INTENT:
            conv.ask('Hi! How are you doing? you can ask me like "is there any parking space at daton road?"');
            break;

        case CanParking_INTENT:
            console.log("conv.parameters.RoadName", conv.parameters.RoadName)
            conv.close(`You said ${conv.parameters.RoadName}`);
            break;
    }

});

接值 ,拿到 RoadName 後,就可以去串 api 了。

const http = require('http');
const { dialogflow } = require('actions-on-google');
//先define
const WELCOME_INTENT = 'Default Welcome Intent';
const CanParking_INTENT = 'CanParking';
const ParkingPayment_INTENT = 'ParkingPayment';

const RoadName_ARGUMENT = 'RoadName';
const { Translate } = require('@google-cloud/translate');
//翻譯用
const translate = new Translate({
    projectId: "xxx",
});

const app = dialogflow({ debug: false });

// you can add a fallback function instead of a function for individual intents
app.fallback(async (conv) => {
    // intent contains the name of the intent
    // you defined in the Intents area of Dialogflow
    const intent = conv.intent;
    let s = ""
    let obj;
    switch (intent) {
        case WELCOME_INTENT:
            conv.ask('Hi! How are you doing? you can ask me like "is there any parking space at lake side road?"');
            break;

        case CanParking_INTENT:
            console.log("conv.parameters.RoadName", conv.parameters.RoadName)
            try {
                obj = await callRoadApi(conv.parameters.RoadName);
            } catch (e) {
                conv.close(e)
                return
            }
            if (obj.length > 0) {
                obj.map(i => {
                    s = `${conv.parameters.RoadName} get ${i.rd_count} parking space!`
                })
                console.log("s", s)
                conv.close(s)
                return

            }
            break;
        case ParkingPayment_INTENT:
            console.log("conv.parameters.RoadName", conv.parameters.RoadName)
            try {
                obj = await callRoadApi(conv.parameters.RoadName);
            } catch (e) {
                conv.close(e)
                return
            }
            console.log("obj", obj[0].tp_name)
            let translation = await askTranslate(obj[0].tp_name);
            console.log("translation", translation)

            conv.close(translation)
            return;

            break;
    }
});

var askTranslate = text => {
    return new Promise((resolve, reject) => {
        translate
            .translate(text, "en")
            .then(results => {
                const translation = results[0];
                console.log(`Translation: ${translation}`);
                reslove(translation)

            })
    })
}

var callRoadApi = (roadName) => {
    return new Promise((resolve, reject) => {
        console.log("roadName", roadName)
        http.get({ host: "data.tycg.gov.tw", path: "/api/v1/rest/datastore/27d2edc9-890e-4a42-bcae-6ba78dd3c331?format=json&limit=271" }, (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);
                // console.log("response.result", response.result)
                let records = response.result.records;
                // console.log("records", records.length)
                let r = records.filter((n) => {
                    // console.log(n.rd_name, roadName, (n.rd_name.indexOf(roadName) > -1))
                    if (n.rd_name.indexOf(roadName) > -1) {
                        return n
                    }
                })
                // console.log("r", r.length)


                if (r.length > 0) {
                    resolve(r)
                } else if (r.length === 0) {
                    reject(`${roadName} is no data`)

                } else {
                    console.log("fail it")
                    reject(`${roadName} is not clear`)
                }
            });
            res.on('error', (error) => {
                console.log(`Error calling the weather API: ${error}`)
                reject();
            });
        })
    })
}


exports.parking_actions_on_google = app

本來 是打算用 google cloud function 做完。不過居然還不吃 await async ….

沒折,只好用 GAE 來做了…

https://cloud.google.com/blog/products/gcp/now-you-can-deploy-your-node-js-app-to-app-engine-standard-environment?m=1

還滿簡單的,照作就開的了了,只有因為太久沒用gcloud,得重 install gcloud.

Yes


上一篇
actions-on-google 建置 Google Home App #18 actions-on-google 撰寫 hello world
下一篇
actions-on-google 建置 Google Home App #20 Permission: name ; locations
系列文
Voice App 開發實務:使用Diagflow+firebase開發Google home App (google assistant action)31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言