Dialogflow html/js card json value v1 - javascript

I am trying to access the card json value, to no avail.
In my scenario, I am asking the bot about "weather in London" and it replies back with "It is currently 9 degrees celcius in London." via the webhook.
Which is correct and dynamic.
However, I am trying to also pass the values to a card too.
In the json reply, I do get the card as so
{
"id": "REMOVED",
"timestamp": "2017-12-05T11:10:52.033Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "weather in london",
"action": "sayWeather",
"actionIncomplete": false,
"parameters": {
"geo-city": "London"
},
"contexts": [],
"metadata": {
"intentId": "REMOVED",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 626,
"intentName": "Weather"
},
"fulfillment": {
"speech": "It is currently 9 degrees celcius in London.",
"source": "agent",
"displayText": "It is currently 9 degrees celcius in London.",
"messages": [
{
"type": 0,
"speech": "It is currently 9 degrees celcius in London."
}
],
"data": {
"items": [
{
"simpleResponse": {
"textToSpeech": "This is the first simple response for a basic card"
}
},
{
"basicCard": {
"title": "Title: this is a title",
"formattedText": "This is a basic card. Text in a\n basic card can include \"quotes\" and most other unicode characters\n including emoji 📱. Basic cards also support some markdown\n formatting like *emphasis* or _italics_, **strong** or __bold__,\n and ***bold itallic*** or ___strong emphasis___ as well as other things\n like line \nbreaks",
"subtitle": "This is a subtitle",
"image": {
"url": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
"accessibilityText": "Image alternate text"
},
"buttons": [
{
"title": "This is a button",
"openUrlAction": {
"url": "https://assistant.google.com/"
}
}
]
}
},
{
"simpleResponse": {
"textToSpeech": "This is the 2nd simple response ",
"displayText": "This is the 2nd simple response"
}
}
]
}
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success",
"webhookTimedOut": false
},
"sessionId": "REMOVED"
}
Accessing the value of speech using data.result.fulfillment.speech works fine.
However, when using data.result.fulfillment.data.items.basicCard.image.url it just doesnt work. And if I go up several levels, I do get:
[object Object]
Your help is appreciated.

The items attribute is a list and not an object. As such, you'll have to use a numerical index to retrive the data. In the example you provided the index of the basicCard object is second so your code should look something like this:
data.result.fulfillment.data.items[1].basicCard.image.url
Notice the [1] after items.
Bear in mind that if the order of this list changes you may no longer be retrieving a basicCard object so you may want to add some checking to make sure you're retrieving the data you want.

Related

How to show card carousel in Gifted Chat based on type in React native?

How to iterate through all these objects and get all?
It is getting response from rasa bot. I want get all objects and show it on Card Carousel in React Native using Gifted Chat. I referred this https://developers.facebook.com/docs/messenger-platform/send-messages/template/generic but not getting how declares types and get all objects from the response and show it on the card Carousel in Gifted Chat. Please help me with that.
Array [
Object {
"attachment": Object {
"payload": Object {
"elements": Array [
Object {
"buttons": Array [
Object {
"payload": "/getEnergy",
"title": "Start",
"type": "postback",
},
],
"image_url": "asset/images/cycle.jpg",
"subtitle": "Boost Your Mood: These activities are designed to release happy hormones and leave you with an overall feeling of positivity. Doing them regularly will help you cultivate resilience and a general, positive outlook.",
"title": "Get Energy",
},
Object {
"buttons": Array [
Object {
"payload": "/improveSelfEsteem",
"title": "Start",
"type": "postback",
},
],
"image_url": "asset/images/mountain.jpg",
"subtitle": "Build Strength: This meditation exercise is a powerful practice in mindfulness that helps us cultivate inner strength. Regular practice enables one to be strong in the face of chaos, change, or uncertainty.",
"title": "Improve Self-esteem",
},
Object {
"buttons": Array [
Object {
"payload": "/forBreakups",
"title": "Start",
"type": "postback",
},
],
"image_url": "asset/images/feather.jpg",
"subtitle": "Find Closure: Work on getting closure through the simple method of writing down what you have never expressed or can't say to the ones you've lost.",
"title": "For Breakups",
},
Object {
"buttons": Array [
Object {
"payload": "/forDeepSleep",
"title": "Start",
"type": "postback",
},
],
"image_url": "asset/images/sleep.jpg",
"subtitle": "Unable To Switch Off: This guided meditation will aid you in letting go of everyday thoughts, helping you switch off, relax and drift into a peaceful sleep.",
"title": "For Deep Sleep",
},
Object {
"buttons": Array [
Object {
"payload": "/sleepStories",
"title": "Start",
"type": "postback",
},
],
"image_url": "asset/images/book.jpg",
"subtitle": "Sleep Story - The Mystical Fog",
"title": "Sleep Stories",
},
Object {
"buttons": Array [
Object {
"payload": "/sleepSounds",
"title": "Start",
"type": "postback",
},
],
"image_url": "asset/images/book.jpg",
"subtitle": "Sleep Sound - Rain By The Porch",
"title": "Sleep Sounds",
},
],
"template_type": "generic",
},
"type": "template",
},
"recipient_id": "UserId1",
},
]

