Theo dõi lượt xem và bình luận của video trên YouTube

Cấp độ lập trình: Cơ bản
Thời lượng: 20 phút
Loại dự án: Tự động hoá bằng điều kiện kích hoạt theo thời gian

Mục tiêu

  • Tìm hiểu vai trò của giải pháp.
  • Hiểu chức năng của các dịch vụ Apps Script trong giải pháp.
  • Thiết lập tập lệnh.
  • Chạy tập lệnh.

Giới thiệu về giải pháp này

Giải pháp này theo dõi hiệu suất của các video công khai trên YouTube, bao gồm cả lượt xem, lượt thích và nhận xét trong một bảng tính Google Trang tính. Trình kích hoạt này sẽ kiểm tra thông tin cập nhật mỗi ngày và gửi email nếu video có hoạt động bình luận mới để bạn có thể tương tác với các câu hỏi và nhận xét.

Ảnh chụp màn hình về dữ liệu trên YouTube trong một tệp Google Trang tính

Cách hoạt động

Tập lệnh sử dụng dịch vụ YouTube nâng cao để lấy thông tin chi tiết và số liệu thống kê về video trên YouTube cho các URL video được liệt kê trong cột Đường liên kết đến video trên mỗi trang tính. Nếu số lượt nhận xét của một video trong danh sách đã tăng lên, tập lệnh sẽ gửi thông báo qua email đến địa chỉ email chứa tên trang tính.

Dịch vụ Apps Script

Giải pháp này sử dụng các dịch vụ sau:

Điều kiện tiên quyết

Để sử dụng mẫu này, bạn cần có các điều kiện tiên quyết sau:

  • Tài khoản Google (các tài khoản Google Workspace có thể yêu cầu quản trị viên phê duyệt).
  • Một trình duyệt web có quyền truy cập vào Internet.

Thiết lập tập lệnh

Tạo dự án Apps Script

  1. Nhấp vào nút sau để tạo bản sao của bảng tính Theo dõi nhận xét và lượt xem video trên YouTube. Dự án Apps Script cho giải pháp này được đính kèm vào bảng tính.
    Tạo bản sao
  2. Trong bảng tính đã sao chép, hãy thay đổi tên của trang tính Your_Email_Address thành địa chỉ email của bạn.
  3. Thêm URL video trên YouTube mà bạn muốn theo dõi hoặc sử dụng URL được cung cấp để kiểm thử. URL phải bắt đầu bằng định dạng www.youtube.com/watch?v=.
  4. Nhấp vào Tiện ích > Apps Script. Nếu YouTube đã được liệt kê trong phần Dịch vụ, bạn có thể bỏ qua 2 bước tiếp theo.
  5. Bên cạnh phần Dịch vụ, hãy nhấp vào biểu tượng Thêm dịch vụ .
  6. Trong danh sách, hãy chọn YouTube Data API (API Dữ liệu YouTube) rồi nhấp vào Add (Thêm).

Tạo trình kích hoạt

  1. Trong dự án Apps Script, hãy nhấp vào Triggers (Điều kiện kích hoạt) > Thêm điều kiện kích hoạt.
  2. Trong phần Chọn hàm để chạy, hãy chọn markVideos.
  3. Đối với mục Chọn nguồn sự kiện, hãy chọn Theo thời gian.
  4. Đối với Chọn loại điều kiện kích hoạt dựa trên thời gian, hãy chọn Hẹn giờ trong ngày.
  5. Đối với mục Chọn thời gian trong ngày, hãy chọn thời gian mà bạn muốn.
  6. Khi được nhắc, hãy cho phép tập lệnh. Nếu màn hình xin phép bằng OAuth hiển thị cảnh báo, Ứng dụng này chưa được xác minh, hãy tiếp tục bằng cách chọn Nâng cao > Chuyển đến {Tên dự án} (không an toàn).

Chạy tập lệnh

Trình kích hoạt mà bạn thiết lập sẽ chạy tập lệnh mỗi ngày một lần. Bạn có thể chạy tập lệnh theo cách thủ công để kiểm tra tập lệnh đó.

  1. Trong dự án Apps Script, hãy nhấp vào biểu tượng Trình chỉnh sửa .
  2. Trong trình đơn thả xuống của hàm, hãy chọn markVideos.
  3. Nhấp vào Chạy.
  4. Quay lại bảng tính để xem lại thông tin mà tập lệnh đã thêm vào trang tính.
  5. Mở email để xem email chứa danh sách những video có từ 1 bình luận trở lên. Khi chạy trong tương lai, tập lệnh chỉ gửi email kèm theo các video có số lượng nhận xét tăng lên kể từ lần chạy gần đây nhất.

Xem lại đoạn mã

Để xem lại mã Apps Script cho giải pháp này, hãy nhấp vào phần Xem mã nguồn bên dưới:

Xem mã nguồn

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>

Người đóng góp

Mẫu này được Google duy trì với sự trợ giúp của các chuyên gia nhà phát triển của Google.

Các bước tiếp theo