Custom payload in Dialogflow - node.js

i try to send custom payload in Dialogflow from fulfillment(nodejs)
My motive is send link and its text as response to web page.
my sample code for reference:
const response = {
messages: [
{
payload: {
messages: [
{
speech: 'here are some quick links for your convenience.',
linkmessage: [{
message: 'google',
link: 'www.google.com'
}, {
message: 'yahoo',
link: 'www.yahoo.co.in'
}],
button: [{
buttonname: 'more page'
}]
}
]
}
}
]
};
agent.add(new Payload(agent.UNSPECIFIED, response, { rawPayload: true, sendAsMessage: true}));
Here i get the response as:
{
"fulfillment": {
"speech": "",
"messages": [
{
"lang": "en",
"type": 0,
"speech": ""
}
],
"data": {
"null": {
"messages": [
{
"payload": {
"messages": [
{
"speech": "here are some quick links for your convenience.",
"linkmessage": [{
"message": "google",
"link": "www.google.com"
}, {
"message": "yahoo",
"link": "www.yahoo.co.in"
}],
"button": [{
"buttonname": "more page"
}]
}
]
}
}
]
}
}
}
Here you can see in response i am getting "null" object is appended inside the data object in the response.
can any one help me out to remove that null object from dialogflow response, and any other option for sending custom payload from fulfillment nodejs.

function update() {
const response = {
messages: [
{
payload: {
messages: [
{
speech: 'here are some quick links for your convenience.',
linkmessage: [{
message: 'google',
link: 'www.google.com'
}, {
message: 'yahoo',
link: 'www.yahoo.co.in'
}],
button: [{
buttonname: 'more page'
}]
}
]
}
}
]
};
agent.add(new Payload(agent.UNSPECIFIED, response, { rawPayload: true, sendAsMessage: true}));
}
In this function need to add parameter as agent so that you can get non 'null' object
Reference code need to be updated.
function update(agent) {
const response = {
messages: [
{
payload: {
messages: [
{
speech: 'here are some quick links for your convenience.',
linkmessage: [{
message: 'google',
link: 'www.google.com'
}, {
message: 'yahoo',
link: 'www.yahoo.co.in'
}],
button: [{
buttonname: 'more page'
}]
}
]
}
}
]
};
agent.add(new Payload(agent.UNSPECIFIED, response, { rawPayload: true, sendAsMessage: true}));
}

Related

How to compare a string with a value inside of object in mongoDB & Node.js

i am receiving a string "city" from "req.body"
my function:
async function searchProject(req: Request, res: Response) {
const { code, archiveNumber, air, city, municipality, origin } = req.body;
console.log(city);
try {
const projects = await Project.find({
$or: [
{ code: { $regex: code ?? "" } },
{ archiveNumber },
{ air },
{
city: {
$in: [city, "$city.value"],
},
},
{ municipality },
{ origin },
],
});
if (!projects)
return res.status(400).json({ message: "Pas de projet trouvée" });
res.status(200).json(projects);
} catch (err) {
console.log(err);
res.status(500).json({ message: "Server Error" });
}
}
i am using $or operator to get projects that matches at least on the values that receive from "req.body", all other values seem to work but "city".
in my document, here is how city looks like:
"city": [
{
"id": "62ed0121f58a5ed78ac05a85",
"value": "City 1"
}
],
now how can i compare a "city" which i get from "req.body" with "city.value" ?
Solved!!!
i tried:
const projects = await Project.find({
$or: [
{ code: { $regex: code ?? "" } },
{ archiveNumber },
{ air },
{ municipality },
{ origin },
],
}).elemMatch("city", {
value: city,
});
and it worked
thanks to
Siddhesh Khadapkar

How to remove an object from array of objects in mongoose?

I have this data and I want to remove a given movie based on its id/title
"_id": "604184234a2f37156cec63ca",
"name": "Jacob Tremblay",
"description": "Jacob Tremblay is a Canadian actor. He made his film debut as Blue in the live action animated film",
"born": "06051993",
"bornCountry": "Usa",
"movies": [
{
"movie": {
"_id": "604184384a2f37156cec63cb",
"title": "Luca",
"__v": 0,
"id": "604184384a2f37156cec63cb"
},
"role": "Luca"
}
],
"__v": 0
}
In documentation it says I can achieve this using the $pull, but im having trouble to figure it out how its done. My controller method
const removeMovieForActor = async (req, res, next) => {
try {
await Actor.updateOne(
{ _id: req.params.id },
{ $pull: { movies: { title: req.body.movie }}},
{ multi: true }
)
res.status(200).json({ success: true, data: 'ok' })
} catch (error) {
res.status(400).json({ success: false, error: error })
}
}

