I want to show data from JSON URL on my facebook messenger bot. I've tried with a lot of code approach. However, I couldn't still get it. I just could show the data the terminal with console.log.
This is the code I use to get data from JSON URL:
const ambilDataProfil = (sender_psid) => {
//sorry this url below is not valid I write intentionally for my privacy data.
request({
url: 'https://sorry-url-privately.firebaseio.com/server/saving-data/users.json',
method: "GET",
}, function(error, response, body){
let jsonBody = JSON.parse(response.body);
let resp = jsonBody.Ndus;
console.log(resp);
let respon = {"text": "resp"};
callSendAPI(sender_psid, respon);
}
// console.log(body.Ndus.goldar);
);
};
function callSendAPI(sender_psid, response) {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
}
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
}
Related
I'm working to send the data from my server to the webhook.
I'm using a "REQUEST" service, but I'm getting an error. My request hits there but I'm getting an error.
var request = require('request');
var data:any = [];
data[5] = {email5 : "abc#gmail.com"};
request.post({
"url": "https://api.jotform.com/form/formId/submissions?apiKey=apikey",
"json": {
submission : data
},
"headers": {
"Content-type": "application/json"
}
}, (error:any, response:any) => {
if (error) {
console.log(error);
}
else {
if(response){
console.log(response);
console.log('=================');
}
}
});
I'm getting an error of questionId.
Here is my error
body:
{ responseCode: 500,
message: 'error',
content: 'QuestionID not found on form questions!',
duration: '29ms' } }
Please help me!
I just want to send a messages to all the subscribers with nodejs.
This is my code ( I have hidden the PSID below ):
app.get('/helloguys', function (req, res) {
var messageData = {
batch: [
{recipient: {id: "..."}},{recipient: {id: "..."}}
],
message: {
text: "Hi guys :)",
metadata: "DEVELOPER_DEFINED_METADATA"
}
};
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: token },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Ok", response.statusCode);
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
res.send('Hi :)')
})
I get this in the nodejs console:
Ok 200
but users don't receive the message.
Why ?
EDIT for Lix:
body:
2017-10-18T13:38:43.538998+00:00 app[web.1]: [ { code: 400,
2017-10-18T13:38:43.538999+00:00 app[web.1]: headers: [Object],
2017-10-18T13:38:43.538999+00:00 app[web.1]: body: '{"error":{"message":"Unsupported get request. Please read the Graph API documentation at https:\\/\\/developers.facebook.com\\/docs\\/graph-api","type":"GraphMethodException","code":100,"error_subcode":33,"fbtrace_id":"Dd6+kHN7Tl+"}}' },
EDIT for CBroe:
var messageData = {
batch: [
{method:"POST", message: "Hello", recipient: {id: "1552389158161227"}},{method:"POST", message: "Hello", recipient: {id: "1419003191530571"}}
]
};
It doesn't work
EDIT for CBroe 2:
app.get('/helloguys', function (req, res) {
var batch = [
{method:"POST", body: "message=Test status update&recipient=..."},
{method:"POST", body: "message=Test status update&recipient=..."}
];
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: token },
method: 'POST',
json: batch
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("ok", response.statusCode, response.statusMessage, response);
res.send('hi')
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
})
And now I get:
2017-10-18T15:36:05.981999+00:00 app[web.1]: Failed calling Send API 400 Bad Request { message: '(#100) The parameter recipient is required',
2017-10-18T15:36:05.982009+00:00 app[web.1]: type: 'OAuthException',
2017-10-18T15:36:05.982010+00:00 app[web.1]: code: 100,
2017-10-18T15:36:05.982011+00:00 app[web.1]: fbtrace_id: 'EJLQgP9UoMT' }
As per FB dev docs (they stated somewhere within the docs, and not very obvious)
Note the URLEncoding for the body param
Also, multiple POST requests (batched requests):
While GET and DELETE operations must only have a relative_url and a method field, POST and PUT operations may contain an optional body field.
And >>
This should be formatted as a raw HTTP POST body string, similar to a URL query string.
Also, this type of request should be made as multipart/form-data.
Then, batch request requirements are:
(1) to be multipart/form-data;
(2) consist of URLEncoding strings in 'body' parameter;
(3) batch request should be raw HTTP POST body string.
Node.js request module could send form-data (through form-data module). See docs
So, your code should be like this >>
app.get('/helloguys', function (req, res) {
var batchUrl = 'https://graph.facebook.com';
var r = request.post(batchUrl, function(error, response, body) {
if (error) {return console.log("error\n", error)};
console.log("successfull\n", body) //but fb sends error in body message, so check body.error for any errors
});
var form = r.form();
var multipleMessages = [];
var message = "message=" + encodeURIComponent(JSON.stringify(
{
"text": "Hi guys :)"
}
));
//loop throught user IDs (PSIDs)
for (var i=0; i<users; i++) {
var recipient = "recipient=" + encodeURIComponent(JSON.stringify({"id": users[i].id}));
var batchMessage = {
"method": "POST",
"relative_url":"v2.6/me/messages",
"body": recipient + "&" + message
};
multipleMessages.push(batchMessage);
}
form.append("access_token", token)
form.append("batch", JSON.stringify(multipleMessages));
res.send('Hi :)')
})
Try to move res.send('Hi') inside your request callback:
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Ok", response.statusCode);
res.send('Hi');
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
I am developing a chatbot on the Facebook Messenger Platform using Node.js. This is my functioning code for setting up a text response:
const fbReq = request.defaults({
uri: 'https://graph.facebook.com/me/messages',
method: 'POST',
json: true,
qs: {
access_token: Config.FB_PAGE_TOKEN
},
headers: {
'Content-Type': 'application/json'
},
});
const fbMessage = (recipientId, msg, cb) => {
const opts = {
form: {
recipient: {
id: recipientId,
},
message: {
text: msg,
},
},
};
fbReq(opts, (err, resp, data) => {
if (cb) {
cb(err || data.error && data.error.message, data);
}
});
};
I am also able to set up an image response this way. However, when I try to make the response a button template (https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template), no response is received. No error is thrown either.
const fbInfo = (recipientId, cb) => {
const opts = {
form: {
recipient: {
id: recipientId,
},
message: {
attachment:{
type:"template",
text:"Check out our website",
payload:{
template_type:"button",
buttons:[
{
type:"web_url",
url:"https://some.website.com",
title:"Website"
}
]
}
}
}
}
};
fbReq(opts, (err, resp, data) => {
if (cb) {
cb(err || data.error && data.error.message, data);
}
});
};
Instead of form you should use json.
take a look at the code which I have written on glitch
should be something like:
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: <TOKEN> },
method: 'POST',
json: messageData}, ...)
I have to send some parameters of String type along with one array in my body.
But it throws me an error message:
First argument must be String or buffer
Here is my code:
var tokenList = JSON.parse(req.body.tokenList);
var mobParams = {
"tokens": tokenList,
"profile": "<myprofile>",
"notification": {
"title": req.body.title,
"message": req.body.text
}
};
request({
method: "POST",
url: 'https://api.ionic.io/push/notifications',
headers: {
"content-type": "application/json",
"authorization": "Bearer ********"
},
body: (mobParams)
}, function(error, response, body){
console.log('Ionic push error', error);
console.log('IOnic push res', response);
console.log('IOnic push body', body);
if(!error){
return res.send({
code: 1,
message: "success"
});
}else{
return res.send({
code: 0,
message: error
});
}
How can I pass my array inside this object to request npm?
Also, I would like to add that this implementation works pretty fine through front-end but I have separate codebase which requires me to hit multiple FCM requests i.e. in a loop. So I would be happy to have a solution as neither ionic push nor FCM push works
For the FCM push I am trying the code below :
let desktopParams = {
"notification": {
"title": 'Merchant Portal Notifications',
"body": req.body.text
// "click_action" : action
},
"to": '/topics/' + topic
};
request({
method: "POST",
json: true,
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
"content-type": "application/json",
"authorization": "key=****"
},
body: desktopParams
}, function(error, response, body){
console.log('error', error);
console.log('response', response);
console.log('body', body);
//return body;
});
you should try stringifying your tokenList & req.body.text before you join it with with the string (try to log it and post the outcome so that people will have a better idea about the objects...):
var cho = [{name:'john',lname:'cena'},{name:'mary',lname:'jane'}];
var che = {list:[{name:'john',lname:'cena'},{name:'mary',lname:'jane'}],group:'people'}
var mobParams = {
"tokens":JSON.parse(JSON.stringify(cho)),
"profile": "<myprofile>",
"notification": {
"title": "Some title",
"message":JSON.parse(JSON.stringify(che))
}
};
console.log(JSON.stringify(mobParams));//----->{"tokens":[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}],"profile":"<myprofile>","notification":{"title":"Some title","message":{"list":[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}],"group":"people"}}}
var arr = [{name:'john',lname:'cena'},{name:'mary',lname:'jane'}]
var js = JSON.stringify(arr);
var blabla = {'item':'something',js}
console.log(blabla); //-----> Object {item: "something", js: "[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}]"}
var js = JSON.parse(JSON.stringify(arr));
var blabla = {'item':'something',js}
console.log(blabla); //-----> Object {item: "something", js: Array(2)}
var js = JSON.parse(arr);
var blabla = {'item':'something',js}
console.log(blabla); //-----> "SyntaxError: Unexpected identifier"
I've built a flow-base chat bot using FB messenger, Wit.ai and node.js. It's working well, but in order to make the interaction seem more natural I want my bot to pause for a short while and appear to be typing each of its responses.
I want the 'typing' bubble to be displayed briefly before each response my bot sends, ideally being able to define the time the bubble is visible for before the response is sent. At the moment there are sections of my conversation where the bot sends consecutive messages and they are all sent too quickly at once.
The FB Messenger Send API says that either the 'message' or 'sender_action' property must be set. I've tried setting both like so:
const fbMessage = (id, text) => {
if(fruits.apples.indexOf(text) >= 0 || fruits.oranges.indexOf(text) >= 0) {
var body = JSON.stringify({
recipient: { id },
"sender_action":"typing_on",
message: {
attachment: {
"type": "image",
"payload": {
"url": text
}
}
},
});
} else {
var body = JSON.stringify({
recipient: { id },
"sender_action":"typing_on",
message: { text },
});
}
const qs = 'access_token=' + encodeURIComponent(FB_PAGE_TOKEN);
return fetch('https://graph.facebook.com/me/messages?' + qs, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body,
})
.then(rsp => rsp.json())
.then(json => {
if (json.error && json.error.message) {
throw new Error(json.error.message);
}
return json;
});
};
But I get the following error:
I'm not sure what I need to do - I'm assuming I've got to set up some sort of 'sender_action' bot response that's triggered before each conversational response but I don't know how I'd do this.
To display the typing bubble you simply send a sender action of typing_on. This displays the typing indicator for up to 20 seconds, during which time you will send the actual message you want to send.
The JSON for this would be:
{
"recipient":{
"id":"USER_ID"
},
"sender_action":"typing_on"
}
The call is documented here
Got it working, can't work out how to control bubble timing but it's fine for now. The code below will make the typing bubble display briefly before each of my bot's responses without mucking up the flow of my conversation.
FB Messenger code:
const typingBubble = (id, text) => {
var body = JSON.stringify({
recipient: { id },
"sender_action":"typing_on"
});
const qs = 'access_token=' + encodeURIComponent(FB_PAGE_TOKEN);
return fetch('https://graph.facebook.com/me/messages?' + qs, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body,
})
.then(rsp => rsp.json())
.then(json => {
if (json.error && json.error.message) {
throw new Error(json.error.message);
}
return json;
});
};
const fbMessage = (id, text) => {
if(scenarioCombos.trends.indexOf(text) >= 0 || scenarioCombos.disruptions.indexOf(text) >= 0) {
var body = JSON.stringify({
recipient: { id },
message: {
attachment: {
"type": "image",
"payload": {
"url": text
}
}
},
});
} else {
var body = JSON.stringify({
recipient: { id },
message: { text },
});
}
const qs = 'access_token=' + encodeURIComponent(FB_PAGE_TOKEN);
return fetch('https://graph.facebook.com/me/messages?' + qs, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body,
})
.then(rsp => rsp.json())
.then(json => {
if (json.error && json.error.message) {
throw new Error(json.error.message);
}
return json;
});
};
Wit.ai send action code (within 'actions'):
send({sessionId}, {text}) {
const recipientId = sessions[sessionId].fbid;
if (recipientId) {
return typingBubble(recipientId, text), fbMessage(recipientId, text)
.then(() => null)
.catch((err) => {
console.error(
'Oops! An error occurred while forwarding the response to',
recipientId,
':',
err.stack || err
);
});
} else {
console.error('Oops! Couldn\'t find user for session:', sessionId);
return Promise.resolve()
}
},