跟踪 YouTube 视频观看次数和评论

编码级别:初级
时长:20 分钟
项目类型:使用基于时间的触发器的自动化操作

目标

  • 了解该解决方案的用途。
  • 了解 Apps Script 服务在解决方案中的作用。
  • 设置脚本。
  • 运行脚本。

关于此解决方案

此解决方案会在 Google 表格电子表格中跟踪公开 YouTube 视频的表现,包括观看次数、赞和评论。该触发器每天都会检查是否有更新的信息,如果视频有新的评论活动,则会发送电子邮件,以便您与问题和评论互动。

Google 表格中 YouTube 数据的屏幕截图

工作原理

该脚本使用高级 YouTube 服务,获取每个工作表中视频链接列中列出的视频网址的 YouTube 视频详情和统计信息。如果列出的视频的评论数量增加,脚本会向工作表的命名来源电子邮件地址发送电子邮件通知。

Apps Script 服务

此解决方案使用以下服务:

前提条件

如需使用此示例,您需要满足以下前提条件:

  • Google 账号(Google Workspace 账号可能需要管理员批准)。
  • 一个能够访问互联网的网络浏览器。

设置脚本

创建 Apps 脚本项目

  1. 点击以下按钮,为跟踪 YouTube 视频观看次数和评论数电子表格创建副本。此解决方案的 Apps 脚本项目已附加到电子表格。
    复制
  2. 在复制的电子表格中,将 Your_Email_Address 工作表的名称更改为您的电子邮件地址。
  3. 添加要跟踪的 YouTube 视频网址,或使用提供的网址进行测试。网址必须以 www.youtube.com/watch?v= 格式开头。
  4. 依次点击扩展程序 > Google Apps 脚本。如果服务下方已列出 YouTube,您可以跳至后续 2 个步骤。
  5. 点击“服务”旁边的“添加服务”图标
  6. 从列表中选择 YouTube Data API,然后点击 Add(添加)。

创建触发器

  1. 在 Apps 脚本项目中,依次点击 Triggers(触发器)> Add trigger(添加触发器)。
  2. 选择要运行的函数部分,选择 markVideos
  3. 对于选择事件来源,请选择基于时间
  4. 选择基于时间的触发器类型中,选择全天计时器
  5. 对于选择当天的某个时间,请选择您的首选时间。
  6. 根据提示为脚本授权。如果 OAuth 意见征求界面显示此应用未经验证警告,请依次选择高级 > 前往 {Project Name}(不安全)以继续操作。

运行脚本

您设置的触发器会每天运行一次脚本。您可以手动运行脚本进行测试。

  1. 在 Apps 脚本项目中,点击编辑器
  2. 在“函数”下拉菜单中,选择 markVideos
  3. 点击运行
  4. 切换回电子表格,查看脚本添加到工作表中的信息。
  5. 打开电子邮件,查看其中包含的视频列表,看看有哪些视频收到了评论。以后,该脚本运行时,只会发送自上次运行脚本以来评论数增加的视频的电子邮件。

查看代码

如需查看此解决方案的 Apps 脚本代码,请点击下方的查看源代码

查看源代码

Code.gs

solutions/automations/youtube-tracker/Code.js
// To learn how to use this script, refer to the documentation:
// https://developers.google.com/apps-script/samples/automations/youtube-tracker

/*
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Sets preferences for email notification. Choose 'Y' to send emails, 'N' to skip emails.
const EMAIL_ON = 'Y';

// Matches column names in Video sheet to variables. If the column names change, update these variables.
const COLUMN_NAME = {
  VIDEO: 'Video Link',
  TITLE: 'Video Title',
};

/**
 * Gets YouTube video details and statistics for all
 * video URLs listed in 'Video Link' column in each
 * sheet. Sends email summary, based on preferences above, 
 * when videos have new comments or replies.
 */
