Using Google Assistant Change Firebase Database Value - firebase-realtime-database

I Created a android app in which if a press a button and value changes in Firebase database (0/1) , i want to do this using google assistant, please help me out, i searched out but didn't found any relevant guide please help me out

The code to do this is fairly straightforward - in your webhook fulfillment you'll need a Firebase database object, which I call fbdb below. In your Intent handler, you'll get a reference to the location you want to change and make the change.
In Javascript, this might look something like this:
app.intent('value.update', conv => {
var newValue = conv.prameters.value;
var ref = fbdb.ref('path/to/value');
return ref.set(newValue)
.then(result => {
return conv.ask(`Ok, I've set it to ${newValue}, what do you want to do now?`);
})
.catch(err => {
console.error( err );
return conv.close('I had a problem with the database. Try again later.');
});
return
});
The real problem you have is what user you want to use to do the update. You can do this with an admin-level connection, which can give you broad access beyond what your security rules allow. Consult the authentication guides and be careful.

I am actually working on a project using Dialogflow webhook and integrated Firebase database. To make this posible you have to use the fulfilment on JSON format ( you cant call firebasedatabase in the way you are doing)
Here is an example to call firebase database and display a simple text on a function.
First you have to take the variable from the json.. its something loike this (on my case, it depends on your Entity Name, in my case it was "tema")
var concepto = request.body.queryResult.parameters.tema;
and then in your function:
'Sample': () => {
db.child(variable).child("DESCRIP").once('value', snap => {
var descript = snap.val(); //firebasedata
let responseToUser = {
"fulfillmentMessages": [
{ //RESPONSE FOR WEB PLATFORM===================================
'platform': 'PLATFORM_UNSPECIFIED',
"text": {
"text": [
"Esta es una respuesta por escritura de PLATFORM_UNSPECIFIED" + descript;
]
},
}
]
}
sendResponse(responseToUser); // Send simple response to user
});
},
these are links to format your json:
Para formatear JSON:
A) https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/Shared.Types/Platform
B) https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/Shared.Types/Message#Text
And finally this is a sample that helped a lot!!
https://www.youtube.com/watch?v=FuKPQJoHJ_g
Nice day!

after searching out i find guide which can help on this :
we need to first create chat bot on dialogflow/ api.pi
Then need to train our bot and need to use webhook as fullfillment in
response.
Now we need to setup firebase-tools for sending reply and doing
changes in firebase database.
At last we need to integrate dialogflow with google assistant using google-actions
Here is my sample code i used :
`var admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
var database = admin.database();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.hello = functions.https.onRequest((request, response) => {
let params = request.body.result.parameters;
database.ref().set(params);
response.send({
speech: "Light controlled successfully"
});
});`

Related

Send the parsed intent and slots back to the client from Amazon-Lex

Amazon Lex FAQ's mention that we can send the parsed intent and slots back to the client, so that we can place the business logic in the client. But am unable to find anything clear on this in the Lex documentation.
My use case:
Send text/voice data to Amazon lex, lex then parses the intent and slots and sends back the JSON with intent, slot and context data back the client which requested it, rather than sending it to Lambda or other backend API endpoint.
Can anyone please point out the right way/configuration for this?
Regards
If I'm understanding you correctly, you want your client to receive the LexResponse and handle it within the client rather than by Lambda or backend API. If this is correct, you can try the following implementation of Lex-Audio.
// This will handle the event when the mic button is clicked on your UI.
scope.audioClick = function () {
// Cognito Credentials for Lex Runtime Service
AWS.config.credentials = new AWS.CognitoIdentityCredentials(
{ IdentityPoolId: Settings.AWSIdentityPool },
{ region: Settings.AWSRegion }
);
AWS.config.region = Settings.AWSRegion;
config = {
lexConfig: { botName: Settings.BotName }
};
conversation = new LexAudio.conversation(config, function (state) {
scope.$apply(function () {
if (state === "Passive") {
scope.placeholder = Settings.PlaceholderWithMic;
}
else {
scope.placeholder = state + "...";
}
});
}, chatbotSuccess
, function (error) {
audTextContent = error;
}, function (timeDomain, bufferLength) {
});
conversation.advanceConversation();
};
The success function which is called after Lex has responded is as follows:
chatbotSuccess = function (data) {
var intent = data.intent;
var slots = data.slots;
// Do what you need with this data
};
Hopefully that gives you some idea of what you need to do. If you need the reference for Lex-Audio, there's a great post about it on the Amazon Blog which you should go check out:
https://aws.amazon.com/blogs/machine-learning/capturing-voice-input-in-a-browser/

