Search code examples
google-apps-scriptgoogle-sheetsinstagram-api

Having multiple var data


The script below is calling the instagram site of "data1" and prints the UserCount into a Spreadsheet. but I want to use different instagramAccountName

I'd like to set up 3 more datas.

The var instagramAccountName = "data1"&&"data2"; isnt working, so what's your suggestions?

var sheetName = "Tabellenblatt1";
var instagramAccountName = "data1";

function insertFollowerCount() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(this.sheetName);
  accountdata = getInstagramData(this.instagramAccountName);
  sheet.appendRow([instagramAccountName, Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"), accountdata.followerCount]);  
 };

function getInstagramData(username) {
  var r = new RegExp('<script type="text\/javascript">' + 
                   '([^{]+?({.*profile_pic_url.*})[^}]+?)' +
                   '<\/script>');
  var url = "https://www.instagram.com/" + username
  var source = UrlFetchApp.fetch(url).getContentText();
  var jsonStr = source.match(r)[2];
  var data = JSON.parse(jsonStr);
  console.log('data', data);
  var oldVariantOfData = data['entry_data']['ProfilePage'][0];
  console.log('oldVariantOfData', oldVariantOfData);

  return {
    followerCount : oldVariantOfData.graphql.user.edge_followed_by.count,
    followCount : oldVariantOfData.graphql.user.edge_follow.count, 
    mediaCount : oldVariantOfData.graphql.user.edge_owner_to_timeline_media.count
  };  
}

Solution

    1. First, just reference your global variables by their names, there is no need for this.
    2. Second, "data1" && "data2" equals to "data1 AND data2" (Google Apps Script is a subset of JavaScript), which always stores true in your instagramAccountName variable.
    3. Third, there are a lot of ways to reference multiple account names, but you can write to your instagramAccountName variable an Array of names = ['n1','n2'] and then invoke getInstagramData(username) using a for, for...of loop or forEach method.

    In the end, your function should look like this (btw, accountdata should be defined in an outer scope, otherwise you will get a ReferenceError):

    var instagramAccountName = ['data1','data2'];
    
    function insertFollowerCount() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getSheetByName(sheetName);
    
      instagramAccountName.forEach(function(username){
        accountdata = getInstagramData(username);
        sheet.appendRow([username, Utilities.formatDate(new Date(), 
        "GMT", "yyyy-MM-dd"), accountdata.followerCount]); 
      });     
    };
    

    References

    1. forEach method reference on MDN