Search code examples
javascriptjsonfacebookfacebook-graph-apigoogle-apps-script

Choosing most liked post from facebook group


Well, here is the json file http://herbalista.hol.es/group.json i am working with JSON.parse(); on Google apps script. I temporarily solve with this code by Choosing the post which have more than 15 likes, but i want to choose the one with more likes independently if have or not more than 15 likes.

function repost() {
var UsrAccess_token = "xxxxxxxxx"
var graph = "https://graph.facebook.com/xxxxxx/feed/?access_token="+UsrAccess_token+"";
var jsondata = UrlFetchApp.fetch(graph,{method:"get"}).getContentText();
var object = JSON.parse(jsondata);
var item = object.data;
var currentTime = new Date();
var year = currentTime.getUTCFullYear();
var month = (currentTime.getUTCMonth()) + 1;
var day = (currentTime.getUTCDate()) - 1;
if (day <= 9) {var day = "0"+day+"";}
if (month <= 9) {var month = "0"+month+"";}
var utime = ""+year+"-"+month+"-"+day+"T";
try {
var i = null;
for (i = 0; item.length > i; i += 1) {
var pubDate = item[i].created_time;
if (pubDate.match(utime)) { var likesdata = item[i].likes.data; var len = likesdata.length;
                           if (len > 15) {var popular = item[i].link;}}


}} catch(err) {
   var err = "ERROR";
}
}

Solution

  • For this you can Choose a default value for a variable like var maxLikes = 0; and verify against len variable.

    The code would be something like this:

    function repost() {
    var UsrAccess_token = "xxxxxxxxx"
    var graph = "https://graph.facebook.com/xxxxxx/feed/?access_token="+UsrAccess_token+"";
    var jsondata = UrlFetchApp.fetch(graph,{method:"get"}).getContentText();
    var object = JSON.parse(jsondata);
    var item = object.data;
    var currentTime = new Date();
    var year = currentTime.getUTCFullYear();
    var month = (currentTime.getUTCMonth()) + 1;
    var day = (currentTime.getUTCDate()) - 1;
    if (day <= 9) {var day = "0"+day+"";}
    if (month <= 9) {var month = "0"+month+"";}
    var utime = ""+year+"-"+month+"-"+day+"T";
    try {
      var i = null;
      var maxLikes = 0; 
      for (i = 0; item.length > i; i += 1) {
        var pubDate = item[i].created_time;
        if (pubDate.match(utime)) { 
          var likesdata = item[i].likes.data;
          var len = likesdata.length;
          if (len > maxLikes) {
            maxLikes = len;
            var popular = item[i].link;
          }
        }
      }
    } catch(err) {
       var err = "ERROR";
    }
    

    }

    Hope that helps!