ติดตามยอดดูวิดีโอ YouTube และความคิดเห็น

ระดับการเขียนโค้ด: มือใหม่
ระยะเวลา: 20 นาที
ประเภทโปรเจ็กต์: การทำงานอัตโนมัติที่มีทริกเกอร์ตามเวลา

วัตถุประสงค์

  • ทำความเข้าใจสิ่งที่โซลูชันใช้
  • ทำความเข้าใจสิ่งที่บริการ Apps Script ทำภายในโซลูชัน
  • ตั้งค่าสคริปต์
  • เรียกใช้สคริปต์

เกี่ยวกับโซลูชันนี้

โซลูชันนี้จะติดตามประสิทธิภาพของวิดีโอ YouTube สาธารณะ รวมถึงการดู การชอบ และความคิดเห็นในสเปรดชีตของ Google ชีต ทริกเกอร์จะตรวจหาข้อมูลที่อัปเดตทุกวันและส่งอีเมลหากวิดีโอมีกิจกรรมความคิดเห็นใหม่ เพื่อให้คุณมีส่วนร่วมกับคำถามและความคิดเห็นได้

ภาพหน้าจอของข้อมูล YouTube ใน Google ชีต

วิธีการทำงาน

สคริปต์จะใช้บริการ YouTube ขั้นสูงเพื่อรับรายละเอียดและสถิติวิดีโอ YouTube สำหรับ URL ของวิดีโอที่แสดงในคอลัมน์ลิงก์วิดีโอในแต่ละชีต หากจำนวนความคิดเห็นสำหรับวิดีโอในรายการเพิ่มขึ้น สคริปต์จะส่งการแจ้งเตือนทางอีเมลไปยังอีเมลที่ใช้ตั้งชื่อชีต

บริการ Apps Script

โซลูชันนี้ใช้บริการต่อไปนี้

ข้อกำหนดเบื้องต้น

หากต้องการใช้ตัวอย่างนี้ คุณต้องมีข้อกำหนดเบื้องต้นต่อไปนี้

  • บัญชี Google (บัญชี Google Workspace อาจ ต้องได้รับการอนุมัติจากผู้ดูแลระบบ)
  • เว็บเบราว์เซอร์ที่เข้าถึงอินเทอร์เน็ตได้

ตั้งค่าสคริปต์

สร้างโปรเจ็กต์ Apps Script

  1. คลิกปุ่มต่อไปนี้เพื่อทำสำเนาสเปรดชีตติดตามยอดดูวิดีโอ YouTube และความคิดเห็น โปรเจ็กต์ Apps Script สำหรับโซลูชันนี้แนบอยู่กับสเปรดชีต
    ทำสำเนา
  2. เปลี่ยนชื่อชีต Your_Email_Address เป็นที่อยู่อีเมลในสเปรดชีตที่คัดลอกมา
  3. เพิ่ม URL ของวิดีโอ YouTube ที่ต้องการติดตามหรือใช้ URL ที่ให้ไว้สำหรับทดสอบ URL ต้องขึ้นต้นด้วยรูปแบบ www.youtube.com/watch?v=
  4. คลิกส่วนขยาย > Apps Script หาก YouTube แสดงอยู่ในส่วนบริการอยู่แล้ว ให้ข้ามไปยัง 2 ขั้นตอนถัดไป
  5. ถัดจาก Services ให้คลิกเพิ่มบริการ
  6. เลือก YouTube Data API จากรายการ แล้วคลิกเพิ่ม

สร้างทริกเกอร์

  1. ในโปรเจ็กต์ Apps Script ให้คลิกทริกเกอร์ > เพิ่มทริกเกอร์
  2. สำหรับเลือกฟังก์ชันที่จะเรียกใช้ ให้เลือก markVideos
  3. ในส่วนเลือกแหล่งที่มาของเหตุการณ์ ให้เลือกตามเวลา
  4. สำหรับเลือกประเภททริกเกอร์ตามเวลา ให้เลือกตัวจับเวลาวัน
  5. สำหรับเลือกเวลาของวัน ให้เลือกเวลาที่ต้องการ
  6. เมื่อได้รับข้อความแจ้ง ให้ให้สิทธิ์สคริปต์ หากหน้าจอความยินยอมของ OAuth แสดงคำเตือน แอปนี้ไม่ได้รับการยืนยัน ให้ดำเนินการต่อโดยเลือกขั้นสูง > ไปที่ {Project Name} (ไม่ปลอดภัย)

เรียกใช้สคริปต์

ทริกเกอร์ที่คุณตั้งค่าจะเรียกใช้สคริปต์วันละครั้ง คุณจะเรียกใช้สคริปต์ด้วยตนเองเพื่อทดสอบได้

  1. ในโปรเจ็กต์ Apps Script ให้คลิกเอดิเตอร์
  2. เลือกmarkVideosในรายการแบบเลื่อนลงของฟังก์ชัน
  3. คลิกเรียกใช้
  4. กลับไปที่สเปรดชีตเพื่อตรวจสอบข้อมูลที่สคริปต์เพิ่มลงในชีต
  5. เปิดอีเมลเพื่อดูอีเมลที่มีรายการวิดีโอที่มีความคิดเห็นมากกว่า 0 รายการ เมื่อสคริปต์ทำงานในอนาคต สคริปต์จะส่งเฉพาะอีเมลที่มีวิดีโอที่มีจำนวนความคิดเห็นเพิ่มขึ้นตั้งแต่ครั้งล่าสุดที่มีการทำงานของสคริปต์

ตรวจสอบโค้ด

หากต้องการตรวจสอบโค้ด Apps Script สำหรับโซลูชันนี้ ให้คลิกดูซอร์สโค้ดด้านล่าง

ดูซอร์สโค้ด

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

ขั้นตอนถัดไป