Я использовал библиотеку dialogflow-fulfillment-nodejs и должен хранить результаты чат-бота диалогового потока в базе данных firestore. Таким образом, когда пользователи вводят свои данные в чат-бот при заказе, они сохраняются в базе данных firestore. Вот код, который я пробовал, но он не работает:
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
var firestore = admin.firestore();
const { WebhookClient } = require('dialogflow-fulfillment');
const { Carousel } = require('actions-on-google');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.firestorehotelreservation = functions.https.onRequest((request, response) => {
console.info('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.info('Dialogflow Request body: ' + JSON.stringify(request.body));
const params = request.body.queryResult.parameters
switch (request.body.result.action) {
case 'input.welcome':
//let params = request.body.result.parameters;
firestore.collection('orders').add(params)
.then((agent) => {
agent.add(`Welcome to my agent!`);
})
.catch((e => {
console.info("error: ", e);
response.send({
speech: "something went wrong when writing on database"
});
}))
break;
case 'input.unknown':
firestore.collection('orders').add(params)
.then((agent) => {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
})
.catch((e => {
console.info("error: ", e);
response.send({
speech: "something went wrong when writing on database"
});
}))
break;
case 'RoomBooking':
firestore.collection('orders').add(params)
.then((agent) => {
agent.add(`${params.name} your hotel booking request for ${params.RoomType}room is forwarded for
${params.persons}persons. We will contact you on ${params.email} soon`);
})
.catch((e => {
console.info("error: ", e);
response.send({
speech: "something went wrong when writing on database"
});
}))
break;
case 'complaint':
firestore.collection('orders').add(params)
.then((agent) => {
agent.add(`Your ${params.typeFeedback} is duly noted against: \n Subject: ${params.subject}.
\n Description: ${params.description}`);
})
.catch((e => {
console.info("error: ", e);
response.send({
speech: "something went wrong when writing on database"
});
}))
break;
default:
response.send({
speech: "no action matched in webhook"
})
}
});
Чат-бот работал отлично, когда я кодировал без библиотеки dialogflow-fulfillment-nodejs, и я получил ответ от чат-бота диалогового потока.
Я не получаю ответа от webhook.
Я попробовал это без библиотеки dialogflow-fulfillment-nodejs, и это сработало нормально, и я получил ответ в чат-боте диалогового потока.
Если без библиотеки работало нормально, есть еще вопрос?
Да! Мне приходится работать с этой библиотекой.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Самая большая проблема заключается в том, что параметр agent не выглядит как Объект WebhookClient, которым он должен быть, если вы собираетесь вызвать add() и добавить его к ответу. Похоже, ваш agent является результатом вызова пожарного магазина.
Как правило, также настраивается функция для каждого намерения, сопоставляется имя намерения (а не имя действия) с этой функцией и используется диспетчер, который является частью библиотеки реализации диалогового потока, чтобы определить, какая функция обработчика должна быть вызвана.
Непонятно, почему вы думаете, что вам нужно использовать библиотеку. Если вы сами обрабатываете ввод и отправляете выходные данные в формате JSON, вам не нужно использовать библиотеку.
В случае, если кто-то ищет тот же вопрос; Вот как я исправил код. Сейчас это работает.
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const { WebhookClient } = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:*'; // enables lib debugging statements
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const _agent = new WebhookClient({ request, response });
// const params = request.body.queryResult.parameters;
console.info('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.info('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
console.info('working');
agent.add(`Good day! Do you want to book a room or have some feedback for us?`);
}
function fallback(agent) {
agent.add(`I'm sorry, I didn't understand. Can you say that again?`);
}
function roombooking(agent) {
const firstname = agent.parameters.firstname;
const lastname = agent.parameters.lastname;
const persons = agent.parameters.persons;
const email = agent.parameters.email;
const RoomType = agent.parameters.RoomType;
console.info(firstname, persons, email, RoomType);
console.info("agent parameters: ", agent.parameters);
const dialogflowAgentRef = db.collection('data').doc();
return db.runTransaction(t => {
t.set(dialogflowAgentRef, { entry: firstname, lastname, persons, email, RoomType});
return Promise.resolve('Write complete');
}).then(doc => {
agent.add(`${firstname} ${lastname} your hotel booking request for ${RoomType} room is forwarded for
${persons} persons. We will contact you on ${email} soon`);
}).catch(err => {
console.info(`Error writing to Firestore: ${err}`);
agent.add(`Failed to write on database`);
});
}
function complaint(agent) {
const typeFeedback = agent.parameters.typeFeedback;
const subject = agent.parameters.subject;
const description = agent.parameters.description;
const dialogflowAgentRef = db.collection('data').doc(); //.doc=docRef,('agent=anythin'=path)
return db.runTransaction(t => {
t.set(dialogflowAgentRef, { entry: typeFeedback, subject, description });
return Promise.resolve('Write complete');
}).then(doc => {
agent.add(`Your ${typeFeedback} is duly noted against: \n Subject: ${subject}.
\n Description: ${description}`);
}).catch(err => {
console.info(`Error writing to Firestore: ${err}`);
agent.add(`Failed to write on database`);
});
}
// Run the proper handler based on the matched Dialogflow intent
const intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('RoomBooking', roombooking);
intentMap.set('Complaint', complaint);
_agent.handleRequest(intentMap);
});
Как узнать, что «проблема в коде», а что «не работает»? Вы получаете сообщения об ошибках? Пожалуйста, обновите свой вопрос. См. Как задать хороший вопрос?