تتبُّع المشاهدات والتعليقات للفيديوهات على YouTube

مستوى الترميز: مبتدئ
المدة: 20 دقيقة
نوع المشروع: أتمتة باستخدام مشغّل يستند إلى الوقت

الأهداف

  • فهم ما يفعله الحلّ
  • فهم وظائف خدمات Apps Script ضمن الحلّ
  • إعداد النص البرمجي
  • شغِّل النص البرمجي.

لمحة عن هذا الحل

يتتبّع هذا الحلّ أداء فيديوهات YouTube العلنية، بما في ذلك عدد المشاهدات والإعجابات والتعليقات، في جدول بيانات Google. يتحقّق المشغّل من المعلومات المعدَّلة كل يوم ويرسل رسالة Gmail إذا كان هناك نشاط جديد في التعليقات على الفيديوهات، ما يتيح لك التفاعل مع الأسئلة والتعليقات.

لقطة شاشة لبيانات YouTube في جدول بيانات Google

آلية العمل

يستخدم النص البرمجي خدمة YouTube المتقدّمة للحصول على تفاصيل فيديو YouTube وإحصاءاته لعناوين URL للفيديوهات المدرَجة في عمود رابط الفيديو في كل ورقة. إذا زاد عدد التعليقات على فيديو مُدرَج، يرسل النص البرمجي إشعارًا عبر البريد الإلكتروني إلى عنوان البريد الإلكتروني الذي تم تسمية ورقة البيانات باسمه.

خدمات "برمجة تطبيقات Google"

يستخدم هذا الحل الخدمات التالية:

  • خدمة جدول البيانات: للحصول على معلومات عناوين URL على YouTube من جدول البيانات
  • خدمة YouTube Data API المتقدّمة: للحصول على تفاصيل الفيديو وإحصاءاته لكل عنوان URL خاص بالفيديو على YouTube.
  • خدمة البريد: تنشئ هذه الخدمة رسالة إلكترونية وترسلها في Gmail تتضمّن قائمة بالفيديوهات التي تتضمّن تعليقات جديدة.

المتطلبات الأساسية

لاستخدام هذا النموذج، يجب استيفاء المتطلبات الأساسية التالية:

  • حساب Google (قد تتطلّب حسابات Google Workspace موافقة المشرف).
  • متصفّح ويب يمكنه الوصول إلى الإنترنت

إعداد النص البرمجي

إنشاء مشروع "برمجة تطبيقات Google"

  1. انقر على الزر التالي لإنشاء نسخة من جدول البيانات تتبُّع عدد مشاهدات فيديوهات YouTube والتعليقات عليها. مشروع "برمجة التطبيقات" الخاص بهذا الحل مرفق بجدول البيانات.
    إنشاء نسخة
  2. في جدول البيانات الذي نسخته، غيِّر اسم ورقة Your_Email_Address إلى عنوان بريدك الإلكتروني.
  3. أضِف عناوين URL للفيديوهات على YouTube التي تريد تتبُّعها أو استخدِم عناوين URL المتوفّرة للاختبار. يجب أن تبدأ عناوين URL بالتنسيق www.youtube.com/watch?v=.
  4. انقر على الإضافات > برمجة تطبيقات Google. إذا كان YouTube مُدرجًا ضمن الخدمات، يمكنك الانتقال إلى الخطوتَين التاليتَين.
  5. بجانب الخدمات، انقر على "إضافة خدمة" .
  6. من القائمة، اختَر YouTube Data API وانقر على إضافة.

إنشاء مشغّل

  1. في مشروع Apps Script، انقر على المشغّلات > إضافة مشغّل.
  2. في اختيار الدالة المطلوب تشغيلها، اختَر markVideos.
  3. بالنسبة إلى اختيار مصدر الحدث، اختَر مستند إلى الوقت.
  4. بالنسبة إلى اختيار نوع عامل التشغيل المستند إلى الوقت، اختَر مؤقت اليوم.
  5. بالنسبة إلى اختيار وقت من اليوم، اختَر الوقت المفضّل لديك.
  6. امنح الإذن للنصّ البرمجي عند مطالبتك بذلك. إذا عرضت شاشة الموافقة على OAuth التحذير لم يتم التحقّق من هذا التطبيق، يمكنك المتابعة من خلال النقر على خيارات متقدمة > الانتقال إلى {اسم المشروع} (غير آمن).

تشغيل النص البرمجي

يتم تشغيل النص البرمجي مرة واحدة يوميًا باستخدام المشغّل الذي أعددته. يمكنك تنفيذ النص البرمجي يدويًا لاختباره.

  1. في مشروع Apps Script، انقر على المحرّر .
  2. في القائمة المنسدلة الخاصة بالدالة، اختَر markVideos.
  3. انقر على تشغيل.
  4. عُد إلى جدول البيانات لمراجعة المعلومات التي أضافها النص البرمجي إلى الورقة.
  5. افتح بريدك الإلكتروني لمراجعة الرسالة الإلكترونية التي تتضمّن قائمة بالفيديوهات التي تتضمّن أكثر من صفر تعليق. عند تشغيل البرنامج النصي في المستقبل، سيرسل رسالة إلكترونية تتضمّن الفيديوهات التي زاد عدد تعليقاتها منذ آخر مرة تم فيها تشغيل البرنامج النصي.

مراجعة الرمز البرمجي

لمراجعة رمز 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 المطوّرين.

الخطوات التالية