How do I save and retrieve information across invocations of my agent in Dialogflow? - dialogflow-es

I would like my Actions on Google agent to store and retrieve certain pieces of information across invocations - like a cookie. How do I do this?

You have a lot of options on how you want to do this, depending on exactly what you're trying to do. It isn't exactly like a web cookie, although there are similarities.
If you want the equivalent of a session cookie, information that is retained during a single conversation, then your options are
Using the Session ID provided as part of the information sent to you on each invocation and tracking this in your fulfillment.
Storing information you want retained using a Dialogflow context
If you are using the actions-on-google JavaScript library, storing this in the app.data object created for you.
If you want the equivalent of a long-lasting cookie to retain information between conversations then your options are
Using the anonymous User ID provided as part of the information sent to you on each invocation and tracking this in your fulfillment.
If you are using the actions-on-google javascript library, storing this in the app.userStorage object created for you.
Storing it as part of the string in the JSON response under data.google.userStorage.
Some more information about each of these
Session ID
A different Session ID is created for each conversation you have. You can get this Session ID by examining the JSON sent to your webhook in the sessionId parameter.
You can then look this up in a data store of some sort that you manage.
Dialogflow context
Contexts are powerful tools that are available with Dialogflow. You return a context as part of your fulfillment webhook and indicate the name of the context, its lifetime (how many more rounds of the conversation it will be passed back to your webhook), and any parameters associated with the context (string key/value pairs).
Contexts are especially useful in helping determine what intents may be called. You can indicate what contexts must be active for an Intent to be recognized by Dialogflow.
If you're using the actions-on-google node.js library, you can set a context using something like this:
var contextParameters = {
foo: "Something foothy",
bar: "Your local bar."
};
app.setContext( "remember_this", 5, contextParameters );
You need to do this before you call app.ask() or app.tell().
Or you can do the equivalent in the JSON as part of the contextOut block of the response
"contextOut": [
{
"name": "remember_this",
"lifespan": 5,
"parameters": {
"foo": "Something foothy",
"bar": "Your local bar."
}
}
]
The next time your webhook is called, you can fetch this context either by looking at the result.contexts array or by using the app.getContext() or app.getContextArgument() methods in the library.
Using app.data
If you're using the library, Google has done some of the work for you. The app.data object is created for you. Any values you set in the object are available for the lifetime of the session - you just read them in later calls to your webhook.
(Under the covers, Google uses a context for this, so there is no magic. The two work together and you're free to do both.)
Anonymous UserID
When a user first uses your action, a user ID is generated. This ID doesn't give you access to any specific information about them, and isn't used for any other action, but every time you see it, you can be assured that it was the same user that used it on a previous occurrence. Just like a cookie, however, the user can reset it and a new ID will be generated for them for your action.
You get this from the JSON at originalRequest.user.userId or by using app.getUser().userId. Once you have it, you'd use a data store of some sort to store and retrieve information about this user.
Using app.userStorage
Similar to app.data, there is also an app.userStorage object that is created for you for each user. Any changes you make to this object are saved in between conversations you have with this user.
Unlike app.data, however, this doesn't get stored in a context. It has its own storage method. Which leads to...
Storing it in JSON
If you're not using the actions-on-google library, you still have access to userStorage through the response and request JSON directly. You need to store this as a string, but if you need to store a more complex object, a common method is to stringify it as JSON.
You'll store this value under data.google.userStorage in the response and can retrieve it under originalRequest.data.user.userStorage in the request your webhook receives.

You can save the information in Context with a key value parameter.
SAVING VALUES IN CONTEXT :
agent.set.Context({
name:'context-name',
lifespan: 5,
parameters:{
'parameter-name':'parameter-value'
}
});
GETTING VALUES FROM CONTEXT
agent.getContext('context-name');
For more Details : https://dialogflow.com/docs/contexts/contexts-fulfillment

You could also use a Google Cloud database like BigQuery or Firestore

Sounds like you may want to checkout out Account Linking: https://developers.google.com/actions/identity/account-linking. With account linking you can collect end-user information which you exchange with Google by providing a unique key. This unique key becomes part of every request you receive from Google, so when you get that unique key you lookup the information you collected from the end-user. In your case, you would store credentials or whatever key is required to access the end-user information. After the initial linking, any new data you obtain could be stored along with the original information collected, based on the unique key obtained during account linking.

For this purpose, i just did a node module just for that, in external json file from api call, i need to store and add additional informations to retrieve later. I thing that you can do a lot with this module, Store object, array, json, value, Navigation history?, back to previous page.
It work like localStorage or Cookies.
There's no limit, you can create multiple storage by name (key) an value. It's new and i'm testing it for bugs right now on my own project.
Test on Runkit
On npm
vStorage = require('virtual-storage');
vStorage.set('name', '{title:'Title 1', description:'Descriptions 1'}')
let getStorage_name = vStorage.get('name');
console.log(getStorage_name.title);
vStorage.get('name')

Related

How to pass a document's ID using Azure CosmoDB?

I am creating a simple CRUD app to learn Azure. I have created a logic app (standard model) and my APIs are designed using the workflow designer. I also have a CosmoDB to hold each object.
My GET API, that gets all the documents, looks like this:
And my GET API, that gets only one document, looks like this:
Here is what my CosmosDB looks like with the ID of the item that is successfully return when statically called:
So what do I need to replace the static ID with, in the *Document ID input so that I can pass in different IDs?
I have looked at the docs and it suggests documentId, but when I type this in I get this error:
Thanks!
Thank you #404 , posting your suggestion as an answer to help other community members.
" You should know the id you want to retrieve from the flow that feeds into the Get a document block (unless it's static). Since you only have a HTTP trigger your id should be supplied through that. As example by passing the id in the url as query parameter which you then refer to in your Document ID field."
Trigger a post request to logic app with Document ID in request body.
Try as below:

I need to store sesion variable witn PHP y Dialogflow

my project is to have a chatbot that can sell electronic device like resistor, diode and so on.
There are many type of resistor and diode
I have my intents in dialogflow so when user choose one item I need to store it into php session variable so when user have finished so I need to restore that items in session variable but it doesnt work
Recieve dialogflow intent that is called "tomar_cantidad"
if (intent_recibido("tomar_cantidad")) {
$modelo = obtener_variables3('modelo');
$cantidad = obtener_variables2('cantidad');
//enviar_texto(print_r($cantidad));
$datos_usuario = array('modelo'=>$modelo,'cantidad'=>$cantidad);
$_SESSION['datos_usuario'][]= $datos_usuario;
enviar_texto(print_r($_SESSION['datos_usuario']));
}
enviar_texto is a method to send information to dialogflow(that is for testing purposes).
I recieve session variable but only store the last item that user choose not all items
The issue is that the PHP $_SESSION variable is tied to an HTTP session, which is usually implemented with an HTTP cookie. But Dialogflow doesn't manage HTTP cookies when it sends messages to a webhook, so each fulfillment call is a new session each time.
You have a few ways you can approach this:
Get the Dialogflow session ID and store the information against this ID
Store any values you want to store between turns in the conversation as a parameter in an Output Context. You should set the lifespan for the Context to a large number, 99 is typical, or re-set this as the Output Context each time. Then, you can read the parameter in the named Context when you need the information.

How to retrieve all user tokens and send FCM to all

I am trying to send a FCM to multiple users at a time. I can't seem to find a clear answer other than using a topic but i have several conditions which make this quite difficult on my side. Is it at all possible to extract all tokens from a particular document (similar to setting it up as a topic but based on my logic) and pass that array to the Cloud function?
My current code is as follows and it works for a single user (i am only posting the part where the token is extracted):
return admin.firestore().doc('Seller_tokens/tokens/' + brand + '/wc').get().then(usertokensdoc =>{
const sellertokenID = usertokensdoc.get("dXufWMvOTLXUOyj8XNv9NFmsQ4x1");
const payload = {
data:{
title:'FCM - Test',
content: 'FCM - This is a test message,
},
token: sellertokenID
};
for the line:
const sellertokenID = usertokensdoc.get("dXufWMvOTLXUOyj8XNv9NFmsQ4x1");
I do not want to specify a single userid, where the 'userid' is the field in the document . And hence I would like to pass an array, if possible.
As you mentioned and as clarified in the official documentation Send messages to multiple devices, there are only two ways of sending messages to multiple tokens:
Firebase Cloud Messaging provides these two ways to target a message to multiple devices:
Topic messaging, which allows you to send a message to multiple devices that have opted in to a particular topic.
Device group messaging, which allows you to send a message to multiple devices that belong to a group you define.
In addition to this, as mentioned in this other question here, there is no API for you to get all tokens at once, so, you will need to get the individually for usage.
So, to summarize, there is not an automatic way of getting the tokens, but once you get them, I believe using the Device Messaging way would be better for you, since you can define specific groups to receive the FCM, per tokens that you retrieved.
Let me know if the information helped you!
you can retrieve the token documents based on your conditions in cloud function. loop through them, create an array of tokens and pass them to Firebase messaging as below
admin.messaging.sendToDevice(tokens, payload). below url has a very good example.
FCM - Cloud Functions Example

Is there an anonymous ID in Actions on Google with Dialogflow?

Is there an anonymous ID in Actions on Google with Dialogflow that I can access using DialogFlow in Node.js?
I don't need to know the Google account of who is using the Action, but I do want to have a unique identifier so that the Action can know when they come back.
Google no longer provides one for you. You will have to generate one when a new user interacts with your webhook and store the generated id in their user storage object.
To identify a new user your just check if they already have an id in their user storage object. For generating the id you can use an library like uuid. https://www.npmjs.com/package/uuid
Uuidv4 is probably the one that you need if you just need a unique id for simple identifications
The original idea from Google was to leverage a field called userStorage, but this feature seems to be borked ATM.
userStorage Documentation:
https://developers.google.com/actions/assistant/save-data
Reddit thread regarding issues:
https://www.reddit.com/r/GoogleAssistantDev/comments/d88z7e/userstorage_saga_continued/
Unless something has changed (I haven't checked on userStorage since I've been busy writing a fix around it) you may be out of luck without Account Linking. Feel free to try userStorage and keep me honest as they may have remedied the situation internally.
Alternatively, if all you need is an identifier or session for a single conversation you can leverage the conversationId which will be unique until the conversation ends.
I've found a possible option...
(When working in DialogFlow in Node.js, most code is in a handler and the parameter is usually called conv. The following assumes that it is inside such a handler.)
On every single call, check for an 'existing' id in the session data and the user storage:
var id = conv.data.MyId || conv.user.storage.MyId || '';
if(!id) {
id = /* make a new Id for this user... a GUID or some other unique id */
conv.user.storage.MyId = id;
}
Once I get the Id from storage or make a new one, it is critical to reassign it to conv.data, since conv.user.storage seems to be reliably provided only on the first call!
// IMPORTANT
conv.data.MyId = id;
/* use the Id as needed */
My code looks up the Id in a firebase database to get details from their last visit.
This seems to be working, but may not be reliable.

Detail of list without user authentication

I'm trying to get details of Foursquare list by PHP library:
$foursquare = new FoursquareAPI($key,$secret);
$list = $foursquare->GetPublic('lists/'.$listId);
But everytime gets this error:
string(7672) "{"meta":{"code":200,"errorType":"deprecated","errorDetail":"Please provide an API version to avoid future errors.See https:\/\/developer.foursquare.co ... "
When I debug it, library calls this URL: https://api.foursquare.com/v2/lists/ with these params: Array ( [client_id] => <client_id> [client_secret] => <client_secret> )
But when I try this API method in Foursquare API Explorer I see that, this URL is calling: OAuth token automatically added. https://api.foursquare.com/v2/lists/<list_id>?oauth_token=<token>&v=20111205.
In lists doc is Requires Acting User: No, so I'm confused. Is it possible to call this function without authenticating user?
It would be nice, because I want to add places from my list (favourite restaurants) to my page on Google map in Contacts. It would be useful for our clients.
The error you are seeing is unrelated to the list endpoint you are requesting or the state of authentication. It is a warning that the library you are using is currently not following versioning best practice for Foursquare. You can read more about it here.
As for the list there should be a response object at the same level as the meta object.

Resources