Sending rich message in Dialogflow fullfilment - javascript

I am trying to create a DialogFlow chatbot setting up my fullfilment with rich message but the payload that carry it never show up.
Here is the inline code I'm using:
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion, Payload} = require('dialogflow-fulfillment');
var answers = [];
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
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 fallback(agent) {
agent.add(`I didn't understand FULLFILMENT`);
agent.add(`I'm sorry, can you try again? FULLFILMENT`);
}
function answer1Handler(agent){
agent.add(`Intent answer1 called`);
const answer = agent.parameters.number;
answers.push(answer);
const payload = {
"text": "Trucmuche"/*,
"attachments": []*/
};
agent.add(new Payload(agent.SLACK, payload));
/*agent.add(
new Payload(agent.SLACK, payload, {rawPayload: true, sendAsMessage: true})
);*/
}
// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('answer1', answer1Handler);
agent.handleRequest(intentMap);
});
This is called when reaching "answer1" intent. It works well when my answer1Handler is only:
function answer1Handler(agent){
agent.add(`Intent answer1 called`);
}
I don't know what I missed I tried both to follow the official documentation on rich message as well as this response but none helped me create my rich responses.
However, when I add a the custom payload you can see above, it doesn't answer anymore and I get an error message in raw api response. Indeed, it wither gives an error:
{
"responseId": "49e306dc-c2a9-4667-ac67-60eb3692ce98-e15c53b8",
"queryResult": {
"queryText": "1",
"parameters": {
"number": 1
},
"allRequiredParamsPresent": true,
"outputContexts": [
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer2",
"lifespanCount": 5,
"parameters": {
"number.original": "1",
"number": 1
}
},
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer1",
"lifespanCount": 4,
"parameters": {
"number.original": "1",
"number": 1
}
}
],
"intent": {
"name": "projects/pollingagent-jnscpa/agent/intents/bea1536a-dede-4faf-ab44-2ba4f80e9c0f",
"displayName": "answer1"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 4993
},
"languageCode": "en"
},
"webhookStatus": {
"code": 4,
"message": "Webhook call failed. Error: DEADLINE_EXCEEDED."
},
"alternativeQueryResults": [
{
"queryText": "1",
"outputContexts": [
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer1",
"lifespanCount": 4,
"parameters": {
"number.original": "1",
"number": 1
}
},
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer2",
"lifespanCount": 3,
"parameters": {
"number.original": "1",
"number": 1
}
}
],
"languageCode": "en"
}
]
}
Or only gives back the first message as you can see in the raw API response:
{
"responseId": "b6bc8807-eca9-45e5-b25e-30e1b4142da7-e15c53b8",
"queryResult": {
"queryText": "1",
"parameters": {
"number": 1
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [
{
"text": {
"text": [
"Intent answer1 called"
]
}
}
],
"outputContexts": [
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer2",
"lifespanCount": 5,
"parameters": {
"number.original": "1",
"number": 1
}
},
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer1",
"lifespanCount": 4,
"parameters": {
"number.original": "1",
"number": 1
}
}
],
"intent": {
"name": "projects/pollingagent-jnscpa/agent/intents/bea1536a-dede-4faf-ab44-2ba4f80e9c0f",
"displayName": "answer1"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 217
},
"languageCode": "en"
},
"webhookStatus": {
"message": "Webhook execution successful"
},
"alternativeQueryResults": [
{
"queryText": "1",
"outputContexts": [
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer1",
"lifespanCount": 4
}
],
"languageCode": "en"
}
]
}
Consequently how can I send rich message within dialogflow fullfilment?

Related

Show JSON in VUE.js

I made an API on Node.js, If I send some params I get the response, it's the same person but different language info, I would like to present it like in the second example I haven't been able to figure it out.
How I'm getting the data
[
{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
},
{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "english",
}
]
how I want to see it
[
{
"Id": 1,
"ced": "123",
"Name": "Andres",
}
"Idiomas":
[
{
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
},
{
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
}
]
]
export default {
el: "myFormPerson",
data() {
return {
results:[],
ced:'',
}
},
methods: {
submitForm() {
axios.get('http://localhost:8080/person/' + this.ced)
.then((response) => {
this.results = response.data;
//console.log(this.results);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
});
//console.log(this.ced);
},
}
}
How I see it right now [1]: https://i.stack.imgur.com/ezHgH.png
Rather than pointlessly trying to get the format you want in the MySQL result (not possible) - work with the JSON to convert it to what you want
this.results=Object.values(response.data.reduce((acc,{Id,ced,Name,...rest})=>(acc[Id]||={Id,ced,Name,Idiomas:[]},acc[Id].Idiomas.push({...rest}),acc),{}));
working example
const have = [{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "spanish",
},
{
"Id": 1,
"ced": "123",
"Name": "Andres",
"NativeLanguage": 1,
"Level": 100,
"NameLang": "english",
}
];
const want = Object.values(have.reduce((acc,{Id,ced,Name,...rest}) => (acc[Id]||={Id,ced,Name,Idiomas:[]},acc[Id].Idiomas.push({...rest}),acc),{}));
console.log(want);

