//Url config spreadsheet-------------------------------------------------------------------------------------------------------------
//***********************************************************************************************************************************
var ss_config = SpreadsheetApp.openByUrl('config spreadsheet url');
/************************************************************************************************************************************
Script:      Extension of Facebook Token
Version:     06.12.2017
Created By:  Stanislav Jilek [standajilek.cz]
/***********************************************************************************************************************************/

function main() {
//Spreadsheet
    var sheet = ss_config.getSheetByName("tokens");
    var settings = sheet.getRange("A4:C" + sheet.getLastRow()).getValues();

    for (var i = 0; i < settings.length; i++)
    {
//Variables  
        var old_token = settings[i][0];
        var app_id = settings[i][1];
        var app_secret = settings[i][2];

//Extension of Access Tokens
        var token_url = "/oauth/access_token?client_id=" + app_id + "&client_secret=" + app_secret + "&grant_type=fb_exchange_token&fb_exchange_token=" + old_token;
        var new_token = fb_api(token_url).access_token;

//Save a new token
        sheet.getRange("A" + (4 + i)).setValue(new_token);
    }
}
//-----------------------------------------------------------------------------------------------------------------------------------
function fb_api(settings_url) {
    var url = 'https://graph.facebook.com' + settings_url;
    var options = {'method': 'get', 'contentType': 'application/json', 'muteHttpExceptions': true};

    try {
        return(JSON.parse(UrlFetchApp.fetch(url, options)));
    } catch (err)
    {
        Utilities.sleep(1000);
        try {
            return(JSON.parse(UrlFetchApp.fetch(url, options)));
        } catch (err)
        {
            Utilities.sleep(1000);
            return(JSON.parse(UrlFetchApp.fetch(url, options)));
        }
    }
}