Problem with sending Push-notification from Firebase to my WordPress-PWA - wordpress

I want a scheduled task. This task gets Temperature Values from my Thinkspeakaccount. If the temperature is below 5 degrees the function sends a message to my WordPress PWA. The code doesn't work. I don't get the problem.
Does anyone now a good tutorial for this problem?
(In WP I use a Plugin which is connect to firebase)
admin.initializeApp({
credential: admin.credential.cert({
"type": "service_account",
"project_id": "XX",
"private_key_id": "XX",
"private_key": "XX",
"client_email": "XX",
"client_id": "XX",
"auth_uri": "XX",
"token_uri": "XX",
"auth_provider_x509_cert_url": "XXX",
"client_x509_cert_url": "hXX"
}),
databaseURL: "XX"
});
const functions = require('firebase-functions');
const axios = require('axios');
exports.checkTemperature = functions.pubsub.schedule('\*/2 \* \* \* \*').onRun(async () = \ > {
try {
const response = await axios.get('https://api.thingspeak.com/channels/XXX/feeds.json?api_key=XXX&results=1&timezone=Europe%2FBerlin');
const temperature = response.data.feeds\[0\].field1;
if (temperature\ < 8) {
const payload = {
notification: {
title: 'Temperature Alert',
body: `Temperature is below 5 degrees: ${temperature}`,
}
};
return admin.messaging().sendToTopic('\<topic_name\>', payload);
}
} catch (error) {
console.error(error);
}
});
When I want to upload the code to firebase I get in firebase a warning

Related

Code problem in DialogFlow Fulfillment as it does not recognize Firebase asynchronous functions

I'm having problems because the code I made in the DialogFlow Fulfillment index.js when I took the context parameters he was unable to send talking to the DialogFlow support I was informed that the DialogFlow Fulfillment does not recognize asynchronous functions so when I use the "push" from Firebase to send the parameters he doesn't send anything I believe he expects some parameter from the context but because he doesn't receive it he skips the push function and ends up not executing and doesn't send anything.
DialogFlow Fulfillment index.js code:
const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion } = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'https://testechatbot-2020.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 Mensagem(agent) {
var context = agent.context.get('awainting_nome');
var nome = context.parameters.nome;
var mensagem = agent.parameters.mensagem;
let teste = nome + " " + mensagem;
try {
admin.database().ref('Dados/').push({
Nome: nome,
Mensagem: mensagem
});
} catch (err) {
console.error(err);
return;
}
}
let intentMap = new Map();
intentMap.set('EntradaMensagem', Mensagem);
agent.handleRequest(intentMap);
});
DialogFlow Fulfillment package.json code:
{
"name": "dialogflowFirebaseFulfillment",
"description": "Fluxo com envio de parametros para o Firebase",
"version": "1.0.0",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"esversion": 8,
"engines": {
"node": ">=10.0.0"
},
"scripts": {
"start": "firebase serve",
"deploy": "firebase deploy"
},
"dependencies": {
"#google-cloud/firestore": "^0.16.1",
"firebase-admin": "^8.13.0",
"actions-on-google": "^2.2.0",
"firebase-functions": "^3.7.0",
"dialogflow": "^1.2.0",
"dialogflow-fulfillment": "^0.6.0",
"#google-cloud/dialogflow": "^3.0.0",
"node-fetch": "^2.6.0"
}
}
Image with response from DialogFlow support about asynchronous functions
response from DialogFlow support
I'm not sure where you heard that the Intent Handler can't support async functions. They most certainly can. If you're using an async function (or a function that returns a Promise - same thing), you either must declare it an async function or return the Promise.
Your handler function should look something more like
function Mensagem(agent) {
var context = agent.context.get('awainting_nome');
var nome = context.parameters.nome;
var mensagem = agent.parameters.mensagem;
let teste = nome + " " + mensagem;
return admin.database().ref('Dados/').push({
Nome: nome,
Mensagem: mensagem
})
.then( snapshot => {
agent.add( "pushed" );
})
.catch (err => {
console.error(err);
agent.add( "Error." );
})
}

In Firebase Functions showing Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail - error message