Issue while updating nested data createEntityAdapter RTK query

I am working on the chat that is utilising RTK Query with entity adapters. We created nested normalised createEntityAdapter . I want to update the message key from onCacheEntryAdded, but not able to update nested object. I'm attaching the query endpoint code along with sample response.
RTK Query Endpoint
endpoints: builder => ({
getMessages: builder.query({
query: ({ orderId, userId, channel }) => {
return {
url: `/messages?orderId=${orderId}&userId=${userId}`,
method: 'GET',
}
},
transformResponse(response, meta, arg) {
return messagesAdapter.setAll(messagesAdapter.getInitialState(), [
{
id: `${arg.orderId}-${arg.userId}`,
isTyping: false,
channel: arg.channel,
orderId: arg.orderId,
messages: messagesAdapter.addMany(
messagesAdapter.getInitialState(),
response,
),
},
])
},
async onCacheEntryAdded(
arg,
{ updateCachedData, cacheDataLoaded, cacheEntryRemoved, cacheData },
) {
try {
await cacheDataLoaded
updateCachedData(draft => {
messagesAdapter.updateOne(draft, {
id: '62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72',
changes: {
messages: messagesAdapter.updateOne(
messagesAdapter.getInitialState(),
{
id: '62da7221bc0eb3a259fc2256',
changes: {
message: 'updated message',
},
},
),
},
})
})
} catch {
// no-op in case `cacheEntryRemoved` resolves before `cacheDataLoaded`,
// in which case `cacheDataLoaded` will throw
}
await cacheEntryRemoved
},
providesTags: (result, error, arg) => {
console.log('providesTags', result, error, arg)
return ['chat']
},
}),
}),
Sample response
{
"ids": [
"62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72"
],
"entities": {
"62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72": {
"id": "62d529f60be7549be1f53df3-62d64eef37d10fea52e1ce72",
"isTyping": false,
"channel": "62d7d9266599a9f0c3bcdaba",
"orderId": "62d529f60be7549be1f53df3",
"messages": {
"ids": [
"62da7221bc0eb3a259fc2256",
"62da724dbc0eb3a259fc2260",
"62da75559f7a23f89a0958d4",
"62da94e59f7a23f89a0958ed"
],
"entities": {
"62da7221bc0eb3a259fc2256": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "dsds",
"sentAt": "2022-07-22T09:47:13.000Z",
"id": "62da7221bc0eb3a259fc2256"
},
"62da724dbc0eb3a259fc2260": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "hello nm",
"sentAt": "2022-07-22T09:47:57.000Z",
"id": "62da724dbc0eb3a259fc2260"
},
"62da75559f7a23f89a0958d4": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "b",
"sentAt": "2022-07-22T10:00:53.000Z",
"id": "62da75559f7a23f89a0958d4"
},
"62da94e59f7a23f89a0958ed": {
"order": "62d529f60be7549be1f53df3",
"alias": "Jacques82",
"sender": "62d7999d976791c65dd6eacd",
"senderRole": "ops",
"receiver": "62d64eef37d10fea52e1ce72",
"receiverRole": "student",
"receiverAlias": "Daniela_Jacobs0",
"message": "hello there",
"sentAt": "2022-07-22T12:15:31.000Z",
"id": "62da94e59f7a23f89a0958ed"
}
}
}
}
}
}

Postman - How to count occurrences of a specific object in a JSON response

I am new to JSON and Postman. I believe I'm trying to do something very simple.
I have created a GET request which will get a JSON response like the one below.
In the example below I want to get the count of All "IsArchived" attributes in the response;
The number of those attributes will vary from response to response.
How can I do it? Thanks in advance
{
"Id": 1328,
"Name": "AAA Test",
"Owner": {
"Id": 208,
"Name": "The Boss"
},
"FieldGroups": [
{
"Id": "c81376f0-6ac3-4028-8d61-76a0f815dbf8",
"Name": "General",
"FieldDefinitions": [
{
"Id": 1,
"DisplayName": "Product Name",
"IsArchived": false
},
{
"Id": 2,
"DisplayName": "Short Description",
"IsArchived": false
},
{
"Id": 33,
"DisplayName": "Long Description",
"IsArchived": false
},
]
},
{
"Id": "5ed8746b-0fa8-4022-8216-ad3af17db91f",
"Name": "Somethingelse",
"FieldDefinitions": [
{
"Id": 123,
"DisplayName": "Attribution",
"IsArchived": false
},
{
"Id": 1584,
"DisplayName": "FC1",
"IsArchived": false
},
{
"Id": 623,
"DisplayName": "Sizes",
"IsArchived": false,
"Owner": {
"Id": 208,
"Name": "The Boss"
},
"Unit": "",
"Options": [
{
"Id": 1,
"Value": "XS"
},
{
"Id": 2,
"Value": "S"
},
{
"Id": 3,
"Value": "M"
}
]
}
]
}
],
"IsArchived": false
"Version": 1
}
It is a rather specific solution but I hope it helps. The description is added as comments:
// Convert the response body to a JSON object
var jsonData = pm.response.json()
// Create a count variable which will be increased by 1 everytime IsArchived occurs
var count = 0;
function countIsArchived() {
// Loop through the FieldGroupsArray
_.each(jsonData.FieldGroups, (fieldGroupsArray) => {
// Loop through the FieldDefinitionsArray
_.each(fieldGroupsArray.FieldDefinitions, (fieldDefinitionsArray) => {
// Check if IsArchived exists
if(fieldDefinitionsArray.IsArchived) {
// Increase count by 1
count++;
}
});
});
// IF you want it:
// Check if IsArchived exists on the top level of the JSON response and increase count
if(jsonData.IsArchived) {
count++;
}
// IF you want it:
// Create a Postman environment variable and assign the value of count to it
pm.environment.set("count", count);
}
Additional info:
The , after the following object is not needed. It invalidates the JSON:
{
"Id": 33,
"DisplayName": "Long Description",
"IsArchived": false
}, <--

