How to connect Realtime Database firebase with dialogflow chatbot - firebase

I want to connect Realtime database firebase with Dialogflow chatbot and how to get some data from Realtime database firebase using Dialogflow. I want when the user ask my chatbot to show the machine water quantity then chatbot will ask for the machine id of which you want to know water quantity, then chatbot access the realtime database firebase to check if the machine is present in database then it will show the water quantity of that machine.
I have tried to connect realtime database firebase this way-
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const firebaseAdmin=require("firebase-admin");
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
firebaseAdmin.initializeapp({
credential:firebaseAdmin.credential.applicationDefault(),
databaseURL:"ws://rtdb.asia-southeast1.firebasedatabase.app/",
});
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));
function welcome(agent) {
agent.add(`Welcome to Akvo chat!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
//function getFromFirebase(agent){
//return firebaseAdmin.database().ref("board_id").once("value", snapshot=>{
//var boardid=snapshot.val();
//agent.add(boardid);
//});
//}
// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
//intentMap.set('board id', getFromFirebase);
agent.handleRequest(intentMap);
});
But it shows an error.
Error: " Error happened during Cloud Functions Deployment "
can you please tell me how to do this.

Related

dialogflow es fulfillment cannot connect to firebase

I had followed the video (link) to connect firebase to dialogflow, but there had some errors that I can’t realized.
I followed the video
My problem is dialogflow always shows
「Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500.」
Firebase show
「Error : No handler for requested intent」
「Error : Process exited with code 16」
「Error : No handler for requested intent」
「Error : Process exited with code 16」
This is my firebase
firebase realtime image
This is my fulfillment
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const firebaseAdmin = require("firebase-admin");
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
firebaseAdmin.initializeApp({
credential:firebaseAdmin.credential.applicationDefault(),
databaseURL:'ws://coherent-lock-376605-default-rtdb.asia-southeast1.firebasedatabase.app/',
});
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));
function welcome(agent) {
var dateTime = new Date();
agent.add(`HIHI! The time is :` + dateTime);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function getFromFirebase(agent){
return firebaseAdmin.database().ref('address').once("value").then((snapshot) =>{
var address = snapshot.child().val();
agent.add('hey! the address is :'+address);
});
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('地址', getFromFirebase);
// intentMap.set('your intent name here', googleAssistantHandler);
agent.handleRequest(intentMap);
});
Can anyone help me to solve it?

Dialogflow - Fulfillment Inline Editor(Firebase) is timeout

I am testing with Dialogflow using Firebase project.
The Firebase Project is already used as an android backend. (Firestore)
Now, I am trying to attach chatbot.
This github code is what I want.
I create a new Dialogflow Agent, it refers to the Firebase project.
Enable Fullfillment Inline Editor, and I copy&paste a code from upper github code.
'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 });
function writeToDb (agent) {
const databaseEntry = agent.parameters.databaseEntry;
const dialogflowAgentRef = db.collection('dialogflow').doc('agent');
return db.runTransaction(t => {
t.set(dialogflowAgentRef, {entry: databaseEntry});
return Promise.resolve('Write complete');
}).then(doc => {
agent.add(`Wrote "${databaseEntry}" to the Firestore database.`);
}).catch(err => {
console.log(`Error writing to Firestore: ${err}`);
agent.add(`Failed to write "${databaseEntry}" to the Firestore database.`);
});
}
let intentMap = new Map();
intentMap.set('WriteToFirestore', writeToDb);
agent.handleRequest(intentMap); // Here is index.js:51
});
This is very simple.
It just writes a text into the Firestore.
That's all.
I deployed this fulfillment and linked to an Intent.
In case of first conversation after deploy, I can find below log in Firebase Cloud Functions.
Error: No handler for requested intent
at WebhookClient.handleRequest (/user_code/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:317:29)
at exports.dialogflowFirebaseFulfillment.functions.https.onRequest (/user_code/index.js:51:9)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)
And after some times, when I retry again, I can find below logs in the Firebase Cloud Functions.
dialogflowFirebaseFulfillment - Function execution took 60002 ms, finished with status: 'timeout'
I don't know what I am missing...
It was my fault.
The key of intentMap should be same with Intent name.
After I fix it, it works fine.

How to retrieve image from firebase storage by dialogflow chat bot?

I need to retrieve image from firebase storage via my dialogflow chatbot google assistant. I already uploaded the image to storage and add the http link to firebase cloud database. If I ask "show my photo" to google assistant(test app), it should receive image response from firebase. I already enable webhook in dialogflow and using index.js file for coding.
Please help me to add code for image retrieving.
Fill up the code here
case 'photo.database':
Please fill the code here.
break;
Existing code
const functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var firestore = admin.firestore();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
exports.MyInformation = functions.https.onRequest((request, response) => {
console.log("request.body.result.parameters: ",
request.body.result.parameters);
let params = request.body.result.parameters;
switch (request.body.result.action) {
case 'write.database':
firestore.collection(${params.name}).doc(${params.document}).set(params)
.then(() => {
if((params.name) === Riyas Elliyas){
response.send({
speech:Your database has been updated with ${params.document} -
${params.content}
});
}
else{
response.send({
speech:Database of ${params.name} has been updated with ${params.document} -
${params.content}
});
}
})
.catch((e => {
console.log("error: ", e);
response.send({
speech: "something went wrong when writing on database"
});
}))
break;
case 'photo.database':
*** Imaging retrieving code is here ***
break;
default:
response.send({
speech: "no action matched in webhook"
});
}
});

Flutter: Firebase Pushnotification On Data Change

After getting the comment, i have deployed this folowing code to my firebase project and it was successfully deploed!.But there is no notifications been send to me.
Please check my Firebase Realtime database Screenshot here for better understanding.
[ITS SOLVED NOW:IT WILL SEND NOTIFICATIONS TO ONLY ONE ID ie My Admin Device]
WORKING CODE:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firbase);
exports.codeformypeople = functions.database.ref('items/{id}').onWrite(evt => {
const payload = {
notification: { title: 'New Customer Requested', body: 'Touch to Open The App', badge: '1', sound: 'default', }
};
const token ="Lsn-bHfBWC6igTfWQ1-h7GoFMxaDWayKIpWCrzC";//replace with ur token
if (token) {
console.log('Toke is availabel .');
return admin.messaging().sendToDevice(token, payload);
} else {
console.log('token error');
}
});
[
SEE THIS VIDEO LINK FOR MORE DETAILS
note:If your app is opened and minmized then it will show notification,but if the app is opened and you are using,or if the app is terminated force close then it will not work!!
You can use firebase cloud function to trigger notification. Here is snippet of cloud functions which i am using to trigger notification:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotification = functions.database.ref('/Notifications/{pushId}')
.onWrite(( change,context) => {
console.log("Push Notification event triggered");
var request = change.after.val();
var payload = {
data:{
username: request.userName,
}
};
admin.messaging().sendToDevice(request.userTokenId, payload)
.then(function(response){
console.log("Successfully sent message: ",response);
console.log(response.results[0].error);
})
.catch(function(error){
console.log("Error sending message: ", error)
})
})
Below i have provided my notification structure, you can see below.This function will trigger if any new data is being pushed in database notification node. To see what is output/error you are getting when this function is trigger go to firebase admin panel > Functions > Logs.
You have deployed function code perfectly, but you forgot to add refresh tokenId in your database as you can see in above picture i am saving userTokenId in my database and in function admin.messaging().sendToDevice(request.userTokenId, payload) i am using that tokenId, this tokenId is used to send notification to particular device, you can get this tokenId using FirebaseInstanceId.getInstance().getToken() and save this in your fbproject1 > items database sturcture. please refer this & this

dialogflow to interact with firebase realtime database

Is it possible to get some data from firebase database by using dialogflow? I'm new to dialogflow so I'm still doing some research about.
For example, I want to ask my chatbot if a doctor is available then chatbot will access the firebase db to check if that specific doctor is available or lets say schedule me an appoint with doc X so dialogflow will do a function that allow will enter a schedule object to the database
thanks.
You can use Firebase function to fulfill your Dialogflow agent and the Firestore database to store data. An example of how to do so with Dialogflow's Google Assistant integration is below:
const functions = require('firebase-functions');
const firebaseAdmin = require('firebase-admin');
const DialogflowApp = require('actions-on-google').DialogflowApp;
// Initialize Firebase Admin SDK.
firebaseAdmin.initializeApp(functions.config().firebase);
exports.dialogflowFulfillment = functions.https.onRequest((req, res) => {
// Log headers and body
console.log('Request headers: ' + JSON.stringify(req.headers));
console.log('Request body: ' + JSON.stringify(req.body));
// Create a new Dialgoflow app request handler
let app = new DialogflowApp({request: req, response: res});
// welcome function handler
function start(app) {
// Get user ID from the Google Assistant through Action on Google
let userId = app.getUser().userId;
// Check if the user is in our DB
admin.firestore().collection('users').where('userId', '==', userId).limit(1).get()
.then(snapshot => {
let user = snapshot.docs[0]
if (!user) {
// If user is not in DB, its their first time, Welcome them!
app.ask('Welcome to my app for the first time!');
// Add the user to DB
firebaseAdmin.firestore().collection('users').add({
userId: userId
}).then(ref => {
console.log('Added document with ID: ', ref.id);
});
} else {
// User in DB
app.ask('Welcome back!')
}
});
}
// Map function hanlder to Dialogflow's welcome intent action 'input.welcome'
const actionMap = new Map('input.welcome', start)
app.handleRequest(actionMap);
});

Resources