Detect if firebase records are deleted by admin or stop delete events [duplicate]

In the example below, is there a way to get the uid of the user who wrote to /messages/{pushId}/original?
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
.onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
const original = event.data.val();
console.log('Uppercasing', event.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return event.data.ref.parent.child('uppercase').set(uppercase);
});
UPDATED ANSWER (v1.0.0+):
As noted in #Bery's answer above, version 1.0.0 of the Firebase Functions SDK introduced a new context.auth object which contains the authentication state such as uid. See "New properties for user auth information" for more details.
ORIGINAL ANSWER (pre v1.0.0):
Yes, this is technically possible, although it is not currently documented. The uid is stored with the event.auth object. When a Database Cloud Function is triggered from an admin situation (for example, from the Firebase Console data viewer or from an Admin SDK), the value of event.auth is:
{
"admin": true
}
When a Database Cloud Function is triggered from an unauthenticated reference, the value of event.data is:
{
"admin": false
}
And finally, when a Database Cloud Function is triggered from an authed, but not admin, reference, the format of event.auth is:
{
"admin": false,
"variable": {
"provider": "<PROVIDER>",
"provider_id": "<PROVIDER>",
"user_id": "<UID>",
"token": {
// Decoded auth token claims such as sub, aud, iat, exp, etc.
},
"uid": "<UID>"
}
}
Given the information above, your best bet to get the uid of the user who triggered the event is to do the following:
exports.someFunction = functions.database.ref('/some/path')
.onWrite(event => {
var isAdmin = event.auth.admin;
var uid = event.auth.variable ? event.auth.variable.uid : null;
// ...
});
Just note that in the code above, uid would be null even if isAdmin is true. Your exact code depends on your use case.
WARNING: This is currently undocumented behavior, so I'll give my usual caveat of "undocumented features may be changed at any point in the future without notice and even in non-major releases."
Ever since Firebase functions reached version 1.0, this behavior is no longer undocumented but has sligtly changed. Be sure to read the docs.
Context has been added to cloud functions and you can use it like this
exports.dbWrite = functions.database.ref('/path/with/{id}').onWrite((data, context) => {
const authVar = context.auth; // Auth information for the user.
const authType = context.authType; // Permissions level for the user.
const pathId = context.params.id; // The ID in the Path.
const eventId = context.eventId; // A unique event ID.
const timestamp = context.timestamp; // The timestamp at which the event happened.
const eventType = context.eventType; // The type of the event that triggered this function.
const resource = context.resource; // The resource which triggered the event.
// ...
});

Atomic update of Realtime Database from Google Cloud Functions

I use Google Cloud Functions to create an API endpoint for my users to interact with the Realtime Database.
The problem I have is that I'm not sure how the code works. I have a helper function doSomething that I need to call only once, but I have a suspicion that there are cases where it can be called twice or possibly more (when multiple users call the API at the same time and the update operation hasn't been processed by the DB yet). Is it possible? Does it mean I need to use a transaction method? Thank you!
DB structure
{
somePath: {
someSubPath: null
}
}
Google Cloud Functions code
const functions = require('firebase-functions')
const admin = require('firebase-admin')
const cors = require('cors')({origin: true});
admin.initializeApp(functions.config().firebase)
// API ENDPOINT
exports.test = functions.https.onRequest((req, res) => {
cors(req, res, () => {
admin.database().ref('/somePath/someSubPath').once('value')
.then(snapshot => {
const value = snapshot.val()
if (value) return res.status(400).send({ message: 'doSomethingAlreadyCalled' })
doSomething()
const updates = { '/somePath/someSubPath': true }
return admin.database().ref().update(updates)
.then(() => res.status(200).send({ message: 'OK' }))
})
.catch(error => res.status(400).send({ message: 'updateError' }))
})
})
// HELPERS
const doSomething = () => {
// needs to be called only once
}
I believe you were downvoted due to the above pseudocode not making complete sense and there being no log or output of what your code is actually doing in your question. Not having a complete picture makes it hard for us to help you.
Just Going from your structure in the question, your actual code could be calling twice due to function hoisting. Whenever I have this issue, I’ll go back to the api documentation and try to restructure my code from rereading.
HTH

First name and last name to Twitter handle