Microsoft power automate: JSON "Object reference not set to an instance of an object"

I am attempting to create a JSON Object from an array to pass into a Microsoft product. The format in which the JSON object is accepted is shown beneath (content-type: "application/json"):
{
"value": [
{
"activityGroupNames": [],
"confidence": 0,
"description": "This is a canary indicator for demo purpose. Take no action on any observables set in this indicator.",
"expirationDateTime": "2019-03-01T21:44:03.1668987+00:00",
"externalId": "Test--8586509942423126760MS164-0",
"fileHashType": "sha256",
"fileHashValue": "b555c45c5b1b01304217e72118d6ca1b14b7013644a078273cea27bbdc1cf9d6",
"killChain": [],
"malwareFamilyNames": [],
"severity": 0,
"tags": [],
"targetProduct": "Azure Sentinel",
"threatType": "WatchList",
"tlpLevel": "green",
},
{
"activityGroupNames": [],
"confidence": 0,
"description": "This is a canary indicator for demo purpose. Take no action on any observables set in this indicator.",
"expirationDateTime": "2019-03-01T21:44:03.1748779+00:00",
"externalId": "Test--8586509942423126760MS164-1",
"fileHashType": "sha256",
"fileHashValue": "1796b433950990b28d6a22456c9d2b58ced1bdfcdf5f16f7e39d6b9bdca4213b",
"killChain": [],
"malwareFamilyNames": [],
"severity": 0,
"tags": [],
"targetProduct": "Azure Sentinel",
"threatType": "WatchList",
"tlpLevel": "green",
}
]
}
I making use of an inline code script in Microsoft automate that performs the following in JavaScript:
var threat = workflowContext.actions.Compose.outputs;
var value = Object.values(threat);
return value;
The workflowContext.actions.Compose.outputs line pulls an array consisting of objects shown in the following snippet:
[{"id": "1", "activityGroupNames": "test2"}, {"id": "2", "activityGroupNames": "test3"}, {"id": "3", "activityGroupNames": "test4"}]
This is my output:
{
"body": [
{
"id": "1",
"action": "alert",
"activityGroupNames": "test2"
},
{
"id": "2",
"action": "alert",
"activityGroupNames": "test3"
},
{
"id": "3",
"action": "alert",
"activityGroupNames": "test2"
}
]
}
it is pretty much identical to the format described my Microsoft shown in the first snippet. (https://learn.microsoft.com/en-us/graph/api/tiindicator-submittiindicators?view=graph-rest-beta&tabs=http) at the bottom.
I am unsure as to how I can change the key name from "body" to "value" and think maybe this will resolve my issue. Either way, I'd appreciate any other help on the matter, if any more context is required, please ask.
EDIT: The image beneath shows that the returned return value; is in fact being used as the input for a POST request to the Microsoft graph API

MongoDB aggregate function is not returning the value of collection joined using JavaScript

I needed assistance in order to work out why the aggregate function is not responding the way I'd expect it to respond. This is a RESTful API service I've designed in which I am trying to connect collections with each other. Please note the following:
Collection: Season
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81"
}
Collection: Play
{
"_id": {
"$oid": "5c0fc4aafb6fc04dd6ea4d81"
},
"Name": "It was the first time",
"Description": "One of the best action heros in the entertainment industry until this day",
"ReleaseDate": "24/12/2010",
"EndingDate": "12/08/2012",
"Category": "Drama"
}
My implemented code in JavaScript
function getTestLookUp(db, collectionName, response, secondCollectionName){
console.log('First collection name: ' + collectionName + '\n' + 'Second collection name: ' + secondCollectionName);
db.collection(collectionName).aggregate([
{
$lookup:
{
from: secondCollectionName,
localField: 'PlayID',
foreignField: '_id',
as: 'requestedDetails'
}
}
]).toArray((err, res) => {
if(err){
console.log(err);
} else {
console.log(res);
response.status(200).json({
'Items': res
});
}
});
}
The response
{
"Items": [
{
"_id": "5c0fc60bfb6fc04dd6ea4e9a",
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81",
"requestedDetails": []
}
]
}
The things I've checked so far: the collection names are accurate, the ID is also accurate as I can search it up on the MLabs search feature. I don't understand as to why this is returning a empty 'requestedDetails' as I hoped it would return the item from the Play collection.
In addition to this, I would also appreciate if someone can point out how I can join multiple collections instead of 2.
I welcome any questions regarding this problem.
While still researching for this issue, I accidentally came across a another problem in which someone wrote a comment stating that "you might be comparing a String with ObjectID". This was the cause for this error as I obtain a String variable in return from the database and I am comparing the String variable with the _id which is expecting to see a ObjectID variable to complete the query. Therefore, meaning that my query/lookup is never matching these two variables.
The only way tackle this issue is to do a conversion (string to ObjectID) and then compare the values. However, since I'm using the version of ^3.1.10 of MongoDB, this functionality is not possible. Will need to update the version to 4.0 to be able to implement this functionality.
In order to rectify this issue, I managed to surround the foreign ID within $iod tags.
Before
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81"
}
After
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": {
"$oid": "5c0fc4aafb6fc04dd6ea4d81"
}
}
Response
{
"Items": [
{
"_id": "5c0fc60bfb6fc04dd6ea4e9a",
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81",
"Details": [
{
"_id": "5c0fc4aafb6fc04dd6ea4d81",
"Name": "It was the first time",
"Description": "One of the best action heros in the entertainment industry until this day",
"ReleaseDate": "24/12/2010",
"EndingDate": "12/08/2012",
"Category": "Drama"
}
]
}
]
}

