Я пишу код чат-бота, который создает резервирование для парикмахерской, они сохраняются в базе данных в Firestore.
Все работает хорошо, за исключением того, что примерно через 20 минут бездействия, когда бот работает выполняются и имя клиента запрашивается в базе данных, оно выдает ошибку в журнале Google Cloud:
"Предупреждение, оценка Firebase Config на основе GCLOUD_PROJECT. Инициализация firebase-admin может произойти сбой "
Что заставляет чат-бота выдавать" Empty_Response "
Я прочитал другие ответы здесь, но решения, которые они представляют, не сработали для меня. Я думал, что это проблема с оператором входа и пакетом. json, но ничего.
Я оставляю код ниже.
У кого-нибудь есть идеи, что происходит?
ЭТА ЧАСТЬ РЕДАКТИРУЕТСЯ В ОРИГИНАЛЬНОМ ВОПРОСЕ С ВСЕМ КОДОМ И ДОПОЛНИТЕЛЬНЫМИ ИЗОБРАЖЕНИЯМИ
Перед поиском бота в БД Firestore он принимает решение в зависимости от ответа пользователя с номером , как показывают здесь:
Здравствуйте, я помощник парикмахера! Пожалуйста, выберите опцию:
1. Знай наш адрес
2. Знать наши графики
3. Знайте наши услуги
4. Назначить встречу
Поскольку вы запросили часть кода, я обновил вопрос полностью, поэтому я думаю, что мне будет легче помочь, в дополнение к этому я указали, что вы спрашивали меня в том же коде:
пакет. json
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "8"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"@google-cloud/firestore": "^3.7.5",
"actions-on-google": "^2.5.0",
"firebase-admin": "^8.2.0",
"firebase-functions": "^2.0.2",
"dialogflow": "^0.6.0",
"dialogflow-fulfillment": "^0.6.1"
}
}
index. js
//Login statement: I've obviously modify login details...
'use strict';
const {dialogflow, SimpleResponse} = require('actions-on-google');
const {WebhookClient} = require('dialogflow-fulfillment');
const functions = require('firebase-functions');
var firebaseConfig = {
apiKey: "Here goes my apikey",
authDomain: "rest***********.firebaseapp.com",
databaseURL: "https://rest****************-houusi.firebaseio.com",
projectId: "rest*************-houusi",
storageBucket: "rest***************.appspot.com",
messagingSenderId: "Here goes my SenderID",
appId: "Here goes my apiID"
};
const admin = require('firebase-admin');
admin.initializeApp(firebaseConfig);
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
//Here is the code for the intent GiveID wich is the one that do the search in the DB:
function BusquedaHandler(agent){
const db = admin.firestore();
var id = agent.parameters.identidad;
var busqueda = db.collection('Clientes').doc(id);
return busqueda.get().then( snap => {
if (snap.exists) {
const alldata = snap.data();
const nombre = alldata.Nombre;
agent.add(`Procesando solicitud`);
agent.setFollowupEvent({ 'name': 'conid', 'parameters': {'nombre': nombre, 'identidad': id,}});
return console.log("LECTURA DE LA BASE DE DATOS!");
} else {
agent.add(`Procesando solicitud`);
agent.setFollowupEvent({ 'name': 'noid', 'parameters': {'identidad': id,}});
return console.log("NO ENCONTRADO EN BASE DE DATOS!");
}
});
}
//End to the code for the intent GiveID
//****************************************************************
//This is the code to write in the DB with an ID
const agent = new WebhookClient({ request, response });
function GuardarHandler(agent){
const db = admin.firestore();
let id = agent.parameters.identidad;
let name = agent.parameters.nombre;
let date = agent.parameters.date;
let Servicio = agent.parameters.servicio;
let Trabajador = agent.parameters.trabajador;
let time = agent.parameters.hora;
db.collection('Reservas').add({
Cif: id,
FechaReserva: date,
Hora: time,
NombreCte: name,
Observaciones: Servicio + ', ATENDIDO POR: ' + Trabajador,
Telefono: '',
});
agent.add('Perfecto ' + name + ' su cita fue apuntada!, en unos minutos nos contactaremos con usted para confirmarla.');
return console.log("CON ID GUARDADO EN LA BASE DE DATOS!");
}
//End to write Db with ID
//*************************************************************************
//Code to write in DB with No ID
function GuardarNoIdHandler(agent){
const db = admin.firestore();
let id = agent.parameters.identidad;
let name = agent.parameters.nombre;
var dateobj = new Date();
var date = dateobj.toISOString();
var time = date;
let obser = agent.parameters.servicio;
let tel = agent.parameters.telefono;
db.collection('Reservas').add({
Cif: id,
FechaReserva: date,
Hora: time,
NombreCte: name,
Observaciones: 'CLIENTE NO REGISTRADO: ' + obser,
Telefono: tel,
});
agent.add('Muchas Gracias ' + name + '! le contactaremos para organizar su cita con más detalle.');
return console.log("NO ID GUARDADO EN LA BASE DE DATOS!");
}
//End to Write in DB with No ID
//********************************************************************
//If the user select the number 4 in
//the question then the bot redirect the
//event *askid* following this code:
function DecisionHandler(agent){
let decision = agent.parameters.decision;
if (decision == 'direccion') {agent.add('HERE GOES THE ADRESS');}
if (decision == 'horarios') {agent.add('HERE GOES THE SCHEDULES');}
if (decision == 'servicios') {agent.add('HERE GOES THE SERVICES');}
if (decision == 'cita') {
agent.add(' ');
agent.setFollowupEvent({ 'name': 'askid',});
}
return console.log("DECISION TOMADA!... REDIRECCIONANDO INTENCION");
}
//end for the code in the welcome intent
//And just here is where the empty_response
//messange is shown, and the error in the
//log of GCLOUD_PROJECT too.
//***********************************************************************
//In this one the bot search for the type
//of services if is another it activate
//another intent call OtrosServicios
function AnalizarReservaHandler(agent){
let id = agent.parameters.identidad;
let name = agent.parameters.nombre;
let date = agent.parameters.date;
let Trabajador = agent.parameters.trabajador;
let time = agent.parameters.hora;
let otros = agent.parameters.otros;
let servicio = agent.parameters.servicio;
if (servicio === 'Otro'){
let servicio = agent.parameters.otros;
agent.add(`Procesando solicitud`);
agent.setFollowupEvent({
'name': 'otroserv',
'parameters': {
'nombre': name,
'identidad': id,
'date' : date,
'servicio' : servicio,
'trabajador' : Trabajador,
'hora' : time,
}
});
return console.log("SERVICIO = OTRO");
}else{
agent.add(`Procesando solicitud`);
agent.setFollowupEvent({
'name': 'guardar',
'parameters': {
'nombre': name,
'identidad': id,
'date' : date,
'servicio' : servicio,
'trabajador' : Trabajador,
'hora' : time,
}
});
return console.log('SERVICIO NORMAL');
}
}
//End to serach for services
//***********************************************************************
//This is the same as above but with NoID appoiment
function AnalizarReservaNOIDHandler(agent){
let id = agent.parameters.identidad;
let date = agent.parameters.date;
let Trabajador = agent.parameters.trabajador;
let time = agent.parameters.hora;
let telefono = agent.parameters.telefono;
let otros = agent.parameters.otros;
let servicio = agent.parameters.servicio;
let name = agent.parameters.nombre.name;
if (servicio === 'Otro'){
let servicio = agent.parameters.otros;
agent.add(`Procesando solicitud`);
agent.setFollowupEvent({
'name': 'otroservNOID',
'parameters': {
'nombre': name,
'identidad': id,
'date' : date,
'servicio' : servicio,
'trabajador' : Trabajador,
'hora' : time,
'telefono' : telefono,
}
});
return console.log("SERVICIO = OTRO");
}else{
agent.add(`Procesando solicitud`);
agent.setFollowupEvent({
'name': 'guardarnoid',
'parameters': {
'nombre': name,
'identidad': id,
'date' : date,
'servicio' : servicio,
'trabajador' : Trabajador,
'hora' : time,
'telefono' : telefono,
}
});
return console.log('SERVICIO NORMAL');
}
}
//End to other services without ID
//*****************************************************************
//This One is to save the input for
//the client for other type of services that was not listed
function otroservicioHandler(agent){
let id = agent.parameters.identidad;
let name = agent.parameters.nombre;
let date = agent.parameters.date;
let Trabajador = agent.parameters.trabajador;
let time = agent.parameters.hora;
let servicio = agent.parameters.otros;
agent.add(`Procesando solicitud`);
agent.setFollowupEvent({
'name': 'guardar',
'parameters': {
'nombre': name,
'identidad': id,
'date' : date,
'servicio' : servicio,
'trabajador' : Trabajador,
'hora' : time,
}
});
return console.log('OTRO SERVICIO REGISTRADO');
}
//End for other service
//**************************
//the same as above but without ID
function otroservicioNOIDHandler(agent){
let id = agent.parameters.identidad;
let name = agent.parameters.nombre;
let date = agent.parameters.date;
let telefono = agent.parameters.telefono;
let Trabajador = agent.parameters.trabajador;
let time = agent.parameters.hora;
let servicio = agent.parameters.otros;
agent.add(`Procesando solicitud`);
agent.setFollowupEvent({
'name': 'guardarnoid',
'parameters': {
'nombre': name,
'identidad': id,
'date' : date,
'servicio' : servicio,
'trabajador' : Trabajador,
'hora' : time,
'telefono' : telefono,
}
});
return console.log('OTRO SERVICIO REGISTRADO');
}
//end for othr service without id
//************************************
//This is the declaration of intents
let intentMap = new Map();
intentMap.set('Guardar_Reserva', GuardarHandler);
intentMap.set('reserva_NoId', AnalizarReservaNOIDHandler);
intentMap.set('Give_id', BusquedaHandler);
intentMap.set('welcome_decision', DecisionHandler);
intentMap.set('direccion', DecisionHandler);
intentMap.set('horario', DecisionHandler);
intentMap.set('servicios', DecisionHandler);
intentMap.set('hacer_cita', DecisionHandler);
intentMap.set('reserva', AnalizarReservaHandler);
intentMap.set('Otros_servicios', otroservicioHandler);
intentMap.set('Otros_servicios_NOID', otroservicioNOIDHandler);
intentMap.set('Guardar_Reserva_NOID', GuardarNoIdHandler);
agent.handleRequest(intentMap);
});
Вот ссылки на изображения
Сообщение о проблеме, отображаемое для пользователя
Отображение предупреждения в GCloud
Это новое изображение с намерением Приветствие, где я прошу номер 4 и т. Д.
И это намерение, где бот попросить ID