How do I updated an item in elasticsearch using node.js lib?

Every update fails for me. I'm not sure what I'm doing wrong:
await search
.update({
index: 'posts',
id: post._id,
body: post,
})
.catch(err => {
failed.updates += 1;
console.log('update failed', post._id);
});
Here is how the docs got inserted:
await search
.index({
index: 'posts',
id: post._id,
body: post,
})
.catch(err => {
failed.inserts += 1;
console.error(err);
});
Inserts work flawlessly. I'm wondering if nothing changed maybe update fails by default? Not sure why but they all fail.
Here is the error:
{
"name": "ResponseError",
"meta": {
"body": {
"error": {
"root_cause": [
{
"type": "x_content_parse_exception",
"reason": "[1:2] [UpdateRequest] unknown field [score]"
}
],
"type": "x_content_parse_exception",
"reason": "[1:2] [UpdateRequest] unknown field [score]"
},
"status": 400
},
"statusCode": 400,
"headers": {
"content-type": "application/json; charset=UTF-8",
"content-length": "221"
},
"warnings": null,
"meta": {
"context": null,
"request": {
"params": {
"method": "POST",
"path": "/posts/_update/5ea1947ebbb15d001c408c4d",
"body": "{\"score\":2,\"views\":21,\"type\":\"link\",\"ranking\":2.7183885087703956,\"sponsored\":false,\"title\":\"Why a âreturn to normalâ could mean disaster for the stock market - MarketWatch\",\"url\":\"https://www.marketwatch.com/story/why-a-return-to-normal-could-mean-disaster-for-the-stock-market-2020-04-22\",\"thumb\":\"https://s.marketwatch.com/public/resources/images/MW-IE973_corona_ZH_20200422114239.jpg\",\"author\":{\"karma\":3910,\"subscriptions\":[\"5e4dad2e5a6930001d9bad99\",\"5e9a298303c86d001c8cf584\",\"5e9aae5d03c86d001c8cf5b9\",\"5e9aa4d703c86d001c8cf5b4\",\"5e622896def3ed002821b9bf\",\"5e507210bdbc8100286fbeee\",\"5e4e3a4d5a6930001d9badb0\",\"5e9da81bd0ff32001c5fd0b9\",\"5e9eecf3ef8abb001ddc2696\"],\"username\":\"marcolanz\",\"created\":\"2020-03-23T03:27:46.936Z\",\"bitcoinAddress\":\"1EsBjmHakFkTnRxxcsB8M1hNHdUnyLg2w7\",\"links\":[],\"id\":\"5e782cb248f8c00027f14f10\"},\"category\":{\"subscriberCount\":2,\"nsfw\":false,\"_id\":\"5e9eecf3ef8abb001ddc2696\",\"name\":\"StockMarket\",\"description\":\"Stock market\",\"owner\":\"5e782cb248f8c00027f14f10\",\"created\":\"2020-04-21T12:54:11.398Z\",\"__v\":0},\"votes\":[{\"user\":\"5e782cb248f8c00027f14f10\",\"vote\":1},{\"user\":\"5e92618ba33715001c54530b\",\"vote\":1}],\"comments\":[],\"created\":\"2020-04-23T13:13:34.989Z\",\"text\":null,\"upvotePercentage\":100,\"commentCount\":0,\"id\":\"5ea1947ebbb15d001c408c4d\"}",
"querystring": "",
"headers": {
"User-Agent": "elasticsearch-js/7.6.1 (linux 4.15.0-96-generic-x64; Node.js v12.16.2)",
"Content-Type": "application/json",
"Content-Length": "1278"
},
"timeout": 30000
},
"options": {
"warnings": null
},
"id": 33
},
"name": "elasticsearch-js",
"connection": {
"url": "http://es01:9200/",
"id": "http://es01:9200/",
"headers": {},
"deadCount": 0,
"resurrectTimeout": 0,
"_openRequests": 1,
"status": "alive",
"roles": {
"master": true,
"data": true,
"ingest": true,
"ml": false
}
},
"attempts": 0,
"aborted": false
}
}
}
Here's the input:
{
score: 2,
views: 21,
type: 'link',
ranking: 2.7183885087703956,
sponsored: false,
_id: 5ea1947ebbb15d001c408c4d,
title: 'Why a âreturn to normalâ could mean disaster for the stock market - MarketWatch',
url: 'https://www.marketwatch.com/story/why-a-return-to-normal-could-mean-disaster-for-the-stock-market-2020-04-22',
thumb: 'https://s.marketwatch.com/public/resources/images/MW-IE973_corona_ZH_20200422114239.jpg',
author: {
karma: 3910,
subscriptions: [
5e4dad2e5a6930001d9bad99,
5e9a298303c86d001c8cf584,
5e9aae5d03c86d001c8cf5b9,
5e9aa4d703c86d001c8cf5b4,
5e622896def3ed002821b9bf,
5e507210bdbc8100286fbeee,
5e4e3a4d5a6930001d9badb0,
5e9da81bd0ff32001c5fd0b9,
5e9eecf3ef8abb001ddc2696
],
_id: 5e782cb248f8c00027f14f10,
username: 'marcolanz',
password: '$2a$10$qDEn46Qr0uGr0pGDP5FWO.aD411ARsOdVJpgzevWAgz1XR0tUW6kK',
created: 2020-03-23T03:27:46.936Z,
__v: 0,
ip: '201.21.39.32',
bitcoinAddress: '1EsBjmHakFkTnRxxcsB8M1hNHdUnyLg2w7',
links: []
},
category: {
subscriberCount: 2,
nsfw: false,
_id: 5e9eecf3ef8abb001ddc2696,
name: 'StockMarket',
description: 'Stock market',
owner: 5e782cb248f8c00027f14f10,
created: 2020-04-21T12:54:11.398Z,
__v: 0
},
votes: [
{ user: 5e782cb248f8c00027f14f10, vote: 1 },
{ user: 5e92618ba33715001c54530b, vote: 1 }
],
comments: [],
created: 2020-04-23T13:13:34.989Z,
text: null
}
await search
.update({
index: 'posts',
id: post._id,
body: { doc: post }, // this is the fix, wrap in "doc"
})
.catch(err => {
failed.updates += 1;
console.log('update failed', post._id);
});
With Elasticsearch 7.6 client, you need to wrap the body inside "doc" key. If you are using "script" along with "doc" then "doc" will be ignored.
Ref: https://www.elastic.co/guide/en/elasticsearch/reference/7.6/docs-update.html#_update_part_of_a_document

