2017-08-27 108 views
0

所以我剛開始爲Google智能助理創建api代理。我遵循https://api.ai/docs/getting-started/basic-fulfillment-conversation的api.ai文檔中的所有內容,以便下面的代理獲取天氣並返回響應。這是一個有效的代碼,但我希望通過回覆獲得創意。我想要做的是從反應中得到國家,並決定是否顯示返回溫度的攝氏或華氏相當於攝氏或華氏。但是在控制檯測試它時,它會繼續使用攝氏溫度。 我還希望根據稍後添加的溫度返回友好提醒。Google智能助理和WorldWeatherOnline API混淆

'use strict'; 
const http = require('http'); 
const host = 'api.worldweatheronline.com'; 
const wwoApiKey = '[api key]'; 
exports.weatherWebhook = (req, res) => { 
    // Get the city and date from the request 
    let city = req.body.result.parameters['geo-city']; // city is a required param 
    // Get the date for the weather forecast (if present) 
    let date = ''; 
if (req.body.result.parameters['date']) { 
date = req.body.result.parameters['date']; 
console.log('Date: ' + date); 
    } 
    // Call the weather API 
    callWeatherApi(city, date).then((output) => { 
// Return the results of the weather API to API.AI 
res.setHeader('Content-Type', 'application/json'); 
res.send(JSON.stringify({ 'speech': output, 'displayText': output })); 
}).catch((error) => { 
// If there is an error let the user know 
res.setHeader('Content-Type', 'application/json'); 
res.send(JSON.stringify({ 'speech': error, 'displayText': error })); 
}); 
}; 
function callWeatherApi (city, date) { 
    return new Promise((resolve, reject) => { 
// Create the path for the HTTP request to get the weather 
let path = '/premium/v1/weather.ashx?format=json&num_of_days=1' + 
    '&q=' + encodeURIComponent(city) + '&key=' + wwoApiKey + '&date=' + date; 


console.log('API Request: ' + host + path); 
// Make the HTTP request to get the weather 
http.get({host: host, path: path}, (res) => { 
    let body = ''; // var to store the response chunks 
    res.on('data', (d) => { body += d; }); // store each response chunk 
    res.on('end',() => { 
    // After all the data has been received parse the JSON for desired data 


    let response = JSON.parse(body); 
    let forecast = response['data']['weather'][0]; 
    let minTemp = forecast['mintempC']; 
    let maxTemp = forecast['maxtempC']; 
    let unit = '°C'; 
    let location = response['data']['request'][0]; 
    //get country 
    let country = location['query'].split(",")[1]; 

    let conditions = response['data']['current_condition'][0]; 
    let currentConditions = conditions['weatherDesc'][0]['value']; 

    if(country == "Liberia" || country == "Myanmar" || country == "United States of America") 
    { 
     minTemp = forecast['mintempF']; 
     maxTemp = forecast['maxtempF']; 
     unit = '°F'; 
    } 

    // Create response 
    let output = 
    `Current conditions in the ${location['type']} 
    ${location['query']} are ${currentConditions} with a projected high of 
    ${maxTemp} ${unit} and a low of 
    ${minTemp}${unit} on 
    ${forecast['date']} in ${country}`; 
    // Resolve the promise with the output text 
    console.log(output); 
    resolve(output); 
    }); 
    res.on('error', (error) => { 
    reject(error); 
    }); 
}); 
}); 
} 
+1

歡迎來到Stack Overflow!這些類型的問題(評論)更適合[codereview.se]。除非有特定問題,否則我會推薦在那裏發帖(請參閱[如何提問](https://stackoverflow.com/help/how-to-ask))。 –

+0

嗨!對於那個很抱歉。那麼我會在那裏移動這篇文章。謝謝! – user2658763

+1

看起來你實際上並不是在尋求代碼審查,而是爲了幫助修復你沒有做到你想要的代碼。您應該[編輯]您的標題以更好地反映這一點,並幫助防止您的問題被關閉。 –

回答

1

雖然您已經使用api.ai和google-on-action標記了此代碼,並且您的代碼似乎來自https://api.ai/docs/getting-started/basic-fulfillment-conversation#setup_weather_api,但Actions API本身並不是真正的問題。看起來它與您處理WorldWeatherOnline(WWO)API的結果以及您期待Google智能助理提供的輸入有關。

你有幾個問題,所有這些都圍繞着一個行:

let country = location['query'].split(",")[1]; 

此行獲取您在查詢中提供的值。在這裏面,你承擔了一些事情,如:

  1. 用戶指定國(WWO可以只是一個城市,如果它足夠有區別)。

  2. 該國被指定爲第二個領域(在談論美國城市時,指定州是常見的,這將使該國成爲第三個領域)。

  3. 谷歌助理指定他們資本化國家的名字(可能,但不能保證)。

  4. 如果這個國家是美國,就用「美國」這個確切的字符串來代替,而不是像「美國」或「美國」那樣較短的東西(但仍然是可識別的)。

此外,還有邏輯問題是詢問信息的人可能希望它在所熟悉的他們單位,而不是傳統的是對該國單位。一位美國人詢問西班牙的天氣可能仍然需要華氏。

無論如何 - 調試這種方法的一個好方法是實際打印出location['query']的值,以查看各種輸入的值,並相應地進行調整。

我不確定是否有直接和好的方法來處理你想要做的事情。一些想法:

  • 你可以嘗試尋找國家作爲查詢字符串的任何地方不區分大小寫字符串,但可能給你一些誤報。儘管如此,這可能是您最簡單的解決方案。

  • @Shuyang提出的建議是一個不錯的選擇 - 但語言區域設置並不總是最好的方式,而且您需要對通過API.AI提供的數據使用Google Actions擴展。

  • 您也可以詢問用戶的當前位置(同樣,如果您使用的是Google操作),然後使用Geolocator找出它們的位置。但那真是太麻煩了。

  • 你可以把它當作對話的一部分 - 擴展Intent短語,讓他們指定「華氏溫度」或其他可能的短語並進行轉換。或者在上下文中存儲一些信息,並且如果他們提供後續短語,例如「華氏度是什麼」,則提供更新的,轉換的信息。 (如果你真的很漂亮,你會將這個人的userId存儲在某種數據庫中,下一次他們訪問你時,你只需以他們選擇的單位提供它)。

我第一個想到的是最簡單的,隨着最後一個是最自然的交談中,但是這一切都取決於什麼樣的location['query']價值實際上可以。

+0

嘿,囚徒,你的第一個建議的解決方案正是我所要做的。位置['query']從響應數據中返回[城市,國家]。所以在我的代碼中,我得到了國家並以此爲基礎來顯示是否顯示攝氏或華氏。但你是對的,我應該把它當作對話的一部分。還有很多東西需要學習。 – user2658763

+0

這是一種全新的思考方式,我們都在試圖找出最適合的方式。一條基本原則 - 思考人們實際上說了些什麼。如果答案有幫助 - 接受或提高答案總是讚賞。 – Prisoner

1

,而不是試圖獲取用戶是來自哪個國家,你可以使用getUserLocale用戶的區域,用戶可以按照自己的意願改變,獨立於它們的位置可以更好地反映其溫度刻度他們喜歡。

使用該方法,您將收到一個字符串,如'en-US''en-GB',這些字符串與一個國家相關聯,因此您可以映射到某個溫度範圍。使用本地化的例子可以在here找到。

在Google控制檯模擬器的操作中,您可以使用語言下拉列表更改語言環境,以便您可以使用不同的語言環境測試您的應用程序。