ردیابی بازدیدهای ویدیوی YouTube & نظرات

سطح کدنویسی : مبتدی
مدت زمان : ۲۰ دقیقه
نوع پروژه : اتوماسیون با محرک زمان

اهداف

  • بفهمید که راه حل چه کاری انجام می‌دهد.
  • درک کنید که سرویس‌های Apps Script در این راهکار چه کاری انجام می‌دهند.
  • اسکریپت را تنظیم کنید.
  • اسکریپت را اجرا کنید.

درباره این راهکار

این راهکار، عملکرد ویدیوهای عمومی یوتیوب، شامل بازدیدها، لایک‌ها و نظرات را در یک صفحه گسترده گوگل شیت ردیابی می‌کند. این تریگر هر روز اطلاعات به‌روز شده را بررسی می‌کند و اگر ویدیوها فعالیت نظرات جدیدی داشته باشند، یک پیام جیمیل ارسال می‌کند تا بتوانید با سوالات و نظرات درگیر شوید.

تصویر صفحه داده‌های یوتیوب در یک صفحه گوگل

چگونه کار می‌کند؟

این اسکریپت از سرویس پیشرفته یوتیوب برای دریافت جزئیات و آمار ویدیوهای یوتیوب برای URL های ویدیویی ذکر شده در ستون لینک ویدیو در هر برگه استفاده می‌کند. اگر تعداد نظرات برای یک ویدیوی ذکر شده افزایش یافته باشد، اسکریپت یک اعلان ایمیل به آدرس ایمیلی که برگه به ​​نام آن نامگذاری شده است، ارسال می‌کند.

سرویس‌های اسکریپت برنامه‌ها

این راهکار از سرویس‌های زیر استفاده می‌کند:

پیش‌نیازها

برای استفاده از این نمونه، به پیش‌نیازهای زیر نیاز دارید:

  • یک حساب گوگل (حساب‌های کاربری گوگل ورک‌اسپیس ممکن است نیاز به تأیید مدیر داشته باشند).
  • یک مرورگر وب با دسترسی به اینترنت.

اسکریپت را تنظیم کنید

پروژه Apps Script را ایجاد کنید

  1. برای ایجاد یک کپی از صفحه گسترده Track YouTube views and comments، روی دکمه زیر کلیک کنید. پروژه Apps Script برای این راهکار به صفحه گسترده پیوست شده است.
    یک کپی تهیه کنید
  2. در صفحه گسترده کپی شده خود، نام برگه Your_Email_Address را به آدرس ایمیل خود تغییر دهید.
  3. آدرس‌های اینترنتی ویدیوهای یوتیوبی که می‌خواهید ردیابی کنید را اضافه کنید یا از آدرس‌های اینترنتی ارائه شده برای آزمایش استفاده کنید. آدرس‌های اینترنتی باید با فرمت www.youtube.com/watch?v= شروع شوند.
  4. روی افزونه‌ها > اسکریپت برنامه‌ها کلیک کنید. اگر یوتیوب از قبل در بخش خدمات فهرست شده است، می‌توانید به دو مرحله بعدی بروید.
  5. در کنار سرویس‌ها ، روی سرویس کلیک کنید.
  6. از لیست، YouTube Data API را انتخاب کنید و روی افزودن کلیک کنید.

یک تریگر ایجاد کنید

  1. در پروژه Apps Script، روی Triggers > Add trigger کلیک کنید.
  2. برای انتخاب تابعی که اجرا شود ، markVideos را انتخاب کنید.
  3. برای انتخاب منبع رویداد ، گزینه Time-driven را انتخاب کنید.
  4. برای انتخاب نوع تریگر مبتنی بر زمان ، تایمر روز را انتخاب کنید.
  5. برای انتخاب زمان روز ، زمان مورد نظر خود را انتخاب کنید.
  6. وقتی از شما خواسته شد، اسکریپت را تأیید کنید. اگر صفحه رضایت OAuth هشدار « این برنامه تأیید نشده است» را نشان می‌دهد، با انتخاب Advanced > Go to {Project Name} (unsafe) ادامه دهید.

اسکریپت را اجرا کنید

تریگری که تنظیم می‌کنید، اسکریپت را روزی یک بار اجرا می‌کند. می‌توانید اسکریپت را به صورت دستی اجرا کنید تا آن را آزمایش کنید.

  1. در پروژه Apps Script، روی Editor کلیک کنید.
  2. در منوی کشویی تابع، markVideos را انتخاب کنید.
  3. روی اجرا کلیک کنید.
  4. برای بررسی اطلاعاتی که اسکریپت به برگه اضافه کرده است، به صفحه گسترده برگردید.
  5. ایمیل خود را باز کنید تا لیست ویدیوهایی که بیش از صفر نظر دارند را بررسی کنید. وقتی اسکریپت در آینده اجرا شود، فقط ایمیلی حاوی ویدیوهایی ارسال می‌کند که تعداد نظرات آنها از آخرین باری که اسکریپت اجرا شده افزایش یافته است.

کد را مرور کنید

برای بررسی کد Apps Script برای این راهکار، روی مشاهده کد منبع در زیر کلیک کنید:

مشاهده کد منبع

کد.gs

راهکارها/اتوماسیون‌ها/یوتیوب-ردیاب/کد.جی‌اس
// 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()});
}

ایمیل.html

راهکارها/اتوماسیون‌ها/یوتیوب-ردیاب/ایمیل.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>

مشارکت‌کنندگان

این نمونه توسط گوگل و با کمک متخصصان توسعه‌دهنده گوگل نگهداری می‌شود.

