所以我剛開始爲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);
});
});
});
}
歡迎來到Stack Overflow!這些類型的問題(評論)更適合[codereview.se]。除非有特定問題,否則我會推薦在那裏發帖(請參閱[如何提問](https://stackoverflow.com/help/how-to-ask))。 –
嗨!對於那個很抱歉。那麼我會在那裏移動這篇文章。謝謝! – user2658763
看起來你實際上並不是在尋求代碼審查,而是爲了幫助修復你沒有做到你想要的代碼。您應該[編輯]您的標題以更好地反映這一點,並幫助防止您的問題被關閉。 –