Monitorare le visualizzazioni e i commenti di video di YouTube

Livello di codifica: principiante
Durata: 20 minuti
Tipo di progetto: automazione con un trigger basato sul tempo

Obiettivi

  • Comprendere il funzionamento della soluzione.
  • Comprendere il funzionamento dei servizi Google Apps Script all'interno della soluzione.
  • Configurare lo script.
  • Eseguire lo script.

Informazioni su questa soluzione

Questa soluzione monitora il rendimento dei video pubblici di YouTube, tra cui visualizzazioni, Mi piace e commenti, in un foglio di lavoro di Fogli Google. Il trigger controlla ogni giorno se sono state aggiornate le informazioni e invia un messaggio Gmail se i video hanno una nuova attività di commenti, in modo che tu possa rispondere a domande e commenti.

Foglio Google che mostra i dati di monitoraggio dei video di YouTube

Come funziona

Lo script utilizza il servizio avanzato di YouTube per ottenere i dettagli e le statistiche dei video di YouTube per gli URL dei video elencati nella colonna Link video di ogni foglio. Se il numero di commenti per un video elencato è aumentato, lo script invia una notifica via email all'indirizzo email con cui è stato denominato il foglio.

Servizi Apps Script

Questa soluzione utilizza i seguenti servizi:

Prerequisiti

Per utilizzare questo esempio, devi soddisfare i seguenti prerequisiti:

  • Un Account Google (gli account Google Workspace potrebbero richiedere l'approvazione dell'amministratore).
  • Un browser web con accesso a internet.

Configurare lo script

Per configurare questo script:

Creare il progetto Apps Script

  1. Per creare una copia del fog0}Monitora visualizzazioni e commenti dei video di YouTube foglio di lavoro, fai clic sul seguente pulsante: Crea una copia Il progetto Apps Script per questa soluzione è allegato al foglio di lavoro.
  2. Nel foglio di lavoro copiato, cambia il nome del foglio Your_Email_Address con il tuo indirizzo email.
  3. Aggiungi gli URL dei video di YouTube che vuoi monitorare o utilizza gli URL forniti per i test. Gli URL devono iniziare con il formato www.youtube.com/watch?v=.
  4. Fai clic su Estensioni > Apps Script. Se YouTube è già elencato in Servizi, puoi saltare i due passaggi successivi.
  5. Accanto a Servizi, fai clic su Aggiungi un servizio .
  6. Dall'elenco, seleziona API YouTube Data e fai clic su Aggiungi.

Creare un trigger

  1. Nel progetto Apps Script, fai clic su Trigger > Aggiungi trigger.
  2. In Scegli la funzione da eseguire, seleziona markVideos.
  3. In Seleziona origine evento, seleziona Basato sul tempo.
  4. In Seleziona tipo di trigger basato sul tempo, seleziona Timer giornaliero.
  5. In Seleziona l'ora del giorno, scegli l'ora che preferisci.
  6. Quando ti viene richiesto, autorizza lo script. <<../_snippets/oauth.md>>

Eseguire lo script

Il trigger che hai configurato esegue lo script una volta al giorno. Puoi eseguire lo script manualmente per testarlo.

  1. Nel progetto Apps Script, fai clic su Editor .
  2. Nel menu a discesa della funzione, seleziona markVideos.
  3. Fai clic su Esegui.
  4. Torna al foglio di lavoro per esaminare le informazioni che lo script ha aggiunto al foglio.
  5. Apri l'email per esaminare l'email con l'elenco dei video che hanno più di zero commenti. Quando lo script verrà eseguito in futuro, invierà un'email solo con i video il cui conteggio dei commenti è aumentato dall'ultima esecuzione dello script.

Esaminare il codice

Per esaminare il codice Apps Script per questa soluzione, fai clic su Visualizza codice sorgente:

Visualizza codice sorgente

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() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

  // Runs through process for each tab in Spreadsheet.
  for (const dataSheet of sheets) {
    const tabName = dataSheet.getName();
    const range = dataSheet.getDataRange();
    const numRows = range.getNumRows();
    const rows = range.getValues();
    const headerRow = rows[0];

    // Finds the column indices.
    const videoColumnIdx = headerRow.indexOf(COLUMN_NAME.VIDEO);
    const titleColumnIdx = headerRow.indexOf(COLUMN_NAME.TITLE);

    // Creates empty array to collect data for email table.
    const emailContent = [];

    // Processes each row in spreadsheet.
    for (let i = 1; i < numRows; ++i) {
      const row = rows[i];
      // Extracts video ID.
      const 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.
      const detailsResponse = getVideoDetails(videoId);
      const title = detailsResponse.items[0].snippet.title;
      const publishDate = detailsResponse.items[0].snippet.publishedAt;
      const publishDateFormatted = new Date(publishDate);
      const views = detailsResponse.items[0].statistics.viewCount;
      const likes = detailsResponse.items[0].statistics.likeCount;
      const comments = detailsResponse.items[0].statistics.commentCount;
      const channel = detailsResponse.items[0].snippet.channelTitle;

      // Collects title, publish date, channel, views, comments, likes details and pastes into tab.
      const 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.
      const addlCommentCount = comments - row[titleColumnIdx + 4];

      // Adds video title, link, and additional comment count to table if new counts > old counts.
      if (addlCommentCount > 0) {
        const 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) {
  const part = "snippet,statistics";
  const 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];
  const 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) {
  const template = HtmlService.createTemplateFromFile("email");
  template.content = content;
  const 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>

Collaboratori

Questo esempio è gestito da Google con l'aiuto di Esperti Google Developers.

Passaggi successivi