مراحل بعدی

،

سطح کدنویسی : مبتدی
مدت زمان : ۲۰ دقیقه
نوع پروژه : اتوماسیون با محرک زمان

اهداف

  • بفهمید که راه حل چه کاری انجام می‌دهد.
  • درک کنید که سرویس‌های Apps Script در این راهکار چه کاری انجام می‌دهند.
  • اسکریپت را تنظیم کنید.
  • اسکریپت را اجرا کنید.

درباره این راهکار

این راهکار، عملکرد ویدیوهای عمومی یوتیوب، شامل بازدیدها، لایک‌ها و نظرات را در یک صفحه گسترده گوگل شیت ردیابی می‌کند. این تریگر هر روز اطلاعات به‌روز شده را بررسی می‌کند و اگر ویدیوها فعالیت نظرات جدیدی داشته باشند، یک پیام جیمیل ارسال می‌کند تا بتوانید با سوالات و نظرات درگیر شوید.

تصویر صفحه داده‌های یوتیوب در یک صفحه گوگل

چگونه کار می‌کند؟

این اسکریپت از سرویس پیشرفته یوتیوب برای دریافت جزئیات و آمار ویدیوهای یوتیوب برای URL های ویدیویی ذکر شده در ستون لینک ویدیو در هر برگه استفاده می‌کند. اگر تعداد نظرات برای یک ویدیوی ذکر شده افزایش یافته باشد، اسکریپت یک اعلان ایمیل به آدرس ایمیلی که برگه به ​​نام آن نامگذاری شده است، ارسال می‌کند.

سرویس‌های اسکریپت برنامه‌ها

این راهکار از سرویس‌های زیر استفاده می‌کند:

پیش‌نیازها

برای استفاده از این نمونه، به پیش‌نیازهای زیر نیاز دارید:

  • یک حساب گوگل (حساب‌های کاربری گوگل ورک‌اسپیس ممکن است نیاز به تأیید مدیر داشته باشند).
  • یک مرورگر وب با دسترسی به اینترنت.

اسکریپت را تنظیم کنید

پروژه Apps Script را ایجاد کنید

  1. برای ایجاد یک کپی از صفحه گسترده Track YouTube views and comments، روی دکمه زیر کلیک کنید. پروژه Apps Script برای این راهکار به صفحه گسترده پیوست شده است.
    یک کپی تهیه کنید
  2. در صفحه گسترده کپی شده خود، نام برگه Your_Email_Address را به آدرس ایمیل خود تغییر دهید.
  3. آدرس‌های اینترنتی ویدیوهای یوتیوبی که می‌خواهید ردیابی کنید را اضافه کنید یا از آدرس‌های اینترنتی ارائه شده برای آزمایش استفاده کنید. آدرس‌های اینترنتی باید با فرمت www.youtube.com/watch?v= شروع شوند.
  4. روی افزونه‌ها > اسکریپت برنامه‌ها کلیک کنید. اگر یوتیوب از قبل در بخش خدمات فهرست شده است، می‌توانید به دو مرحله بعدی بروید.
  5. در کنار سرویس‌ها ، روی سرویس کلیک کنید.
  6. از لیست، YouTube Data API را انتخاب کنید و روی افزودن کلیک کنید.

یک تریگر ایجاد کنید

  1. در پروژه Apps Script، روی Triggers > Add trigger کلیک کنید.
  2. برای انتخاب تابعی که اجرا شود ، markVideos را انتخاب کنید.
  3. برای انتخاب منبع رویداد ، گزینه Time-driven را انتخاب کنید.
  4. برای انتخاب نوع تریگر مبتنی بر زمان ، تایمر روز را انتخاب کنید.
  5. برای انتخاب زمان روز ، زمان مورد نظر خود را انتخاب کنید.
  6. وقتی از شما خواسته شد، اسکریپت را تأیید کنید. اگر صفحه رضایت OAuth هشدار « این برنامه تأیید نشده است» را نشان می‌دهد، با انتخاب Advanced > Go to {Project Name} (unsafe) ادامه دهید.

اسکریپت را اجرا کنید

تریگری که تنظیم می‌کنید، اسکریپت را روزی یک بار اجرا می‌کند. می‌توانید اسکریپت را به صورت دستی اجرا کنید تا آن را آزمایش کنید.

  1. در پروژه Apps Script، روی Editor کلیک کنید.
  2. در منوی کشویی تابع، markVideos را انتخاب کنید.
  3. روی اجرا کلیک کنید.
  4. برای بررسی اطلاعاتی که اسکریپت به برگه اضافه کرده است، به صفحه گسترده برگردید.
  5. ایمیل خود را باز کنید تا لیست ویدیوهایی که بیش از صفر نظر دارند را بررسی کنید. وقتی اسکریپت در آینده اجرا شود، فقط ایمیلی حاوی ویدیوهایی ارسال می‌کند که تعداد نظرات آنها از آخرین باری که اسکریپت اجرا شده افزایش یافته است.

کد را مرور کنید

برای بررسی کد Apps Script برای این راهکار، روی مشاهده کد منبع در زیر کلیک کنید:

مشاهده کد منبع

کد.gs

راهکارها/اتوماسیون‌ها/یوتیوب-ردیاب/کد.جی‌اس
// 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()});
}

ایمیل.html

راهکارها/اتوماسیون‌ها/یوتیوب-ردیاب/ایمیل.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>

مشارکت‌کنندگان

این نمونه توسط گوگل و با کمک متخصصان توسعه‌دهنده گوگل نگهداری می‌شود.

مراحل بعدی