I have a bare bones chatbot in messenger set up and would like to expand on its potential functionality. The first thing I want to be able to do is access user info, mostly the users first name. I know this is possible, but as I am new to NodeJS I am not sure how to achieve this. I have not been able to find very many tutorials on chatbots past the intro stage. Any help is greatly appreciated!
Below is a link to an abbreviated version of my chatbot
This is the main bit of code that I think needs refining (see it below in the context of the rest of the bot)
function getName(event){
request({
url: "https://graph.facebook.com/v2.6/" + sender,
qs: {
access_token : token,
fields: "first_name"
},
method: "GET",
}, function(error, response, body) {
if(error){
console.log("error getting username")
} else{
var bodyObj = JSON.parse(body)
name = bodyObj.first_name
sendText(sender, "Hi, ")
sendText(sender, name)
sendText(sender, " whatsup?")
}
})
}
Chatbot Code
You can get the facebook user info by below code:
request({
url: "https://graph.facebook.com/v2.6/" + senderId + "?",
qs: {
access_token: config.FB_PAGE_ACCESS_TOKEN
},
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'test-bot'
},
method: "GET",
json: true,
time: true
},
function(error, res, faceUserInfo) {
console.log("faceUserInfo", faceUserInfo)
}
);
Double check your access token is correct.
I also suggest you check the what the error message is
console.log("error getting username", error);
Sender is not defined in your function.
It is being passed into your other functions, or delcared in the scope of your post request handler.
Make sure sender is defined, and your code should work fine.
Add the below line to your getName function:
var sender = event.sender.id
Your variable name is not defined, should add let name=... and it works fine
Related
I am attempting to get data in the form of an image sent from elsewhere using multipartform, however when trying to understand this via the great sanctuary(stack overflow) there are missing elements I don't quite understand.
const options = {
method: "POST",
url: "https://api.LINK.com/file",
port: 443,
headers: {
"Authorization": "Basic " + auth,
"Content-Type": "multipart/form-data"
},
formData : {
"image" : fs.createReadStream("./images/scr1.png")
}
};
request(options, function (err, res, body) {
if(err) console.log(err);
console.log(body);
});
2 questions:
what is the variable auth, what do I initialize it to/where/how do I declare it
what is the url "api.LINK.com", is this just the site url where this code is on
After your comments I think I may be doing this wrong. The goal is to send data(an image) from somewhere else(like another website) to this node app, then the nodeapp uses the image and sends something back.
So that I would be the one creating the API endpoint
I'm using sendgrid (javascript) to add a new contact to my list.
Within marketing.
var request = require("request");
var options = { method: 'PUT',
url: 'https://api.sendgrid.com/v3/contactdb/lists/193029b7-0b8b-4c0c-948d-47d09a157542/recipients',
headers: { authorization: 'Bearer myapi' },
body: '{"contacts":[{"email": "myemail#gmail.com","unique_name":"hello"}]}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
But then I get the message 'acces forbidden'.
Am I using the wrong url?
(The API token is set to administrator all access.)
Thanks!
It looks like there's a few things going on here.
According to the docs, there are not endpoints in the Contact API that accept the method PUT.
After checking our own implementation, it also looks like there's an issue with what you're intending to do.
See the docs for adding multiple recipients to a list:
POST https://api.sendgrid.com/v3/contactdb/lists/{list_id}/recipients HTTP/1.1
Request body:
[
"recipient_id1",
"recipient_id2"
]
In order to use that method, you need to first create the users and retrieve their recipient ID's.
POST https://api.sendgrid.com/v3/contactdb/recipients HTTP/1.1
[
{
"email": "myemail#gmail.com",
"unique_name":"hello"
}
]
Check out the links posted for more information on their usage and response.
I am trying to update a Mailchimp list but receive the following error:
{
"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title":"Wrong Datacenter",
"status":403,
"detail":"The API key provided is linked to a different datacenter",
"instance":""
}
However, the data-center referenced in my request URL is the same (us14) as the one suffixing my API key.
request.put({
url: 'https://us14.api.mailchimp.com/3.0/lists/xxxxxxxxx/members/',
auth: {
user: 'apikey:xxxxxxxxxxxxxxxxxxxxx-us14'
},
data: {
email_address: email,
status_if_new: 'subscribed',
email_type: 'html'
}
}
I have tried generating new API keys to no avail (they're all in us14).
Ok I was able to get this to work by first passing your API Key via the headers object. Second, I wrapped my data in JSON.stringify to ensure MailChimp was receiving a proper JSON Object on post. See below for sample code, hope this helps:
request.post({
url: 'https://usXX.api.mailchimp.com/3.0/lists/xxxxxxx/members',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxxxx-usXX'
},
form: JSON.stringify({
email_address: req.body.email,
status: 'subscribed',
interests: { 'xxxxxxx': true } // Interest Group
})
}, function(err, httpResponse, body) {
res.send(body);
});
const options = {
method: "POST",
auth: "uname:apikey656a******d2dfdb37c071a7cc-us19" //Should not give a space after a colon after uname
}
I had given a Space after the colon of uname. Now the API is working fine
I'm trying to hit one of the mailchimp's api, but for somehow I always get
{
"type": "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title": "Resource Not Found",
"status": 404,
"detail": "The requested resource could not be found.",
"instance": ""
}
I'm using request library to make the request and see the code below
var uniqueListId = "XXXX";
var apiKey = "XXX";
.post(function(req, res) {
var email = req.body.email;
var status = "subscribed";
request({
url: 'https://usX.api.mailchimp.com/3.0/lists/' + uniqueListId + '/members',
headers: {
'Authorization': 'randomUser ' + apiKey,
'Content-Type': 'application/json',
},
method: 'POST',
json: {
email_address: email,
status: status
}
}, function(err, response, body) {
if (err) {
res.json(err);
} else {
res.json(response.statusCode, body);
}
});
});
For the sake of clarity, this is the documentation that I'm referring to http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/
Is it because of my req.body data?
I agree with #TooMuchPete, The same issue happened with me and scratched my head for a whole day to solve that issue, and finally, I've found that Audience Idlist_id is wrong.
we need to pick the one which is located under the AudienceTab > ViewContacts > Settings > Audience and Defaults > Audience ID, but unfortunately, I have picked the one which is showing in the URL.
If you're getting a 404 it's because the URL you're hitting doesn't refer to an actual resource. Probably uniqueListId is either empty or not the right ID.
I would suggest using the Postman chrome add-on app to play with the requests and posts - you could also use it to generate sample code, in most languages. It is great for debugging.
After using it, I found that your request options should look something like:
let requestOptions = {
hostname: 'us14.api.mailchimp.com',
method: 'GET',
path: '/3.0/lists' + listId,
headers: {
'Authorization': 'User ' + config.mailChimp.apiKey,
'Content-Type': 'application/json',
},
}
You're almost certainly confusing mailchimp's web_id with list_id. The list_id is the one you need for the API, the web_id is the one you see in the url when you open your list.
I have absolutely no idea why mailchimp uses 2 different ids, nor why they don't seem to put it forward in any of their developer documentation.
Below is an article which explains how to find it - basically you go to your list -> settings tab -> list name and defaults.
https://3by400.com/get-support/3by400-knowledgebase?view=kb&kbartid=6
I'm using NodeJS to call the new MailChimp 3.0 API in order to add an email to a list. While I can get it working via POSTman, I'm having a hard time with Node's http:
var http = require('http');
var subscriber = JSON.stringify({
"email_address": "test#test.com",
"status": "subscribed",
"merge_fields": {
"FNAME": "Tester",
"LNAME": "Testerson"
}
});
var options = {
host: 'https://us11.api.mailchimp.com',
path: '/3.0/lists/<myListID>/members',
method: 'POST',
headers: {
'Authorization': 'randomUser myApiKey',
'Content-Type': 'application/json',
'Content-Length': subscriber.length
}
}
var hreq = http.request(options, function (hres) {
console.log('STATUS CODE: ' + hres.statusCode);
console.log('HEADERS: ' + JSON.stringify(hres.headers));
hres.setEncoding('utf8');
hres.on('data', function (chunk) {
console.log('\n\n===========CHUNK===============')
console.log(chunk);
res.send(chunk);
});
hres.on('end', function(res) {
console.log('\n\n=========RESPONSE END===============');
});
hres.on('error', function (e) {
console.log('ERROR: ' + e.message);
});
});
hreq.write(subscriber);
hreq.end();
Rather than getting even some sort of JSON error from Mailchimp, however, I'm getting HTML:
400 Bad Request
400 Bad Request
nginx
Is it clear at all what I"m doing wrong here? It seems pretty simple, yet nothing I've tried seems to work.
A few additional thoughts:
While http's options have an "auth" property, I'm using the headers instead to ensure the authorization is sent without the encoding (as mentioned here). Still, I've also tried with the "auth" property, and I get the same result.
I'm actually making this call from inside an ExpressJS API (my client calls the Express API, that calls the above code - I've edited all that out of this example for simplicity). That's why my variables are "hres" and "hreq", to distinguish them from the "res" and "req" in Express. Is there any reason that could be the issue?
As mentioned above, I am able to get successful results when using POSTman, so I at least know my host, path, list ID, and API key are correct.
It turns out this had a very simple solution: the "host" property of the options object needed to have only the domain name. IE, remove the "https://" protocol:
var options = {
host: 'us11.api.mailchimp.com',
path: '/3.0/lists/<myListID>/members',
method: 'POST',
headers: {
'Authorization': 'randomUser myApiKey',
'Content-Type': 'application/json',
'Content-Length': subscriber.length
}
}
Try this , its working fine for Me.
var request = require('request');
function mailchimpAddListCall(email, cb){
var subscriber = JSON.stringify({
"email_address": email,
"status": "subscribed"
});
request({
method: 'POST',
url: 'https://us13.api.mailchimp.com/3.0/lists/<Your list id>/members',
body: subscriber,
headers:
{
Authorization: 'apikey <your Mailchimp API key>',
'Content-Type': 'application/json'
}
},
function(error, response, body){
if(error) {
cb(err, null)
} else {
var bodyObj = JSON.parse(body);
console.log(bodyObj.status);
if(bodyObj.status === 400){
cb(bodyObj.detail, null);
}
var bodyObj = JSON.parse(body);
cb(null, bodyObj.email_address +" added to list.");
}
});
}
request is a node module, that you'll need to install into your package.json. npm install --save request
You can use the auth properties just fine with API v3, but if you're getting a 400, that's not the problem. The body of the 400 Error should provide more detailed information, but one thing that jumps out immediately: MailChimp doesn't allow fake or fake-looking emails to be added to lists (like test#test.com), so I'd try a real address and see if that works for you.