function markVideos() {
  let ss = SpreadsheetApp.getActiveSpreadsheet();
  let sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

  // Runs through process for each tab in Spreadsheet.
  sheets.forEach(function(dataSheet) {
    let tabName = dataSheet.getName();
    let range = dataSheet.getDataRange();
    let numRows = range.getNumRows();
    let rows = range.getValues();
    let headerRow = rows[0];

    // Finds the column indices.
    let videoColumnIdx = headerRow.indexOf(COLUMN_NAME.VIDEO);
    let titleColumnIdx = headerRow.indexOf(COLUMN_NAME.TITLE);

    // Creates empty array to collect data for email table.
    let emailContent = [];

    // Processes each row in spreadsheet.
    for (let i = 1; i < numRows; ++i) {
      let row = rows[i];
      // Extracts video ID.
      let videoId = extractVideoIdFromUrl(row[videoColumnIdx])
      // Processes each row that contains a video ID.
      if(!videoId) { 
        continue;
      }
      // Calls getVideoDetails function and extracts target data for the video.
      let detailsResponse = getVideoDetails(videoId);
      let title = detailsResponse.items[0].snippet.title;
      let publishDate = detailsResponse.items[0].snippet.publishedAt;
      let publishDateFormatted = new Date(publishDate);
      let views = detailsResponse.items[0].statistics.viewCount;
      let likes = detailsResponse.items[0].statistics.likeCount;
      let comments = detailsResponse.items[0].statistics.commentCount;
      let channel = detailsResponse.items[0].snippet.channelTitle;

      // Collects title, publish date, channel, views, comments, likes details and pastes into tab.
      let detailsRow = [title,publishDateFormatted,channel,views,comments,likes];
      dataSheet.getRange(i+1,titleColumnIdx+1,1,6).setValues([detailsRow]);

      // Determines if new count of comments/replies is greater than old count of comments/replies.
      let addlCommentCount = comments - row[titleColumnIdx+4];

      // Adds video title, link, and additional comment count to table if new counts > old counts.
      if (addlCommentCount > 0) {
        let emailRow = [title,row[videoColumnIdx],addlCommentCount]
        emailContent.push(emailRow);
      }
    }
    // Sends notification email if Content is not empty.
    if (emailContent.length > 0 && EMAIL_ON == 'Y') {
      sendEmailNotificationTemplate(emailContent, tabName);
    }
  });
}

/**
 * Gets video details for YouTube videos
 * using YouTube advanced service.
 */
function getVideoDetails(videoId) {
  let part = "snippet,statistics";
  let response = YouTube.Videos.list(part,
      {'id': videoId});
 return response;
}

/**
 * Extracts YouTube video ID from url.
 * (h/t https://stackoverflow.com/a/3452617)
 */
function extractVideoIdFromUrl(url) {
  let videoId = url.split('v=')[1];
  let ampersandPosition = videoId.indexOf('&');
  if (ampersandPosition != -1) {
    videoId = videoId.substring(0, ampersandPosition);
  }   
 return videoId;
}

/**
 * Assembles notification email with table of video details. 
 * (h/t https://stackoverflow.com/questions/37863392/making-table-in-google-apps-script-from-array)
 */
function sendEmailNotificationTemplate(content, emailAddress) {
  let template = HtmlService.createTemplateFromFile('email');
  template.content = content;
  let msg = template.evaluate();  
  MailApp.sendEmail(emailAddress,'New comments or replies on YouTube',msg.getContent(),{htmlBody:msg.getContent()});
}

email.html

solutions/automations/youtube-tracker/email.html
<!--
 Copyright 2022 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<body>
  Hello,<br><br>You have new comments and/or replies on videos: <br><br>
  <table border="1">
    <tr>
      <th>Video Title</th>
      <th>Link</th>
      <th>Number of new replies and comments</th>
    </tr>
    <? for (var i = 0; i < content.length; i++) { ?>
    <tr>
      <? for (var j = 0; j < content[i].length; j++) { ?>
      <td align="center"><?= content[i][j] ?></td>
      <? } ?>
    </tr>
    <? } ?>
  </table>
</body>

贡献者

此示例由 Google 维护,并由 Google 开发者专家提供帮助。

后续步骤