Śledzenie wyświetleń filmów i komentarzy w YouTube

Poziom kodowania: początkujący
Czas trwania: 20 minut
Typ projektu: automatyzacja z wyzwalaczem opartym na czasie

Cele

  • Dowiedz się, co robi rozwiązanie.
  • Dowiedz się, jakie funkcje pełnią usługi Apps Script w rozwiązaniu.
  • Skonfiguruj skrypt.
  • Uruchom skrypt.

Informacje o rozwiązaniu

To rozwiązanie śledzi w arkuszu kalkulacyjnym Google Arkusze skuteczność publicznych filmów w YouTube, w tym wyświetlenia, polubienia i komentarze. Wywołanie codziennie sprawdza, czy są nowe informacje, i wysyła e-maila, jeśli w filmach pojawiły się nowe komentarze. Dzięki temu możesz odpowiadać na pytania i komentarze.

Zrzut ekranu przedstawiający dane z YouTube w Arkuszach Google

Jak to działa

Skrypt korzysta z zaawansowanej usługi YouTube, aby pobierać szczegóły i statystyki filmów w YouTube na podstawie adresów URL filmów wymienionych w kolumnie Link do filmu w każdym arkuszu. Jeśli liczba komentarzy do wymienionego filmu wzrośnie, skrypt wyśle powiadomienie e-mail na adres e-mail, od którego pochodzi nazwa arkusza.

Usługi Apps Script

To rozwiązanie korzysta z tych usług:

Wymagania wstępne

Aby użyć tego przykładu, musisz spełnić te wymagania wstępne:

  • Konto Google (w przypadku kont Google Workspace może być wymagana zgoda administratora).
  • przeglądarkę internetową z dostępem do internetu,

Konfigurowanie skryptu

Tworzenie projektu Apps Script

  1. Kliknij poniższy przycisk, aby utworzyć kopię arkusza Śledzenie wyświetleń i komentarzy do filmów w YouTube. Projekt Apps Script dla tego rozwiązania jest dołączony do arkusza kalkulacyjnego.
    Utwórz kopię
  2. W skopiowanym arkuszu zmień nazwę arkusza Your_Email_Address na swój adres e-mail.
  3. Dodaj adresy URL filmów w YouTube, które chcesz śledzić, lub użyj podanych adresów URL do testowania. Adresy URL muszą zaczynać się od www.youtube.com/watch?v=.
  4. Kliknij Rozszerzenia > Apps Script. Jeśli YouTube jest już wymieniony w sekcji Usługi, możesz przejść do następnych 2 kroków.
  5. Obok opcji Usługi kliknij Dodaj usługę.
  6. Na liście wybierz YouTube Data API i kliknij Dodaj.

Utwórz aktywator

  1. W projekcie Apps Script kliknij Reguły > Dodaj regułę.
  2. W sekcji Wybierz funkcję do uruchomienia kliknij markVideos.
  3. W sekcji Wybierz źródło zdarzeń kliknij Oparte na czasie.
  4. W sekcji Wybierz typ aktywatora opartego na czasie kliknij Timer dzienny.
  5. W sekcji Wybierz porę dnia wybierz preferowaną godzinę.
  6. Gdy pojawi się odpowiedni komunikat, autoryzuj skrypt. Jeśli na ekranie zgody OAuth wyświetla się ostrzeżenie Ta aplikacja nie została zweryfikowana, kliknij kolejno Zaawansowane > Otwórz {Project Name} (niebezpieczne).

Uruchamianie skryptu

Skonfigurowany przez Ciebie aktywator uruchamia skrypt raz dziennie. Możesz uruchomić skrypt ręcznie, aby go przetestować.

  1. W projekcie Apps Script kliknij Edytor .
  2. W menu funkcji wybierz markVideos.
  3. Kliknij Wykonaj.
  4. Wróć do arkusza kalkulacyjnego, aby sprawdzić informacje dodane do niego przez skrypt.
  5. Otwórz e-maila z listą filmów, które mają więcej niż 0 komentarzy. Gdy skrypt zostanie uruchomiony w przyszłości, wyśle tylko e-maila z filmami, których liczba komentarzy wzrosła od ostatniego uruchomienia skryptu.

Sprawdź kod

Aby sprawdzić kod Apps Script tego rozwiązania, kliknij poniżej Wyświetl kod źródłowy:

Pokaż kod źródłowy

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>

Współtwórcy

Ten przykład jest obsługiwany przez Google przy pomocy ekspertów Google ds. programowania.

Dalsze kroki