YouTube-Videoaufrufe und Kommentare verfolgen

Programmierstufe: Anfänger
Dauer: 20 Minuten
Projekttyp: Automatisierung mit einem zeitgesteuerten Trigger

Zielsetzungen

  • Verstehen Sie, was die Lösung leisten kann.
  • Was die Apps Script-Dienste innerhalb der Lösung leisten
  • Richten Sie das Skript ein.
  • Führen Sie das Skript aus.

Informationen zu dieser Lösung

Diese Lösung verfolgt die Leistung öffentlicher YouTube-Videos, einschließlich der Aufrufe, „Mag ich“-Bewertungen und Kommentare, in einer Google Tabellen-Tabelle. Der Trigger prüft jeden Tag auf aktualisierte Informationen und sendet eine E-Mail, wenn es bei Videos neue Kommentaraktivitäten gibt, damit Sie auf Fragen und Kommentare reagieren können.

Screenshot von YouTube-Daten in einer Google-Tabelle

Funktionsweise

Das Skript nutzt den erweiterten YouTube-Dienst, um Details und Statistiken zu YouTube-Videos zu den Video-URLs abzurufen, die in jedem Tabellenblatt in der Spalte Videolink aufgeführt sind. Wenn die Anzahl der Kommentare für ein aufgelistetes Video gestiegen ist, sendet das Skript eine E-Mail-Benachrichtigung an die E-Mail-Adresse, nach der das Tabellenblatt benannt ist.

Apps Script-Dienste

Diese Lösung verwendet die folgenden Dienste:

Voraussetzungen

Sie benötigen die folgenden Voraussetzungen, um dieses Beispiel verwenden zu können:

  • Ein Google-Konto (Google Workspace-Konten erfordern möglicherweise die Administratorgenehmigung).
  • Ein Webbrowser mit Zugang zum Internet.

Skript einrichten

Apps Script-Projekt erstellen

  1. Klicken Sie auf die folgende Schaltfläche, um eine Kopie der Tabelle YouTube-Videoaufrufe und -kommentare verfolgen zu erstellen. Das Apps Script-Projekt für diese Lösung ist an die Tabelle angehängt.
    Kopie erstellen
  2. Ändern Sie in der kopierten Tabelle den Namen des Tabellenblatts Your_Email_Address in Ihre E-Mail-Adresse.
  3. Fügen Sie die URLs der YouTube-Videos hinzu, die Sie erfassen möchten, oder verwenden Sie die angegebenen URLs für Testzwecke. Die URLs müssen im Format www.youtube.com/watch?v= beginnen.
  4. Klicken Sie auf Erweiterungen > Apps Script. Wenn YouTube bereits unter Dienste aufgeführt ist, können Sie mit den nächsten beiden Schritten fortfahren.
  5. Klicken Sie neben Dienste auf „Dienst hinzufügen“ .
  6. Wähle in der Liste YouTube Data API aus und klicke auf Hinzufügen.

Trigger erstellen

  1. Klicken Sie im Apps Script-Projekt auf Trigger > Trigger hinzufügen.
  2. Wählen Sie unter Funktion auswählen, die ausgeführt werden soll die Option markVideos aus.
  3. Wählen Sie für Ereignisquelle auswählen die Option Zeitgesteuert aus.
  4. Wählen Sie unter Typ des zeitbasierten Triggers auswählen die Option Tagestimer aus.
  5. Wählen Sie unter Uhrzeit auswählen die gewünschte Zeit aus.
  6. Autorisieren Sie das Skript, wenn Sie dazu aufgefordert werden. Wenn auf dem OAuth-Zustimmungsbildschirm die Warnung Diese Anwendung wurde nicht überprüft angezeigt wird, wählen Sie Erweitert > Zu {Projektname} (unsicher) aus.

Skript ausführen

Der von Ihnen eingerichtete Trigger führt das Skript einmal täglich aus. Sie können das Skript zum Testen manuell ausführen.

  1. Klicken Sie im Apps Script-Projekt auf Editor .
  2. Wählen Sie im Drop-down-Menü der Funktion markVideos aus.
  3. Klicken Sie auf Ausführen.
  4. Wechseln Sie zurück zur Tabelle, um die Informationen zu überprüfen, die das Skript dem Tabellenblatt hinzugefügt hat.
  5. Öffne deine E-Mail, um die E-Mail mit der Liste der Videos mit mehr als null Kommentaren zu überprüfen. Wenn das Skript in Zukunft ausgeführt wird, sendet es nur eine E-Mail mit Videos, deren Anzahl an Kommentaren seit der letzten Ausführung des Skripts zugenommen hat.

Code ansehen

Wenn Sie den Apps Script-Code für diese Lösung sehen möchten, klicken Sie unten auf Quellcode ansehen:

Quellcode ansehen

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>

Beitragende

Dieses Beispiel wird von Google mit Unterstützung von Google Developers-Experten verwaltet.

Nächste Schritte