Finding and Updating record - Mongoose

I am building an API to store friends names for a game, I have built the API to receive the post request as so :
exports.addFriends = async (req, res) => {
try {
console.log('hit');
console.log(req.body.friendNames);
const addUser = await User.updateOne(
{ uniqueid: req.body.uniqueid },
{ $push: { friendNames: [req.body.friendNames] } }
);
res.json({
addUser
});
} catch (error) {
console.log(error);
}
};
ad the post request as
const friends = await axios.post('/api/v1/users/add/friends', {
uniqueId: this.uniqueid,
friendNames: [
{
userName: 'test',
region: 'euw'
}
]
});
My API is being hit as a see the logs, but no record is made. My User Schema is as so
const userSchema = new mongoose.Schema({
uniqueid: {
type: String,
required: true,
trim: true
},
summonerName: {
type: String
},
friendNames: [
{
userName: String,
region: String
}
]
});
I get no error and the request seems to go through, but no records are added. Any ideas?
$push is used to add one element to the array. But using the $each array update operator, we can push an array of items.
Also, I used findOneAndUpdate with new:true option to retrieve the updated document, because updateOne doesn't return the updated document.
exports.addFriends = async (req, res) => {
try {
console.log(req.body.friendNames);
const addUser = await User.findOneAndUpdate(
{ uniqueid: req.body.uniqueid },
{ $push: { friendNames: { $each: req.body.friendNames } } },
{ new: true }
);
res.json({ addUser });
} catch (error) {
console.log(error);
res.status(500).send("Something went wrong");
}
}
Let's say we have this existing document:
{
"_id": "5e31c749f26d5f242c69f3aa",
"uniqueid": "uniqueid1",
"summonerName": "John",
"friendNames": [
{
"_id": "5e31c749f26d5f242c69f3ab",
"userName": "Max",
"region": "Germany"
}
],
"__v": 0
}
Let's send a request to the controller with this request body:
{
"uniqueid": "uniqueid1",
"friendNames": [
{
"userName": "Andrew",
"region": "England"
},
{
"userName": "Smith",
"region": "USA"
}
]
}
The response will be like this:
{
"addUser": {
"_id": "5e31c749f26d5f242c69f3aa",
"uniqueid": "uniqueid1",
"summonerName": "John",
"friendNames": [
{
"_id": "5e31c749f26d5f242c69f3ab",
"userName": "Max",
"region": "Germany"
},
{
"_id": "5e31c763f26d5f242c69f3ad",
"userName": "Andrew",
"region": "England"
},
{
"_id": "5e31c763f26d5f242c69f3ac",
"userName": "Smith",
"region": "USA"
}
],
"__v": 0
}
}

