dialogflow and firebase - cannot read data from firebase - firebase

Below is my fulfilment inline code
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
// initialise DB connection
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'ws://rochechatbot.firebaseio.com/',
});
process.env.DEBUG = 'dialogflow:debug';
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 handleData(agent) {
const Product_name = agent.parameters.Product_name;
agent.add('Hello');
return admin.database().ref('rochechatbot').once("value").then((snapshot) => {
var StockData = snapshot.child("Stock").val();
agent.add(StockData);
});
}
// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('StockLevelEnquiry', handleData);
agent.handleRequest(intentMap);
});
Below is my firebase DB
Below is my dialogflow, webhook is enabled
Wonder why even 'hello" is not being returned?
how to read the data from the firebase?

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?

Connecting Dialogflow to Firebase question

I have been reading around but cannot find the answer
I tried my firebase and it's not storing any data.
Here's the related inline editor
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
function angerEmotionCapture(agent) {
let angryTo = agent.parameters.angryDirectedTo;
agent.add(`love your ${angryTo},dude`);
return db.collection('directedTo').add({directedTo: angryTo});
}
Here's my firebase database
Any help will be greatly appreciated, thanks!
Please have a look into the following sample code showing how to connect Firebase's Firestore database to Dialogflow fulfillment hosting on Firebase functions:
'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) {
// Get parameter from Dialogflow with the string to add to the database
const databaseEntry = agent.parameters.databaseEntry;
// Get the database collection 'dialogflow' and document 'agent' and store
// the document {entry: "<value of database entry>"} in the 'agent' document
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.`);
});
}
// Map from Dialogflow intent names to functions to be run when the intent is matched
let intentMap = new Map();
intentMap.set('WriteToFirestore', writeToDb);
agent.handleRequest(intentMap);
});
Have a look into the Dialogflow's Firestore GitHub example

Unable to fetch data from firestore database

I am working on a dialogflow agent and using fulfillment to fetch data from the firestore.
I have a firestore collection called Users which has name and location fields. But am getting the error which causes the fetching of data to fail.
Warning, estimating Firebase Config based on GCLOUD_PROJECT.
Initializing firebase-admin may fail
The fulfillment code for the agent is as follows
'use strict';
const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion } = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
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));
var name='';
var location='';
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
function getUserDetails(agent)
{
name= agent.parameters.name;
location=agent.parameters.location;
console.log("buyer name is " + name);
db.collection("Users").doc("101").set({
name: name,
location:location});
agent.add(`User has been inserted`);
}
intentMap.set('Buy Car', getUserDetails);
agent.handleRequest(intentMap);
})
This form of initialization for the Firebase Admin SDK is deprecated:
admin.initializeApp(functions.config().firebase);
You should initialize like this instead:
admin.initializeApp();

Unable to Access Firestore Document Within a Firestore Cloud Function

Issue: Type Error
I setup a Firestore Cloud Function to call from my Android app which is being called as expected, however I am unable to access a Firestore document from within the method and receiving a TypeError in the logs.
Attempted Solutions
functions.firestore().document('qa/content/feeds/main/content/'+contentTitle)
functions.firestore().ref('qa/content/feeds/main/content/'+contentTitle)
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();
const MAIN_FEED_TYPE = "MAIN";
const SAVED_FEED_TYPE = "SAVED";
const ARCHIVED_FEED_TYPE = "ARCHIVED";
const SAVE_USER_ACTION = "SAVE";
const ARCHIVE_USER_ACTION = "ARCHIVE";
const SAVED_PATH = "saved"
const ARCHIVED_PATH = "archived"
exports.updateQualityScore = functions.https.onCall((data, context) => {
const environment = data.environment
const feedType = data.feedType
const action = data.action
const contentTitle = data.contentTitle
const uid = context.auth.uid;
var feedTypePath
if (feedType === SAVED_FEED_TYPE) {
feedTypePath = SAVED_PATH
} else if (feedType === ARCHIVED_FEED_TYPE) {
feedTypePath = ARCHIVED_PATH
}
admin.firestore().ref('qa/content/feeds/main/content/'+contentTitle)
.get().then(function(doc) {
console.log('Trigger fired on content: '
+ contentTitle + " | user: " + uid
+ " | action: " + action + ' | feedType: ' + feedType);
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
console.log("No such document!");
}
return {
status: 'Get content success.'
}
}).catch(function(error) {
console.log("Error getting document:", error);
return {
status: 'Get content error.'
}
});
});
Firestore doesn't have a ref() method. Realtime Database does. You're probably confusing the two.
With Firestore, you deal with collections and documents, and there are different methods to get a hold of collection and document references. Maybe you meant to use the doc() method instead, like this?
admin.firestore().doc('qa/content/feeds/main/content/'+contentTitle)
Sorry wrong answer.
You need to pass credential when initializing app.
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
or
admin.initializeApp({
credential: admin.credential.cert({
projectId: '<PROJECT_ID>',
clientEmail: 'foo#<PROJECT_ID>.iam.gserviceaccount.com',
privateKey: '-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n'
}),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});
initialize the sdk
Quick Start

Firebase cloud function / notification

I am trying to make a notification function to deploy using cloud functions of firebase
I did the first part of the code and it was successfully done which is:
'use-strict'
const functions = require('firebase-functions');
//const paypal=require('paypal-rest-sdk');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification=functions.firestore
.document("Users/{user_id}/Notifications/{notification_id}")
onWrite((change, context)=>{
const user_id=context.params.user_id;
const notification_id=context.params.notification_id;
});
without returning promise and it was ok but when i tried to complete like this:
'use-strict'
const functions = require('firebase-functions');
//const paypal=require('paypal-rest-sdk');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification=functions.firestore
.document("Users/{user_id}/Notifications/{notification_id}")
.onWrite((change, context)=>{
const user_id=context.params.user_id;
const notification_id=context.params.notification_id;
return admin.firestore().collection("Users").doc(user_id)
.collection("Notifications")
.doc(notification_id)
.get()
.then(queryResult=>{
const from_user_id=queryResult.data().from;
const from_data=admin.firestore()
.collection("Users").doc(from_user_id).get();
const to_data=admin.firestore().collection("Users")
.doc(user_id).get();
return Promise.all([from_data,to_data]).then(result=>{
const from_name=result[0].data().name;
const to_name=result[1].data().name;
console.log("from :"+from_name+"TO"+to_name);
});
});
// console.log("user_id"+ user_id+ "notification_id"+notification_id);
});
I have these 2 errors in node.cm:
1-Avoid nesting promises
2-each then()should return a value
how can i fix this problem???
Send push notification through FCM and cloud function when a change in Firestore database
You can try like this
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.firestore
.document('/users/{documentId}')
.onWrite((change, context) => {
console.log("CHANGE in DOCUMENT ID : " + context.params.documentId);
// Fetch data using standard accessors
const userId = change.after.data().userId;
const ownerId = change.after.data().ownerId;
console.log('We have a new request UID:', userId, 'for owner:', ownerId);
const owner_data = admin.firestore().collection('users').doc(ownerId).get();
const user_data = admin.firestore().collection('users').doc(userId).get();
return Promise.all([owner_data, user_data]).then(result => {
const ownerFCMToken = result[0].data().fcmToken;
const userName = result[1].data().displayName;
console.log("OWNER Token : " + ownerFCMToken + " USER: " + userName);
const payload = {
notification: {
title: 'Test title!',
body: `${userName} sent you a following request.`
// icon: follower.photoURL
}
};
admin.messaging().sendToDevice(followedFCMToken, payload)
.then(function (response) {
console.log("Push response : " + response);
return response
})
.catch(function (error) {
console.error("Error in sending push");
});
});

Resources