How to capture dialogflow response? - dialogflow-es

I have a dialogflow intent and I want to write a javascript code to get json response of this intent and show it in an html file. I used webhook fulfillment for this intent and now I want to show chat history between dialogflow and user in an html file. I used this javascript code to extract and have dialogflow response:
baseUrl = "https://api.dialogflow.com/v1/",
$.ajax({
type: "POST",
url: baseUrl + "query",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({query: text, lang: "en", sessionId: "b1973977-20be-4cdc-85a5-7f4225cfdb5a"}),
success: function(data) {
console.log("data",data);
prepareResponse(data);
},
error: function() {
respond(messageInternalError);
}
});
}
But the json it returns me is incorrect and has no fulfillment part in order to extract correct data and show response.
The returned json is :
id: "a0114c2a-afdb-415e-af08-e7a2c5b7d925"
lang: "en"
result: {…}
action: ""
metadata: Object { intentName: "Edit.Attributes", intentId: "9601923d-596b-44df-80de-92dff61869cf", webhookUsed: "true", … }
parameters: Object { VarName: […], percentage: "20%", currncy: "", … }
resolvedQuery: "Change the attribute vacancy rate to 20%"
score: 1
source: "agent"
speech: ""
__proto__: Object { … }
sessionId: "b1973977-20be-4cdc-85a5-7f4225cfdb5a"
status: Object { code: 200, errorType: "success", webhookTimedOut: false }
timestamp: "2018-01-24T12:35:46.342Z"

In my case, this was the solution:
Putting :
url: baseUrl + "query?v=20170712",
instead of :
url: baseUrl + "query",
in ajax call,solved my problem.

The dialogflow response is contained in speech and displayText propery.

Related

How to add parameters to Axios

I am trying to implement axios POST to itop, everything works fine using POSTMAN for me to hard code "title, description, name and first name". Basically at the first start I want to make it like a webpage to input data and then submit the data to itop using POST.
Instead of me manually adding the required parameters, I want to grab the parameters from a form. As for the current script that I have, it said the URL is wrong because the actual URL should be like this instead of below (actual URL from postman: http://test.com/itop/webservices/rest.php?version=1.3&json_data={\n "operation": "core/create",\n "comment": "Synchronization from blah...",\n "class": "UserRequest",\n "output_fields": "id, friendlyname",\n "fields":\n {\n "org_id": "SELECT Organization WHERE name = \"TEST\"",\n "caller_id":\n {\n "name": "name",\n "first_name": "first_name"\n },\n "title": "Test",\n "description": "Test Ticket"\n }\n}')
Here is the code, this code will give out 404 because the request is not correct
app.post('/form-submit', (req, res) => {
let bodyData = {
"operation": "core/create",
"class": "UserRequest",
"output_fields": "id, friendlyname",
"fields": {
"org_id": "SELECT Organization WHERE name = 'TEST'",
},
"caller_id": {
"name": req.body.name,
"first_name": req.body.first_name
},
"title": req.body.title,
"description": req.body.description,
}
let axiosConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic c2FtdWVsLmNoYW5AbHlasdfasdZS5jb206W04wemgxa2FyMV0=',
'Cookie': 'itop-ffb5bc6b0d3aasdfa53a36b=g20efh3399am02aq7v8tif1b7l'
},
}
axios.post('http://test.com/itop/webservice/rest.php?version=1.3&json_data=', bodyData, axiosConfig)
.then(function (response) {
console.log("Ticket created:" + response.data)
})
.catch(function (error) {
console.log(error)
})
})
Thanks ahead for any insight provided

503 error on post request from nodejs application

