使用NodeJS从Get请求中检索Facebook用户信息

时间:2016-04-25 17:52:28

标签: node.js facebook facebook-graph-api curl

我正在制作Facebook聊天机器人并需要一些基本的用户信息。

我正在NodeJS中编写我的机器人,现在我将我的机器人作为echo bot运行。它所做的只是收集用户消息并使用相同的文本回复它们。

我想从Facebook获取用户 first_name last_name 以在消息中使用。我正在使用Facebook Graph API,我在Facebook文档中找到了这个:

curl -X GET "https://graph.facebook.com/v2.6/<USER_ID>?fields=first_name,last_name,profile_pic&access_token=<PAGE_ACCESS_TOKEN>"

所以我在终端上运行了这个并返回了正确的信息。

我只想在NodeJS的Chatbot代码中使用该CURL函数。我查看了这个文档:https://nodejs.org/docs/v0.5.2/api/http.html#http.request但无法弄明白。

那么我如何在NodeJs中运行相同的CURL请求来获取用户名?

这是我的代码:

var express = require('express');
var bodyParser = require('body-parser');
var request = require("request")

var app = express();
var port = process.env.PORT || 3000;

var mongoose = require('mongoose');
mongoose.connect('mongodb://#@ds013911.mlab.com:13911/wyrdbot');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log("We're connceted")
});

// body parser middleware
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(port, function () {
    console.log('Listening on port ' + port);
});

app.get('/', function (req, res) {
    if (req.query['hub.verify_token'] === '<myToken>') {
        res.send(req.query['hub.challenge']);
        console.log("app.get ran")
        res.sendStatus(200)
    }

    res.send(req.query['hub.challenge']);
})

app.post('/', function (req, res) {
    console.log("app.post ran")
    messaging_events = req.body.entry[0].messaging;
    for (i = 0; i < messaging_events.length; i++) {
        event = req.body.entry[0].messaging[i];
        sender = event.sender.id;
        if (event.message && event.message.text) {
            text = event.message.text;

            if (text === 'Generic') {
                sendGenericMessage(sender);
                continue;
            }

            sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));

        }
    }

    res.sendStatus(200);
});

var token = "<myToken>";

function sendTextMessage(sender, text) {
    messageData = {
        text:text
    }
    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token:token},
        method: 'POST',
        json: {
            recipient: {id:sender},
            message: messageData,
        }
    }, function(error, response, body) {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }
    });
}

function sendGenericMessage(sender) {
    messageData = {
        "attachment": {
        "type": "template",
            "payload": {
                "template_type": "generic",
                "elements": [{
                    "title": "First card",
                    "subtitle": "Element #1 of an hscroll",
                    "image_url": "http://messengerdemo.parseapp.com/img/rift.png",
                    "buttons": [{
                        "type": "web_url",
                        "url": "https://www.messenger.com/",
                        "title": "Web url"
                    },{
                        "type": "postback",
                        "title": "Postback",
                        "payload": "Payload for first element in a generic bubble",
                    }],
                },{
                    "title": "Second card",
                    "subtitle": "Element #2 of an hscroll",
                    "image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
                    "buttons": [{
                        "type": "postback",
                        "title": "Postback",
                        "payload": "Payload for second element in a generic bubble",
                    }],
                }]
            }
        }
    };

    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token:token},
        method: 'POST',
        json: {
          recipient: {id:sender},
          message: messageData,
        }
    }, function(error, response, body) {
        if (error) {
          console.log('Error sending message: ', error);
        } else if (response.body.error) {
          console.log('Error: ', response.body.error);
        }
    });
}

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

看看facebook-node-sdk

示例:

<Grid
    >
    <Grid.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="TextWrapping" Value="Wrap" />
            <Setter Property="Text">
                <Setter.Value>
                    Lorem Ipsum is simply dummy text of the printing and 
                    typesetting industry. Lorem Ipsum has been the industry's 
                    standard dummy text ever since the 1500s, when an unknown 
                    printer took a galley of type and scrambled it to make a 
                    type specimen book.
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>

    <StackPanel Orientation="Horizontal">
        <ScrollViewer 
            Width="200" 
            Height="100" 
            Margin="4"
            HorizontalScrollBarVisibility="Disabled">
            <TextBlock />
        </ScrollViewer>
        <ScrollViewer 
            Width="200" 
            Height="100" 
            Margin="4"
            HorizontalScrollBarVisibility="Hidden">
            <TextBlock />
        </ScrollViewer>
    </StackPanel>
</Grid>