Error in enum data type while uploading intent dialogflow

I am trying to upload my intent everything is working fine, i am writing script in V2 and everything works but for parameter webhookState data type is enum ( [here] ) and we have to enter following of the three values ( [here][1]) now when i enter any one and try to upload it shows.
" Unable to load file: SyntaxError: Unexpected token W in JSON at position 98 "
now when I pass WEBHOOK_STATE_ENABLED(or any one) in quotes code uploads successfully (because as per my knowledge it treats it as string and gets executed) and intent is created for my agent but webhook remains off and also training phrases are not there, i am certain that the parameter webhookState is not being activated when i pass in quotes(because of above mentioned reason) Same is the case with rest, like when i try to put in type of training phrases.
{
"name": "Warehouse_Management",
"displayName": "Warehouse_Management",
"webhookState": "WEBHOOK_STATE_ENABLED_FOR_SLOT_FILLING" ,
"priority": 50000,
"isFallback": false,
"mlDisabled": false,
"trainingPhrases": [
{
"name":"Try1" ,
"type": "EXAMPLE",
"parts": [
{
"text": "for",
"userDefined": true
},
{
"text": "warehouse",
"entityType": "#Properties",
"alias": "Properties",
"userDefined": true
},
{
"text": "management",
"userDefined": true
}
]
},
{
"name":"Try2" ,
"type": "EXAMPLE",
"parts": [
{
"text": "i want app for ",
"userDefined": true
},
{
"text": "warehouse",
"alias": "Properties",
"entityType": "#Properties",
"userDefined": true
}
]
}
],
"outputContexts": [
{
"name": "Yes",
"lifespanCount": 2
},
{
"name": "No",
"lifespanCount": 2
},
{
"name": "Device_Integration",
"lifespanCount": 2
}
],
"resetContexts": false,
"parameters": [
{
"name": "Properties",
"displayName": "Properties",
"value": "$parameter_name",
"entityTypeDisplayName": "#Properties",
"mandatory": false,
"isList": true
}
],
"messages": [
{
"text":"This is sample response"
}
],
"rootFollowupIntentName": "root",
"parentFollowupIntentName": "parent"
}
Please NOTE that in the attached Json i have put it in quotes so it would get successfully executed and will create intent.
In order for it to be valid JSON, the enum value should be wrapped in quotes. It's expecting the enum value as a String.