Im Trying to create ticket with attachment using request module of NodeJs. But not able to do so. I get an error: "Exception":"API Gateway encountered an error. Error Message: Native service provider error. Code : 503.
Following is the code used when making the post request.Is there any error in the api call?
var options = {
method: 'POST',
uri: URL,
headers: {
'Content-Type': 'application/json',
'x-Gateway-APIKey': KEY,
'Authorization': token
},
formData: {
'entry': JSON.stringify({
"values": {
"key1" : value1,
"key2" : value2
},
"options": {
"contentType": "application/json"
}
}),
'attach-z2AF_Act_Attachment_1': {
'value': fs.createReadStream(attachment),
'options': {
'contentType': 'application/octet-stream'
}
}
}
};
The post request works fine through postman.
Update on the issue:Seems the issue is with
'attach-z2AF_Act_Attachment_1': {
'value': fs.createReadStream('sample.txt'),
'options': {
'contentType': 'application/octet-stream'
}
}
Do I need convert 'sample.txt' to binary format before passing in 'value' ?

Provisional headers are shown

I am using Extjs in web and node.js in the api side. I called the api defined, from the web. I passed params and required data as request, but its showing the below error and request is unsuccessful.
Here is the api call code:
Ext.Ajax.request({
url: "http://localhost:3000/update-fund",
method: "POST",
dataType: 'json',
params: {
userId: userDocGlobal.id
},
headers: {
'Content-Type': 'application/json'
},
jsonData: {
fundId: PECalculator.selectedFund,
fundDate: getAiqDateFromPicker(Ext.getCmp("currentCalculationDateFundLevel")),
fundData: fund,
ownerId: userDocGlobal.companyid,
lpId: userDocGlobal.companyid,
role: userDocGlobal.role,
userId: userDocGlobal.id,
companyid: userDocGlobal.companyid
},
success: function (response) {
if (callback) {
callback(response);
}
if(userRole === "FREE"){
moduleObj.setFundNameAndCalcDateForFreeUser();
}
},
error: function () {
if (errorCallback) {
errorCallback();
}
}
})

Unable to create Eventbrite event using API

I am trying to create an event using V3 API. The parameters I am sending are:
var _event = {
"event" : {
"name": {
"html": "Test Event 01"
},
"description": {
"html": "Test Event 01"
},
"start": {
"timezone": "America/Chicago",
"utc": "2017-07-10T18:00:00Z"
},
"end": {
"timezone": "America/Chicago",
"utc": "2017-07-10T20:00:00Z"
},
"currency": "USD"
}
};
This is how I am sending the request using NodeJS:
var request = require('request');
var _headers = {
'Authorization': 'Bearer ' + _token,
'Content-Type': 'application/json',
}
// Configure the request
var options = {
url: EVENTBRITE_API_URL + "events/",
method: 'POST',
headers: _headers,
form: _event
}
I have also tried Content-Type: application/x-url-form-encoded and inside options, JSON.stringify(_event). I also tried to change _event object to:
var _event = {
"name": {
"html": "Test Event 01"
},
"description": {
"html": "Test Event 01"
},
"start": {
"timezone": "America/Chicago",
"utc": "2017-07-10T18:00:00Z"
},
"end": {
"timezone": "America/Chicago",
"utc": "2017-07-10T20:00:00Z"
},
"currency": "USD"
};
I have tried all the combinations but I always get the same response:
{
"status_code": 400,
"error_description": "There are errors with your arguments: event[currency] - Unknown parameter, event.start.timezone - This field is required., event.currency - This field is required., event.start.utc - This field is required., event[start][timezone] - Unknown parameter, event.end.utc - This field is required., event[end][utc] - Unknown parameter, event[description][html] - Unknown parameter, event[name][html] - Unknown parameter, event[end][timezone] - Unknown parameter, event[start][utc] - Unknown parameter, event.end.timezone - This field is required., event.name.html - This field is required.",
"error": "ARGUMENTS_ERROR"
}
Is there any sample create event request anywhere I can look into? What is the problem with above request?
I think the issue is that you're currently sending a form post (by virtue of using the form option), but then your parameters should look like { "event.currency": "USD", "event.name.html": "Test Event 01", ... }. If you want to send JSON, you need to use json: true and pass a JSON-serializable body:
var request = require('request');
var _headers = {
'Authorization': 'Bearer ' + _token,
'Content-Type': 'application/json',
}
// Configure the request
var options = {
url: EVENTBRITE_API_URL + "events/",
method: 'POST',
headers: _headers,
// Instead of this:
// form: _event
// use this:
json: true, // says you're sending JSON
body: _event, // so the body should be JSON-serializable
};
If you want to stick with a form post, I think this should do it:
var _event = {
"event.name.html": "Test Event 01",
"event.description.html": "Test Event 01",
"event.start.timezone": "America/Chicago",
"event.start.utc": "2017-07-10T18:00:00Z",
"event.end.timezone": "America/Chicago",
"event.end.utc": "2017-07-10T20:00:00Z",
"event.currency": "USD",
};
var request = require('request');
var _headers = {
'Authorization': 'Bearer ' + _token,
'Content-Type': 'application/x-www-form-urlencoded',
}
// Configure the request
var options = {
url: EVENTBRITE_API_URL + "events/",
method: 'POST',
headers: _headers,
form: _event,
};

