This tutorial shows you how to fetch Facebook Friends if you have Facebook accessToken.
Here is the the code for Scheduled task called getFriends
function getFriends() {
//Name of the table where accounts are stored
var accountTable = tables.getTable('FacebookAccounts');
//Name of the table where friends are stored
var friendsTable = tables.getTable('Friends');
checkAccounts();
function checkAccounts(){
accountTable
.read({success: function readAccounts(accounts){
if (accounts.length){
for (var i = 0; i < accounts.length; i++){
console.log("Creating query");
//Call createQuery function for all of the accounts that are found
createQuery(accounts[i], getDataFromFacebook);
}
} else {
console.log("Didn't find any account");
prepareAccountTable();
}
}});
}
function prepareAccountTable(){
var myAccount = {
accessToken: "", //enter here you facebook accessToken. You can retrieve it from http://developers.facebook.com/tools/explorer
name: "Ajay Sharma" //enter here your name
};
//Enter new account into table and then run the code from start when done
accountTable.insert(myAccount, {success: function() { checkAccounts(); }});
}
function getDataFromFacebook(url, name){
console.log("Getting data from facebook. " + url);
var request = require('request');
request(url, function friendsLoaded (error, response, body){
if (!error && response.statusCode == 200){
console.log("Retrieved the data from Facebook");
var results = JSON.parse(body).data;
if (results){
console.log("Parsing succeeded");
results.forEach(function visitResult(friend){
var newFriend = {
//Store friends name, id and fetchers name
name: friend.name,
facebookId: friend.id,
fetcher: name
};
friendsTable.insert(newFriend);
console.log("Added new friend " + friend.name);
})
} else {
console.error("Error on parsing");
}
} else {
console.error(error);
}
});
}
function createQuery(account, callback){
friendsTable
.orderByDescending('facebookId')
.where({
//If there's multiple accounts make sure that checking for right friends
fetcher: account.name
})
.read(
{success: function readFriends(friends){
if (friends.length){
//At least some of the friends already on table. Checking only for the new ones
callback(
"https://graph.facebook.com/me/friends?offset=" + friends.length +
"&access_token=" + account.accessToken,
account.name);
} else {
//No friends stored yet so receiving all of them
callback(
"https://graph.facebook.com/me/friends?limit=10&access_token=" + account.accessToken,
account.name);
}
}}
);
}
}
Comments
Post a Comment