button postback messenger bot is not being recieved on heroku - javascript

I've been a little bit struggling , I'v put the button payload as follows .. but it's not being transmitted to server ,
the message object
let message = {
"attachment":{
"type" : "template",
"payload" : {
"template_type" : "generic",
"elements" : [
{
"title" : "title",
"buttons": [{
"type": "postback",
"title": "wishlist",
"payload": "wishlist"
},
],
},
],
}
}
}
and the sending function
function sendMessage(recipientId, message) {
request({
url: "https://graph.facebook.com/v2.6/me/messages",
qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
method: "POST",
sender_action :"typing_on",
json: {
recipient: {id: recipientId},
message: message,
}
}, function(error, response, body) {
if (error) {
console.log("Error sending message: " + response.error);
}
});
}

You cannot send a sender_action and message in the same request, so the recipient is never receiving your message.

Related

Parameter in query graphql breaking JSON with NodeJS

my script connects to a graphql API by fetch and inserts the JSON return in the postgresql database, however when I insert the primaryLabels parameter into the query, it returns that my JSON is broken by a token>.
If I remove this parameter, everything goes perfectly, any solution?
I tried to turn the query into a string, but the code still fails
Code
let queryAPI = {"query": `{squads {name cards(includedOnKanban: true, closed: false, archived: false, cancelled: false, updatedSince: \"2020-01-01T00:00:00-0300\") { identifier title description status priority assignees { fullname email } secondaryLabel primaryLabels swimlane workstate}}}`};
(async () => {
try {
const rawResponse = await fetch('https://www.bluesight.io/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Bluesight-API-Token': 'token-here'
},
body: JSON.stringify(queryAPI)
});
const content = await rawResponse.json();
OUTPUT
at async C:\Users\Documents\Autoportal\Bluesight\index.js:35:25 {
name: 'FetchError',
message: 'invalid json response body at https://www.bluesight.io/graphql reason: Unexpected token < in JSON at position 0',
type: 'invalid-json'
JSON result example:
{
"data": {
"squads": [
{
"name": "SUPPORT IT",
"cards": [
{
"identifier": "06x38y",
"title": "ALL - Validate data",
"description": "review database.",
"status": null,
"priority": "medium",
"assignees": [
{
"fullname": "Carlos",
"email": "carlos#br.it.com",
}
],
"secondaryLabel": null,
"primaryLabels": [
"CLIENT"
]
}
]
}
]
} }
CONTENT
{
squads: [ { name: 'SUPPORT IT', cards: [Array] } ]
}

How to make an AJAX call to GraphHopper Matrix API

I need to send this json with the following information, but at the time of making the request I get an error
message: "Unsupported content type application/x-www-form-urlencoded; charset=UTF-8"
status: "finished"
I don't the correct way to the request
request sent for JS and Jquery:
<script>
$("#request").click(() => {
var url = "https://graphhopper.com/api/1/matrix?key=d5ab0f9f-538a-4842-926a-9667970d4061";
var data = {
"elevation": false,
"from_points": [-33.467482, -70.624736],
"to_points": [
[-33.468756, -70.622155],
[-33.467359, -70.627332],
[-33.466348, -70.621985]
],
"from_point_hints": ["nuble"],
"to_point_hints": [
"place 1",
"place 2",
"place 3"
],
"out_arrays": [
"distances",
"times"
],
"vehicle": "car"
};
$.ajax({
url: url,
data: JSON.stringify(data),
method: 'POST',
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
</script>
you must first enter the longitude and then the latitude and the next error you had was to specify the head of the ajax request
the code would be:
var url = "https://graphhopper.com/api/1/matrix?key=myKey";
var data ={
"from_points": [
[
-70.6247406,
-33.4673461
]
],
"to_points": [
[
-70.913138,
-33.794796,
]
],
"from_point_hints": [
"ñuñoa"
],
"to_point_hints": [
"places 1"
],
"out_arrays": [
"times",
"distances"
],
"vehicle": "car"
};
$.ajax({
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Accept", "application/json");
},
url: url,
data: JSON.stringify(data),
type: 'POST', //en este caso
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});

Request parameters not read when calling Google Cloud Printing API

I'm trying to use the Google Cloud Printing API. I previously had problems relating to the sending of my request. After some json/stringifying experimentation, I no longer get that error. Instead, my API calls are unsuccessful according to the response sent back by the Google API. Here's what I'm doing:
// Ticket used for google cloud printing
const ticket = {
"version":"1.0",
"print":{
"color":{"vendor_id":"psk:Color","type":0},
"duplex":{"type":0},
"page_orientation":{"type":0},
"copies":{"copies":1},
"dpi":{"horizontal_dpi":1200,"vertical_dpi":1200},
"media_size":{"width_microns":80000,"height_microns":58000,"is_continuous_feed":false},
"collate":{"collate":true},
"vendor_ticket_item":[
//Printer specific settings here, from the capabilities:
{"id":"psk:JobInputBin","value":"ns0000:Tray3"},
{"id":"psk:PageICMRenderingIntent","value":"psk:Photographs"},
{"id":"psk:PageMediaType","value":"ns0000:Auto"},
{"id":"psk:JobOutputBin","value":"ns0000:Auto"},
//etc.
]
}
}
request({
"method": "POST",
"content-type" : "application/json",
"url": googlePrintUrl + "submit",
"headers": {
"Authorization": "OAuth " + googleAccessToken
},
"body" : {
"printerid": "39875g133-ae7d-76hg-65af-jhe5bc682404",
"ticket": JSON.stringify(ticket),
"title": "TEST PRINT",
"content": "test msg",
"contentType": "text/plain"
},
"json": true
}, function (error, res, body){
if (error) {
console.log("There was an error with Google Cloud Print");
console.log(error);
return;
}
console.log("The server responded with:", body);
});
this request results in this response from the server:
The server responded with: { success: false,
request:
{ time: '0',
params: {},
user: 'mytest#gmail.com',
users: [ 'mytest#gmail.com' ] },
errorCode: 3,
message: 'Printer Id required for this request.' }
As you can see, the params field is empty. This is strange because when I use Postman to do the same request, this field is filled with the params I sent in the API call. Here's how I successfully did it in Postman:
Which generated the server response:
{
"success": true,
"request": {
"time": "0",
"params": {
"ticket": [
"{\"version\":\"1.0\",\"print\":{\"color\":{\"vendor_id\":\"psk:Color\",\"type\":0},\"duplex\":{\"type\":0},\"page_orientation\":{\"type\":0},\"copies\":{\"copies\":1},\"dpi\":{\"horizontal_dpi\":600,\"vertical_dpi\":600},\"media_size\":{\"width_microns\":80000,\"height_microns\":58000,\"is_continuous_feed\":false},\"collate\":{\"collate\":true},\"vendor_ticket_item\":[{\"id\":\"psk:JobInputBin\",\"value\":\"ns0000:Tray3\"},{\"id\":\"psk:PageICMRenderingIntent\",\"value\":\"psk:Photographs\"},{\"id\":\"psk:PageMediaType\",\"value\":\"ns0000:Auto\"},{\"id\":\"psk:JobOutputBin\",\"value\":\"ns0000:Auto\"}]}}"
],
"printerid": [
"39875g133-ae7d-76hg-65af-jhe5bc682404"
],
"title": [
"TEST"
],
"contentType": [
"text/plain"
],
"content": [
"**** test"
]
},
"user": "mytest#gmail.com",
"users": [
"mytest#gmail.com"
]
},
"xsrf_token": "AIp06DhAZRSLW9GlHWQLKykbpU-5fYRqcA:1531484990909",
"message": "Print job added.",
"job": {
"ticketUrl": "https://www.google.com/cloudprint/ticket?jobid\u003df11043fe-3e00-d912-11dd-c859718a5575",
"printerName": "",
"errorCode": "",
"updateTime": "1531484993830",
"title": "**** TEST",
"message": "",
"ownerId": "mytest#gmail.com",
"tags": [
"^own"
],
"uiState": {
"summary": "QUEUED",
"progress": "Delivery attempts: 1"
},
"numberOfPages": 1,
"createTime": "1531484991068",
"semanticState": {
"delivery_attempts": 1,
"state": {
"type": "QUEUED"
},
"version": "1.0"
},
"printerid": "39875g133-ae7d-76hg-65af-jhe5bc682404",
"fileUrl": "https://www.google.com/cloudprint/download?id\u003df11043fe-3e00-d912-11dd-c859718a5575",
"id": "f11043fe-3e00-d912-11dd-c859718a5575",
"rasterUrl": "https://www.google.com/cloudprint/download?id\u003df11043fe-3e00-d912-11dd-c859718a5575\u0026forcepwg\u003d1",
"contentType": "application/pdf",
"status": "QUEUED"
}
}
This is a successful printing job, and all the parameters sent by me are sent back in the response object.
So where am I going wrong in my node.js code?
Postman sends payload (printerid, content, title, etc) in formData rather than body
Underneath the "SEND" button is a button "Code" that can generate functional NodeJS (and other) snippets like
var request = require("request");
var options = { method: 'POST',
url: 'https://www.google.com/cloudprint/submit',
headers:
{ 'cache-control': 'no-cache',
Connection: 'keep-alive',
'Content-Length': '769',
'Accept-Encoding': 'gzip, deflate',
Host: 'www.google.com',
'Cache-Control': 'no-cache',
'Content-Type': 'application/json',
Authorization: 'Bearer ya29.GlxWB5_vr8QmJw3DChvVyqpRhNJ2hsuVzwNTJoYRH6r2VVGTwDE3MLNAN8pjTB3-BDWtZeIDrCDcP5DwYGywM1vgb9VMPhoi806HrMpOpKAaKzrgiliojec6IB2Cwg',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
formData:
{ printerid: 'd936d368-7ea4-6f66-84fd-6d5a7a357318',
title: 'Document Title',
content: 'Hello World',
ticket: '{"version":"1.0","print":{"vendor_ticket_item":[],"color":{"type":"STANDARD_MONOCHROME"},"copies":{"copies":1}}}',
contentType: 'text/plain' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

Debugging Bad Request 400 error

I'm trying to return a list of flights from Google's QPX Express API, howver I'm stumped on a bad request response:
{ StatusCodeError: 400 - {"error":{"errors":[{"domain":"global","reason":"badRequest","message":"Invalid inputs: received empty request."}],"code":400,"message":"Invalid inputs: received empty request."}}
Is there something wrong with how I'm approaching the structure of the request? I'm using the request-promise library
const options = {
method: 'POST',
uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXX',
qs: {
"request": {
"passengers": {
"adultCount": 1 },
"slice": [{"origin": "BOS",
"destination": "LAX",
"date": "2017-03-01"
}]
}
},
json: true
}
request(options)
.then(function (response) {
console.log(response)
})
.catch(function (err) {
console.log(err)
})
I have solved the issue. The request needed to include the data in the body key with the content-type set to JSON.
This now returns data from the API as expected.
const options = {
method: 'POST',
uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?&key=XXXXXXXXXXXXXXXXXXXX',
body: {
"request": {
"passengers": {
"adultCount": "1"
},
"slice": [
{
"origin": "SFO",
"destination": "LAX",
"date": "2017-06-19"
}
],
"solutions": "1"
}
},
json: true
}
request(options)
.then(function (response) {
console.log(response.trips.tripOption[0].saleTotal)
})
.catch(function (err) {
console.log(err)
})
Check it:
const options = {
method: 'POST',
uri: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXX',
qs: {
"request": {
"passengers": {
"adultCount": 1 },
"slice": [{"origin": "BOS",
"destination": "LAX",
"date": "2017-03-01"
}]
}
},
json: true
};
request(options)
.then(function (response) {
console.log(response);
})
.catch(function (err) {
console.log(err);
});
You forgot to end the uri string. Also please don't forget the semicolons.
Edit:
Try:
request({
url: (your url here),
method: "POST",
json: requestData
},
where requestData will be your qs.

AJAX JQuery | accessing returned object data

I am trying to access data returned in an Ajax call I have made. This is referencing the steam API and is successfully returning the data. I have console logged it to check. Whenever I try and access the data i get and undefined console message.
Below is a snippet of my returned JSON file
{
"playerstats": {
"steamID": "Removed for SO",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 7642
},
{
"name": "total_deaths",
"value": 7349
},
{
"name": "total_time_played",
"value": 427839
},
{
"name": "total_planted_bombs",
"value": 341
},
Below is the code for my ajax call
$.ajax({
url: this.props.url,
dataType: 'json',
crossDomain: true,
success: function(data) {
console.log("success", typeof data);
console.log(data.playerstats.stats.total_kills);
console.log(data["playerstats"]["stats"]["total_kills"]);
}.bind(this),
error: function(xhr, status, err, data) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
I am successfully entering the success function but it is displaying the following in the console
success object
Inline JSX script:21 undefined
Inline JSX script:22 undefined
the 2 undefined errors are appearing on the console.log line where I have tried accessing the Data the only thing I can think of is that I am accessing them wrong.
Attempts
console.log(data.playerstats.stats.total_kills);
console.log(data["playerstats"]["stats"]["total_kills"]);
total_kills is not a property of stats, nor even a property of every item in stats, but a value of the property "name", you want the value of the property "value" of every item in the stats array:
$.ajax({
url: this.props.url,
dataType: 'json',
crossDomain: true,
success: function(data) {
console.log("success", typeof data);
data.playerstats.stats.forEach(function (stat) {
console.log(stat.value);
});
}.bind(this),
error: function(xhr, status, err, data) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
To get only the item which has "total_kills" as the value of its "name" property, you can use this :
var totalKillsObj = data.playerstats.stats.reduce(function(item) {
return item.name === 'total_kills';
});
var totalKills = totalKillsObj.value;
Demo Fiddle
var data = {
"playerstats": {
"steamID": "Removed for SO",
"gameName": "ValveTestApp260",
"stats": [{
"name": "total_kills",
"value": 7642
}, {
"name": "total_deaths",
"value": 7349
}, {
"name": "total_time_played",
"value": 427839
}, {
"name": "total_planted_bombs",
"value": 341
}]
}
}
alert(data.playerstats.steamID);
data.playerstats.stats.forEach(function (stat) {
alert(stat.name + ":" + stat.value);//property for stats are name and value
});

Categories

Resources