I do receive an error message while deploying.
In Firebase Functions showing Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail
I have already define all the apikey etc but the database is not linked dialogflow.
Please advise.
const functions = require('firebase-functions');
var config = {
apiKey: xxxxx,
authDomain: xxxxx,
databaseURL: xxxxx,
projectId: xxxxx,
storageBucket: xxxxx,
messagingSenderId: xxxxx,
;// your config object could be differ
const admin = require('firebase-admin');
admin.initializeApp(config);
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
const db = admin.database();
const action = request.body.queryResult.action;
if (action === 'product_description') {
const product = request.body.queryResult.parameters.Products.trim();
const ref = db.ref(`products/${product.toLowerCase()}/description`);
ref.once('value').then((snapshot) => {
const result = snapshot.val();
if (result === null) {
response.json({
fulfillmentText: `Product does not exists in inventory`
});
return;
}
response.json({
fulfillmentText: `Here is the description of ${product}: ${result}`,
source: action
});
}).catch((err) => {
response.json({
fulfillmentText: `I don't know what is it`
});
});
} else if(action === 'product_quantity') {
const product = request.body.queryResult.parameters.Products.trim();
const ref = db.ref(`products/${product.toLowerCase()}`);
ref.once('value').then((snapshot) => {
const result = snapshot.val();
if (result === null) {
response.json({
fulfillmentText: `Product does not exists in inventory`
});
return;
}
if (!result.stock) {
response.json({
fulfillmentText: `Currently ${product} is out of stock`,
source: action
});
} else {
response.json({
fulfillmentText: `We have ${result.stock} ${product} in stock`,
source: action
});
}
}).catch((err) => {
response.json({
fulfillmentText: `I don't know what is it`
});
});
} else {
response.json({
fulfillmentText: `I don't know what is it`
});
}
});`
This is the my package.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": {
"actions-on-google": "^2.12.0",
"firebase-admin": "^8.8.0",
"firebase-functions": "^3.3.0",
"dialogflow": "^0.12.1",
"dialogflow-fulfillment": "^0.6.1"
}
}

Firebase messaging, message not recieved

My cloud function states it has sent a message successfully undefined messages were sent successfully but I don't receive it:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
var serviceAccount = require("./config.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://pushmessage-bd1eb.firebaseio.com"
});
const messaging = admin.messaging();
const message = {
data: { title: "Testing", body: "Test" },
token:
"fm8hZocb9X0:APA91bGANY8U1k7iXSAofh8PEtyA3SfkAvyvicjHbSzDC7s1DwzhCxBBhj5oeAhiZpNLFC1wUHOPX_C0vlGtUMv882EXxBjsM4qeBpFndka8kzir9kgmJnuPTRImx2cxUT53oXzJuAzB"
};
messaging.send(message).then(response => {
console.log(
response.successCount + " messages were sent successfully"
);
});
If I use the same token in the firebase dashboard to send a message, the message sends successfully.
How can I get my cloud function to send a message?
config.json:
{
"type": "service_account",
"project_id": "pushmessage-bd1eb",
"private_key_id": "xxx",
"private_key": "-----BEGIN PRIVATE KEY-----\nxxx-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-8dd2o#pushmessage-bd1eb.iam.gserviceaccount.com",
"client_id": "xxx",
"senderID": "388436954224",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-8dd2o%40pushmessage-bd1eb.iam.gserviceaccount.com"
}
Are you using admin.messaging().send()?
See:
https://firebase.google.com/docs/reference/admin/node/admin.messaging.Messaging#send
https://firebase.google.com/docs/reference/admin/node/admin.messaging.Message
https://firebase.google.com/docs/reference/admin/node/admin.messaging.Notification
Please try the following code.
Change data to notification.
And the admin.messaging().send() return string.
const message = {
notification: { title: "Testing", body: "Test" },
token:
"The registration token here"
};
admin.messaging().send(message).then(response => {
console.log(
response + " messages were sent successfully"
);
});
Or you can use admin.messaging().sendToDevice().
See:
https://firebase.google.com/docs/reference/admin/node/admin.messaging.Messaging#sendToDevice
https://firebase.google.com/docs/reference/admin/node/admin.messaging.MessagingPayload
https://firebase.google.com/docs/reference/admin/node/admin.messaging.MessagingDevicesResponse
Please try the following code.
const token= "The registration token here";
const payload = {
notification: { title: "Testing", body: "Test" }
};
admin.messaging().sendToDevice(token, payload).then(response => {
console.log(
response.successCount + " messages were sent successfully"
);
});

FirebaseMessaging callback not triggered while sending notification from cloud functions

client side code
final FirebasebaseMessaging _firebaseMessaging = new FirebaseMessaging();
_firebaseMessaging.configure(onMessage: (Map<String,dynamic> notification){
print("onMessage : $notification");
}, onResume: (Map<String,dynamic> notification){{
print("onResume: $notification");
}}, onLaunch: (Map<String,dynamic> notification){
print("onLaunch: $notification");
});
_firebaseMessaging.getToken().then((String token){
print("token is : $token");
});
server side
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var db = admin.firestore();
const payload = {
"notification": {
"body": postingUserDocumentSnapshot.data()['username'] + " commented on your post",
"title": "You got a comment",
"sound": 'enabled',
},
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"senderId": postingUserDocumentSnapshot.data()['userId'],
"postID": context.params.postId,
"notificationType": "COMMENT",
},
};
admin.messaging().sendToDevice(receiverMessagingToken, payload);
I do receive notification in the system tray but the firebaseMessaging callbacks are not triggered. However if i send notification from google console those callbacks are triggered.
Can anyone explain me or suggest me on why those callbacks are not triggered while sending notification via admin.messaging().sendToDevice?

Why Does FireFox Trigger OnMessage() sometimes and does not trigger the other time, while using FCM

While Using FCM when a notification is send against token for firefox browser , the messaging.onMessage function gets called sometimes and not for the other times.
I really Can't Understand what is the issue
My JS Code is:-
var config = {
apiKey: "my api key",
authDomain: "my auth domain",
databaseURL: "my db url",
projectId: "my proj id",
storageBucket: "my stirage bucket url",
messagingSenderId: "my msging sender ID"
};
firebase.initializeApp(config);
var messaging = firebase.messaging();
messaging.requestPermission()
.then(function () {
console.log('Notification permission granted.');
messaging.getToken()
.then(function(token){
console.log(token)
})
.catch(function (error) {
console.log('Unable to generate Token')
})
})
.catch(function (err) {
console.log('Unable to get permission to notify.', err);
})
messaging.onMessage(function (payload) {
console.log(payload.notification.body);
})
my json for notification is:-
{
"notification": {
"title": "My Title",
"body": "My Message",
"icon": "",
"click_action": ""
},
"to": "token"
}

Resources