Error when trying to send transactional email from template using sendGrid

I'm trying to send a transactional email via node using sendGrid. Below is an example of my code.
const subject = 'Email subject';
const templateId = 'templateId';
const sg = require('sendgrid')(secret);
const request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: {
"personalizations": [
{
"bcc": userEmails,
"substitutions": {
"-userName-": userDetails.name,
"-productPrice-": productDetails.price,
"-productUrl-": productDetails.url,
"-productPercentageDrop-": productDetails.percentageDrop,
"-productName-": productDetails.name,
"-productOriginalPrice-": productDetails.origPrice,
"-productDroppedPrice-": productDetails.dropPrice,
"-productImageUrl-": productDetails.imageUrl
},
"subject": subject.substring(0, 75)
}
],
"from": {
"email": "myemail",
"name": "myname"
},
"content": [
{
"type": "text/html"
}
],
"template_id": templateId
}
});
sg.API(request, function (error, response) {
if (error) {
console.log('Error response received');
}
console.log(response.body.errors);
});
But every time I run the code I get the following error message.
400
message: 'Bad Request', field: null, help: null
Which isn't really that helpful when trying to find out why its erroring.
Body JSON being sent:
{
"host":"",
"method":"POST",
"path":"/v3/mail/send",
"headers":{
},
"body":{
"personalizations":[
{
"bcc":[
{
"email":"name1#hotmail.com",
"name":"name1"
},
{
"email":"name2#hotmail.com",
"name":"name2"
}
],
"substitutions":{
"-productPrice-":189.5,
"-productUrl-":"http://www.tesco.com/direct/humax-fvp-4000t500-m-smart-freeview-play-hd-digital-tv-recorder-with-wi-fi-500gb/483-1785.prd",
"-productName-":"Tesco direct: Humax FVP-4000T/500 (M) Smart Freeview Play HD Digital TV Recorder with Wi-Fi - 500GB"
},
"subject":"Product Tesco direct: Humax FVP-4000T/500 (M) Smart Freeview Play HD Digita"
}
],
"from":{
"email":"email#pricetracker.io",
"name":"Pricetracker"
},
"content":[
{
"type":"text/html"
}
],
"template_id":"XXXXXX"
},
"queryParams":{
},
"test":false,
"port":""
}
don't know if this could still be helpful for you, but I've had some similar issues when using substitutions with Sendgrid. I'm using the sendgrid-php library, but internally it sends the same format. What I found was that all substitution values should be converted to string. For instance your value for productPrice should be like this:
"-productPrice-": "189.5",
With quotes. In my case I had integers, and when I converted them to strings, all worked correctly.
If you are not passing string value to the template file then SendGrid will give you
{"errors":[{"message":"Bad Request","field":null,"help":null}]}
Convert your all non-string value to string before sending to the template file.
I got same issue, then I fix using this below syntax, change only you message format.
"value": "'.html_entity_decode((str_replace('"',"'",$message))).'"

Resources