Iterate through nested Javascript Objects from API response

I've tried 100 different things, and spend days looking through Google and Stackoverflow, but I can't find a solution to this problem. Everything I call after the body of this API response returns undefined!
The response from Facebook SDK looks like this:
[
{
"body": "[
"data": [
{
"name": "Larry Syid Wright",
"administrator": false,
"id": "xxx"
}, {
"name": "Melissa Long Jackson",
"administrator": false,
"id": "xxx"
}, {
"name": "Charlotte Masson",
"administrator": false,
"id": "xxx"
}
],
"paging": {
"next": "url"
}
]"
},{
"body": "{
"data": [
{
"id": "xxx_xxx",
"message": "In honor of Halloween, how many of you have your own ghost stories? Who believes in ghosts and who doesn't?",
"type": "status",
"created_time": "2014-10-31T20:02:01+0000",
"updated_time": "2014-11-01T02:52:51+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Joe HerBatman Owenby Jr."
}
],
}
"paging": {
"cursors":
{
"after": "xxx",
"before": "xxx"
}
}
}
},{
"id": "xxx_xxx",
"from": {
"id": "xxx",
"name": "Jessica Starling"
},
"message": "Watching the "Campaign" and I can't help but notice what a fantastic job they did (Will ferrell and all) with that North Carolina accent! Ya'll know we sound different than other southern states ;)",
"type": "status",
"created_time": "2014-11-01T02:36:21+0000",
"updated_time": "2014-11-01T02:36:21+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Scott Williams"n
}
]
}
}
],
"paging": {
"previous": "xxx",
"next": "xxx"
}
}"
}
]
This response is from a batch call. If I call them separately, I can easily iterate through the responses, and get everything from them. When I call them in the batch though, I can't get past "body", and I need to use a batch call.
console.log(response[0].body); will return the object inside the body of the first part of the response, but console.log(response[0].body.data); returns undefined. I just don't get it. This should be simple but it's like there's a lock on the door and I don't have the right key.
I normally have no issue iterating through objects, so I don't need a generalized answer. I need help seeing whatever it is here that I don't see. Why does the console show undefined when I call anything after the body, and what do I need to be doing to get any of these values?
That JSON contains nested JSON. body seems to be a string. Use
var body = JSON.parse(response[0].body);
The values from the body are just strings.which are embedded as json.So firstly you would need to parse them using JSON.parse.
The code would be like
var body = JSON.parse(response[0].body);

Categories