Retrieving subscriberCount of Channel from Video URLs of YouTube using Google Apps Script

Gists

This is a sample script for retrieving the values of subscriberCount of the channel from the video URLs of YouTube using Google Apps Script.

In this sample, the video URLs are retrieved from Spreadsheet. And, the retrieved values of subscriberCount are put to the Spreadsheet. The sample Spreadsheet is as follows.

Sample script

Please copy and paste the following script to the script editor of Spreadsheet. Before you use this script, please enable YouTube Data API v3 at Advanced Google services. Ref And, please set the sheet name.

function myFunction() {
  // Retrieve the YouTube URLs from the column "A" of Spreadsheet.
  const sheetName = "Sheet1"; // Please set the sheet name.
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const range = sheet.getRange("A2:A" + sheet.getLastRow());
  const values = range.getValues().map(([a]) => a.split("=").pop().trim());
  const check = values.slice();

  // Retrieve subscriberCount from the YouTube URLs.
  const limit = 50;
  const obj = [...Array(Math.ceil(values.length / limit))].reduce((obj, _) => {
    const res1 = YouTube.Videos.list(["snippet"], {
      id: values.splice(0, limit),
      maxResults: limit,
    }).items.reduce(
      (o, { id, snippet: { channelId } }) => ((o[id] = channelId), o),
      {}
    );
    const res2 = YouTube.Channels.list(["statistics"], {
      id: Object.values(res1),
      maxResults: limit,
    }).items.reduce(
      (o, { id, statistics: { subscriberCount } }) => (
        (o[id] = Number(subscriberCount)), o
      ),
      {}
    );
    Object.entries(res1).forEach(([k, v]) => (obj[k] = res2[v] ? res2[v] : ""));
    return obj;
  }, {});

  // Put the values of subscriberCount to the column "B" of the sheet.
  range.offset(0, 1).setValues(check.map((a) => [obj[a] || ""]));
}

Reference

 Share!