// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require( 'firebase-functions' );
const mysql = require( 'mysql' );
const {WebhookClient} = require( 'dialogflow-fulfillment' );
const {Text, Card, Image, Suggestion, Payload} = require( 'dialogflow-fulfillment' );
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
const mysiteurl = 'https://en.wikipedia.org/wiki/Narendra_Modi';
exports.dialogflowFirebaseFulfillment = functions.https.onRequest( ( request, response ) =>{
const agent = new WebhookClient( {request, response} );
console.log( 'Dialogflow Request headers: ' + JSON.stringify( request.headers ) );
console.log( 'Dialogflow Request body: ' + JSON.stringify( request.body ) );
let action = request.body.result['action'];
function welcome( agent ){
agent.add( `Welcome to infohub personal assistant, my name is Isobel` );
agent.add( new Card( {
title: `mysite`,
imageUrl: mysiteurl,
text: `Did you know already mysite if not visit it now! `,
buttonText: 'mysite',
buttonUrl: mysiteurl
} )
);
agent.add( `I can help you get information already contained in mysite` );
agent.add( new Suggestion( `population` ) );
agent.add( new Suggestion( `avgincome` ) );
agent.add( new Suggestion( `thisyeargdp` ) );
}
//Call the callDBJokes method
function navigationdistance( agent ){
// Get parameters from Dialogflow to convert
const from = agent.parameters.from;
const to = agent.parameters.to;
console.log( `User requested to get info on ${to} in ${from}` );
if (action === 'get.data') {
// Call the callDBJokes method
callDB().then((output) => {
// Return the results of the weather API to API.AI
response.setHeader('Content-Type', 'application/json');
response.send(JSON.stringify(output));
}).catch((error) => {
// If there is an error let the user know
response.setHeader('Content-Type', 'application/json');
response.send(JSON.stringify(error));
});
}
// Sent the context to store the parameter information
// and make sure the followup
agent.setContext( {
name: 'navigationdistance',
lifespan: 3,
parameters: {from: from, to: to}
} );
// Compile and send response
agent.add( ` ${to} in ${from} ` );
agent.add( `Would you like to know something else?` );
agent.add( new Suggestion( `population` ) );
agent.add( new Suggestion( `avgincome` ) );
agent.add( new Suggestion( `thisyeargdp` ) );
}
function fallback( agent ){
agent.add( `I didnt get that, can you try again?` );
}
function callDB( to, from ){
return new Promise( ( resolve, reject ) =>{
try{
var connection = mysql.createConnection( {
host: "localhost",
user: "root",
password: "",
database: "test"
} );
var sql = "INSERT INTO mocktable (from, to) VALUES ('$from', '$to')";
connection.query( sql, function( error, results, fields ){
if( !error ){
let response = "The solution is: " + results[0];
response = response.toString();
let output = {'speech': response, 'displayText': response};
console.log( output );
resolve( output );
} else{
let output = {
'speech': 'Error. Query Failed.',
'displayText': 'Error. Query Failed.'
};
console.log( output );
reject( output );
}
} );
connection.end();
} catch
( err ){
let output = {
'speech': 'try-cacth block error',
'displayText': 'try-cacth block error'
};
console.log( output );
reject( output );
}
});
}
let intentMap = new Map(); // Map functions to Dialogflow intent names
intentMap.set( 'Default Welcome Intent', welcome );
intentMap.set( 'get info about mycountry', navigationdistance );
intentMap.set( 'Default Fallback Intent', fallback );
agent.handleRequest( intentMap );
})
;
Это код, который я использую для подключения диалогового потока к базе данных. Я использую встроенный редактор в диалоговом потоке и изменяю его для подключения к базе данных. Я не могу подключиться к базе данных. Есть ли какой-либо другой способ подключения диалогового потока к базе данных.
- У меня есть все зависимости в файле package.json.
- Я создал базу данных с именем test в MySQL.
- Я создал некоторые намерения в диалоговом потоке, и я получаю ответы по умолчанию от намерений.
- Мне нужно вставить детали из ответа в базу данных.
ТИА