I have a list of people (first and last name) who I want to follow, but I don't want to Google or search them via Twitter separately. What is the best way to get the Twitter handles? Some GitHub repos or tutorials are also fine.
Twitter offers a "User Search" API request.
If you want to search for a user named "Ada Lovelace" you will need to send an OAuth'd request to
https://api.twitter.com/1.1/users/search.json?q=Ada%20Lovelace
You will get back a list of results. There may be many people who share the same first and last name.
As for how to do it, that rather depends on the programming language you want to use.
If you just want a clickable link, use https://twitter.com/search?q=Terence%20Eden
So firstly this question is off-topic but I will try write an answer for you. You could use the twitter api for this but that might be a little overkill if you just want to do this for you.
I made you an API
I made an API just for you using KimonoLabs. You can use this and just make a script that loops through your list and requests this api every time, then return a list of the results. Here is the API endpoint:
https://www.kimonolabs.com/api/duwxgie4?apikey=D6UKiTtKU93kv0YJj8i3kFBAbsIjdSTC&q=PERSON%20NAME
The &q= is the paramater for the person's name. To seperate the first and last name use %20, like so: Robert%20Keus
The documentation for this api is here:
https://www.kimonolabs.com/apis/duwxgie4
Let me know if you need any help,
Luca
Latest answer # 2016
First Solution: I wrote following node.js script. You need access_token and id of pulicly published google doc spreadsheet. For testing purpose I have provided sample spreadsheet's link and its id in following code.
var Twit = require('twit'),
async = require('async');
var T = new Twit({
consumer_key: 'xxxxxxxx',
consumer_secret: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
access_token: 'xxxxxxxxxxx',
access_token_secret: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
timeout_ms: 60*1000 // optional HTTP request timeout to apply to all requests.
});
//https://docs.google.com/spreadsheets/d/1n7DxgJTTHZ9w3xwiHokUhXMLkBwpP5c9ZLFmsYFDCic/edit?usp=sharing
var GoogleSpreadsheet = require("google-spreadsheet"),
_ = require('underscore');
var sheetId = req.params.sheet || "1n7DxgJTTHZ9w3xwiHokUhXMLkBwpP5c9ZLFmsYFDCic",
sheet = new GoogleSpreadsheet(sheetId);
async.waterfall([
function (cb) {
sheet.getRows(1, {}, function (err, rows) {
if (err) { res.send(err); return;};
var names = [];
_.each(rows, function (row) {
names.push(row.first + " " + row.last);
});
cb(null, names);
});
},
function (names, callback1) {
async.map(names, function(name, cb){
T.get('users/search', { q: name, page: 1 }, function (err, data, response) {
if(data.length)
cb(null, {screen_name: data[0].screen_name, name:data[0].name});
else
cb(null, {screen_name: "no_data_retrieved", name: name});
});
}, function (err, results) {
callback1(null, results);
});
},
function (users, callback) {
console.log(users); //**YOU GET ALL DESIRED DATA HERE**
}
], function (err, result) {
//handle in memory data
});
Second Solution: Clone node-cheat twitter-screen-names, run npm install and shoot node server, Now get all twitter usernames as json in browser.
Happy Helping!

SAPUI5 get username/userid from OData request

I am currently focussing a problem which I thought it would be easy to solve. but I didnt. There are controls which allow us to show the username or logged in user, such as the lovely shell-headitems:
var oShell = new sap.ui.ux3.Shell("myShell", {
headerItems: [
new sap.ui.commons.TextView({
text: oController.getUserName() }),
],
});
It looks like this:
In here we define headerItems, which are in my opinion foreseen to show a username / or the currently logged in user. but how can I receive it? my idea is to get it from the odata request, which was made earlier. It requires me to enter username and password -> thus I want to read this username in my controller-method, but how?
getUserName : function() {
// return navigator.userAgent;
var model = sap.ui.getCore().getModel();
return model.getProperty('sUser'); // doesnt work :(
},
I also tried to get it from navigator.userAgent() but this information does not belong to the user.
Anybody knows how to receive it?
And yes: I searched in google and found some threads discussing about users/login but none of these threads solved my issue. Otherwise I thought about transferring sy-uname from SAP to the frontend, but how could you send a single Text? I don't want to build a complete service for this single transaction.
If you do not provide sUser and sPassword during oData-Model-Initialization it will be empty during runtime. You cannot access it from the model, though I realized an own service for this.
The username is in the sap.ui.model.odata.ODataMetadata of ODataModel.
var getUserName = function() {
var model = sap.ui.getCore().getModel();
var sUser = model.oMetadata.sUser;
// Display user logic here.
};
oModel.attachMetadataLoaded(null,getUserName);
Update answer for comment question from zyrex:
var user = new sap.ui.commons.TextView();
var getUserNameCallBack = function(userName) {
user.setText(userName);
}
oController.getUserName(getUserNameCallBack);
Controller method:
getUserName: function(callback) {
var userName = '';
$.getJSON(sServiceUrl).done(function(data) {
userName = data.d.Name;
callback(userName);
});
}

Resources