Actions on Google - Location Permission

How do you request device location using webhook, and actions on google v2.
Previously, I used permission_request field, but that is now deprecated, and not sure where it fits into the response object at.
json response
{
speech: "",
displayText: "",
data: {
google: {
expectUserResponse: true,
noInputPrompts: [
{
textToSpeech: "Hello McFly!"
},
{
textToSpeech: "Good talk, Russ"
},
{
textToSpeech: "Alright, I'm just gonna go over here and hang out. Let me know if there is anything else I can do for you."
}
],
richResponse: {
items: [
{
simpleResponse: {
textToSpeech: "Testing",
ssml: "<speak >Testing</speak>",
displayText: "Testing"
},
basicCard: null
}
],
suggestions: [ ],
linkOutSuggestion: {
destinationName: null,
url: null
}
},
systemIntent: null,
possibleIntents: [
{
intent: "actions.intent.PERMISSION",
inputValueData: {
#type: "type.googleapis.com/google.actions.v2.PermissionValueSpec",
optContext: "To provide weather information for you.",
permissions: [
"DEVICE_COARSE_LOCATION"
]
}
}
]
}
},
contextOut: [ ],
source: "Abbi"
}
so i needed to add the permission request as a system intent, not expected intent, or possible intent.
the below json works now
{
speech: "",
displayText: "",
data: {
google: {
expectUserResponse: true,
noInputPrompts: [
{
textToSpeech: "Hello McFly!"
},
{
textToSpeech: "Good talk, Russ"
},
{
textToSpeech: "Alright, I'm just gonna go over here and hang out. Let me know if there is anything else I can do for you."
}
],
richResponse: {
items: [
{
simpleResponse: {
textToSpeech: "",
ssml: "<speak ></speak>",
displayText: ""
},
basicCard: null
}
],
suggestions: [ ],
linkOutSuggestion: {
destinationName: null,
url: null
}
},
systemIntent: {
intent: "actions.intent.PERMISSION",
data: {
#type: "type.googleapis.com/google.actions.v2.PermissionValueSpec",
optContext: "To provide an accurate experience, ",
permissions: [
"DEVICE_PRECISE_LOCATION"
],
carouselSelect: null
}
}
}
},
contextOut: [ ],
source: "Abbi"
}

Resources