背景:我设置了一个具有两个意图的简单 DialogFlow。设置为 api v1 和 webhook 到故障服务器。我使用 glitch.com 托管一些 js 来收集信息(由用户请求)。
切换到 api 的 v2 打破了这一点。我发现的所有示例都使用 firebase 而不是您自己的服务器来托管 java 脚本,这就是为什么我被卡住并希望有人能指出我在 v2 中向/从谷歌助手获取/返回数据的正确方向而无需火力基地。
请参阅下面的代码
// init project pkgs
const express = require('express');
const ApiAiAssistant = require('actions-on-google').ApiAiAssistant;
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
const Map = require('es6-map');
// Pretty JSON output for logs
const prettyjson = require('prettyjson');
const toSentence = require('underscore.string/toSentence');
app.use(bodyParser.json({type: 'application/json'}));
app.use(express.static('public'));
// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function (request, response) {
response.sendFile(__dirname + '/views/index.html');
});
// Handle webhook requests
app.post('/', function(req, res, next) {
// Log the request headers and body to help in debugging.
// Check the webhook requests coming from Dialogflow by clicking the Logs button the sidebar.
logObject('Request headers: ', req.headers);
logObject('Request body: ', req.body);
// Instantiate a new API.AI assistant object.
const assistant = new ApiAiAssistant({request: req, response: res});
// Declare our action parameters
const PRICE_ACTION = 'price';
// Create functions to handle price query
function getPrice(assistant) {
console.log('** Handling action: ' + PRICE_ACTION);
let requestURL = 'https://blockchain.info/q/24hrprice';
request(requestURL, function(error, response) {
if(error) {
console.log("got an error: " + error);
next(error);
} else {
let price = response.body;
logObject('the current bitcoin price: ' , price);
// Respond to the user with the current temperature.
assistant.tell("The current bitcoin price is " + price);
}
});
}
// Add handler functions to the action router.
let actionRouter = new Map();
actionRouter.set(PRICE_ACTION, getPrice);
actionRouter.set(STATUS_ACTION, getStatus);
// Route requests to the proper handler functions via the action router.
assistant.handleRequest(actionRouter);
});
// Handle errors
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send('Oppss... could not check the bitcoin price');
})
// Pretty print objects for logging
function logObject(message, object, options) {
console.log(message);
console.log(prettyjson.render(object, options));
}
// Listen for requests
let server = app.listen(process.env.PORT, function () {
console.log('--> Our Webhook is listening on ' + JSON.stringify(server.address()));
});