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.
Related
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.
I have the following function in my index.ts file:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
const fcm = admin.messaging();
export const sendToDevice = functions.firestore
.document('orders/{orderId}')
.onCreate(async snapshot => {
print("aa")
console.log("osakosak");
const order = snapshot.data();
const querySnapshot = await db
.collection('users')
.doc(order.ustaID)
.collection('tokens')
.get();
const tokens = querySnapshot.docs.map(snap => snap.id);
const payload: admin.messaging.MessagingPayload = {
notification: {
title: 'New Order!',
body: `you sold a ${order.day} for ${order.time}`,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
};
return fcm.sendToDevice(tokens, payload);
});
However, when the new document gets added into the order collection, this doesn't get triggered. Even the print and console.log don't work. I tried putting print and console log before export, and it still didn't fire.
Based on your comments ("It depends on cloud_firestore in pubspec.yaml"), it seems that you didn't deploy your Cloud Function correctly.
As a matter of fact, Cloud Functions are totally independent from your Flutter app (your front-end). It is a back-end service. You should deploy it with the Firebase CLI, see the doc. Note that the code shall be in the Firebase Project, not in your Flutter project.
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
I want to update or creat an object, but i have this error :"TypeError: functions.database is not a function" on the registry of firebase function
this is my code:
const functions = require('firebase-functions');
exports.actualizar = functions.https.onRequest((request, response) => {
const obj = request.body;
const MAC = obj.MAC;
functions.database().ref ('/sensores/{MAC}').update(obj).promise.then(() =>
{
console.log("UpDate Success");
return req.status(200).send("ok");
})
.catch(() => {
functions.database.ref('/sensores'). set(obj).promise.then(() =>{
console.log ("Created Succces");
return req.status(200).send("");
})
.catch(() =>{
console.log("Error");
return req.status(500).send("error");
})
})
});
You can't use the Cloud Functions for Firebase SDK to query the database. It's just used for building the function definition. To query your database or other Firebase products, you need to use the Firebase Admin SDK, or whatever SDK is normally used to do so.
For example, you will see lots of official sample code that starts like this:
const admin = require('firebase-admin'); // this is the Admin SDK, not firebase-functions
admin.initializeApp();
// Then use "admin" to reach into Realtime Database, Firestore, Cloud Storage, etc.
Quick question. Long story short, I am getting this error in my google cloud functions log:
Firestore (4.10.1): Could not reach Firestore backend.
Here is my code in my functions file:
// pull in firebase
const firebase = require('firebase');
// required
require("firebase/firestore");
// initialize firebase
const firebaseApp = firebase.initializeApp({
// Firebase configuration.
apiKey: "<Key Here>",
authDomain: "<Auth Domain>",
databaseURL: "<database url>",
projectId: "<project id>",
storageBucket: "<storage bucket>",
messagingSenderId: "<messaging sender id>"
});
// setup the firestore
var fs = firebaseApp.firestore();
exports.search = functions.https.onRequest((request, response) => {
cors(request, response, () => {
// set a reference to the foo table in firestore
var docRef = fs.collection("foo");
// check for the foo in the firestore
docRef.where('bar', '==', <something>).get().then(function(doc) {
if (!doc.docs) {
return db.collection("foo").add({
bar: <something>
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
});
});
});
At this point I am stuck. As far as I can tell, I have things set up, but maybe not? I have searched the docs and googled the issue, without much success. Do you see anything wrong?
All right. So the answer to my question is that I was not being very smart. A big thank you to Taha Azzabi for pointing me in the right direction. It turns out my problem was here:
docRef.where('bar', '==', <something>).get().then(function(doc) {
if (!doc.docs) {
return db.collection("foo").add({
bar: <something>
})
This would never work. My query was correct, but the check on doc.docs was incorrect. My code is now:
// setup the firestore
const fs = firebase.firestore();
// set a reference to the document for the searched summoner
var docRef = fs.collection("bars").doc("snickers");
// check for the bar in the firestore
return docRef.get()
.then(function(doc) {
if (!doc.docs) {
return fs.collection("bars").doc("snickers").set({
name: "snickers"
})
.then(function(reference) {
console.log("Document written");
return response.status(200).send('');
})
This is what I was looking for so I am good to go. Long story short, I was grabbing a collection of results then trying to check to see if a single result existed. What I needed to do was grab a single doc from the firestore and from there check to see if the single doc existed. However, the error:
Firestore (4.10.1): Could not reach Firestore backend.
Didn't really do a very good job at pointing me in that direction.
Did you install the Firebase CLI ?
npm install -g firebase-tools
Did you log in to the Firebase console through the CLI ?
firebase login
Did you initialize Firebase Cloud Functions ?
firebase init functions
You don't need then to reinitialize the app, initialize an admin app instance,thought.
Here's an example hope that will help
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
//trigger a function to fire when new user document created
exports.createUser = functions.firestore
.document('users/{userId}')
.onCreate(event => {
// perform desired operations ...
});
to deployer your functions
firebase deploy --only functions
read more here https://firebase.google.com/docs/functions/get-started