KazooTTT

KazooTTT

twitter
github
email
bilibili

Use Google Sheets + API to regularly fetch YouTube view counts

The motivation was to record the view count of the trailer for milklove's second collaboration Whale Store xoxo on YouTube คุณวาฬร้านชำ (Whale Store xoxo) | GMMTV 2025 - YouTube.

So I first searched for any open-source projects or APIs that could be used directly, and then learned from the article Batch Statistics for YouTube Video Views - Yang's Outbound Marketing Notes that Google Sheets' Apps Script can be used to directly retrieve YouTube view counts.

However, the script in this article focuses more on obtaining the current view count rather than retrieving it on a schedule, so I made some modifications to this script to achieve regular view count retrieval and store the time and corresponding view count information in the sheet.

The final result is shown in the image. Grocery Store View Count Record - Google Sheets

CleanShot 2024-12-15 at 21.38.06@2x.png

Operation Tutorial#

Step 1: The original template in the sheet looks like this:

LinkVideo IDTimeView Count
https://www.youtube.com/watch?v=Eia_Sh_ZTyQ=MID(A2, FIND("v=", A2) + 2, LEN(A2) - FIND("v=", A2) - 1)

Write the YouTube link you want to monitor in the first column, and the video ID is calculated directly using a formula.

Step 2: Click on Extensions - Apps Script here to go to the script configuration interface.

CleanShot 2024-12-15 at 21.40.14@2x.png

Click the plus sign next to Services on the left side to add YouTube Data API v3; the identifier and version can be left as default.

CleanShot 2024-12-15 at 21.44.17@2x.png

Step 3: Copy the code into Code.gs, as shown in the image:

function onOpenFunc() {
  PropertiesService.getScriptProperties().setProperty("accessToken", ScriptApp.getOAuthToken());
}

function getVideoViews(videoid) {
  var accessToken = PropertiesService.getScriptProperties().getProperty('accessToken');
  
  // Check if the access token exists
  if (!accessToken) {
    Logger.log('No access token found.');
    return 'Error: No access token';
  }
  
  try {
    var videoStatsResponse = YouTube.Videos.list('statistics', {
      'id': videoid, 
      'access_token': accessToken
    });
    
    // Check if the response contains the expected data
    if (videoStatsResponse.items && videoStatsResponse.items[0] && videoStatsResponse.items[0].statistics) {
      return videoStatsResponse.items[0].statistics.viewCount;
    } else {
      Logger.log('No statistics found for video ID: ' + videoid);
      return 'Error: No statistics';
    }
  } catch (error) {
    Logger.log('Error fetching statistics for video ID ' + videoid + ': ' + error.toString());
    return 'Error: ' + error.toString();
  }
}

function recordYouTubeViewCount() {
  // Get the active spreadsheet
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  
  // Get the ID from the second row
  var videoId = sheet.getRange(2, 2).getValue();   
  
  // Get the current time
  var currentTime = new Date();
  
  try {
    // Get the view count
    var viewCount = getVideoViews(videoId);
    
    // Get the last row of the current spreadsheet
    var lastRow = sheet.getLastRow();
    
    // Insert a new row after the last row and fill in the time and view count
    sheet.insertRowAfter(lastRow);
    sheet.getRange(lastRow + 1, 3).setValue(currentTime); // Set time
    sheet.getRange(lastRow + 1, 4).setValue(viewCount); // Set view count
  } catch (error) {
    // Error handling
    Logger.log('Error processing video ' + videoId + ': ' + error.toString());
    
    // If an error occurs, record the error message
    var lastRow = sheet.getLastRow();
    sheet.insertRowAfter(lastRow);
    sheet.getRange(lastRow + 1, 3).setValue(currentTime); // Set time
    sheet.getRange(lastRow + 1, 4).setValue('Error: ' + error.toString()); // Set error message
  }
}

CleanShot 2024-12-15 at 21.41.33@2x.png

Then, to verify if it's correct, select recordYouTubeViewCount and click the run button. If all goes well, a new row will be added to the sheet.

CleanShot 2024-12-15 at 21.42.08@2x.png

Step 4, which is the final step, we need to set a trigger to regularly query the view count and write it to the sheet. Click on the trigger menu in the left sidebar, then click the add trigger button in the bottom right corner.

CleanShot 2024-12-15 at 21.47.04@2x.png

Set it up as follows, and after configuration is complete, click the save button.

image.png

After clicking, a verification pop-up may appear, requiring you to select your Google account, then click go to xxx project (unsaved), and click allow for authorization. (There are no screenshots retained here, but it should be understandable.)

Then we have completed all configurations and just need to wait an hour to see if it runs normally.

References and Acknowledgments#

This script is based on the script from Batch Statistics for YouTube Video Views - Yang's Outbound Marketing Notes, thanks to the author for providing a detailed tutorial and code.

Also, thanks to Google for providing the API.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.