Documents are not deleted when using the Javascript APIs deleteByQuery()?

Using deleteByQuery() in the Javascript API I would like to delete some documents from an index called people.
It might be important to note that this is version 5.1 in AWS Elastic Search Service.
The index mapping looks like this:
"people": {
"mappings": {
"person": {
"properties": {
"name": {
"type": "string"
},
"parent_id": {
"type": "long"
},
"query": {
"properties": {
"match": {
"properties": {
"parent_id": {
"type": "long"
}
}
},
"term": {
"properties": {
"parent_id": {
"type": "long"
}
}
}
}
}
}
}
}
}
And a search query that is structured as follows:
query: {
term: {
parent_id: 1
}
}
Responds with:
"hits": {
"total": 1,
"max_score": 10.135444,
"hits": [
{
"_index": "people",
"_type": "person",
"_id": "AVp6EDRVm933W5mwl4O9",
"_score": 10.135444,
"_source": {
"name": "Bob",
"parent_id": 1
}
}
]
}
So then using the documentation for the JS API I have created the following:
const elasticsearch = require('elasticsearch')
function deletePeople (parentId) {
new elasticsearch
.Client({ host: 'es.host.domain' })
.deleteByQuery({
index: 'people',
type: 'person',
body: {
query: {
term: {
parent_id: parentId
}
}
}
}, function afterDeletingPeople (error, response) {
if (error) {
return console.log("deletePeople :: Error :: ", error);
}
else {
return console.log("deletePeople :: Response :: ", response);
}
});
};
deletePeople(1);
Which gives a response like:
info: deletePeople :: Response :: { _index: 'people',
_type: 'person',
_id: '_delete_by_query',
_version: 30,
_shards: { total: 2, successful: 1, failed: 0 },
created: false }
And that looks hopeful but no people are actually removed from the index. I tried to use match instead of term in the query but that does the same thing.
Could anyone suggest where I have gone wrong here with this as currently my function deletes no people? TIA!

Getting Messages from Inbox

I have a question about the Graph API.
I use Javascript for the API and make a little test website ,where you can log in ,look for new messages and write a new status.
My problem is that I can't get the messages or the thread.
FB.api('/me/inbox',function(response) { alert(response.id); } ); don't work.
Have somebody an example for getting the messages in the inbox??
Thanks
The /me/inbox request requires that you have the read_mailbox permission granted.
Once you've got that, the /me/inbox request will return an array of Thread's, which will look something like this;
{
"data": [
{
"id": "1126884978255",
"from": {
"name": "Someone's Name",
"id": "34723472"
},
"to": {
"data": [
{
"name": "Someone's Name",
"id": "34723472"
},
{
"name": "Matt Lunn",
"id": "560914724"
}
]
},
"message": "Testing the one-ness.",
"updated_time": "2012-01-31T12:13:00+0000",
"unread": 0,
"unseen": 0,
"comments": {
"data": [
{
"id": "1126884978255_6769",
"from": {
"name": "Someone's Name",
"id": "34723472"
},
"message": "£140!?",
"created_time": "2012-01-31T11:33:15+0000"
},
{
"id": "1126884978255_6771",
"from": {
"name": "Matt Lunn",
"id": "560914724"
},
"message": "^^ month in advance as well",
"created_time": "2012-01-31T11:33:26+0000"
}
]
},
"type": "thread"
}
],
"summary": {
"unseen_count": 0,
"unread_count": 21,
"updated_time": "2012-01-31T13:19:31+0000"
}
}
So depending which ID you're after, you'll have to do;
for (var i=0;i<response.data.length;i++) {
var thread = response.data[i];
for (var j=0;j<thread.comments.data.length;j++) {
var comment = thread.comments.data[j];
console.log(comment.message);
}
}
Hopefully you get the idea...

Categories

Resources