简体   繁体   中英

Facebook Messenger Bot - How to use NodeJS to get User Information?

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

您的变量名称未定义,应添加let name = ...并且可以正常工作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM