Apps Script 程式碼範例

以下 Apps Script 程式碼範例適用於 YouTube Data API。您可以從 GitHub 上的 YouTube API 程式碼範例存放區apps-script 資料夾下載這些程式碼範例。

擷取上傳內容

這個函式會擷取目前指令碼使用者上傳的影片。執行這項操作需要 YouTube 的 OAuth 讀取/寫入範圍,以及使用者授權。在 Apps Script 的執行階段環境中,使用者第一次執行指令碼時,Apps Script 會提示使用者授予權限,以便存取指令碼所呼叫的服務。授予權限後,系統會將權限快取一段時間。當所需權限發生變更,或遭 ScriptApp.invalidateAuth() 函式判定為無效時,執行指令碼的使用者將會再次收到權限提示。

這段指令碼會採取下列步驟,擷取活躍使用者上傳的影片:
  1. 擷取使用者的頻道。
  2. 擷取使用者的「上傳」播放清單。
  3. 逐一檢查這個播放清單,並記錄影片 ID 和標題。
  4. 擷取下一頁憑證 (如果有的話)。如果有下一頁,則擷取該頁面。重複步驟 3。
/**
 * This function retrieves the current script user's uploaded videos. To execute,
 * it requires the OAuth read/write scope for YouTube as well as user authorization.
 * In Apps Script's runtime environment, the first time a user runs a script, Apps
 * Script will prompt the user for permission to access the services called by the
 * script. After permissions are granted, they are cached for some periodF of time.
 * The user running the script will be prompted for permission again once the
 * permissions required change, or when they are invalidated by the
 * ScriptApp.invalidateAuth() function.
 *
 * This script takes the following steps to retrieve the active user's uploaded videos:
 *    1. Fetches the user's channels
 *    2. Fetches the user's 'uploads' playlist
 *    3. Iterates through this playlist and logs the video IDs and titles
 *    4. Fetches a next page token (if any). If there is one, fetches the next page. GOTO Step 3
 */
function retrieveMyUploads() {
  var results = YouTube.Channels.list('contentDetails', {mine: true});
  for(var i in results.items) {
    var item = results.items[i];
    // Get the playlist ID, which is nested in contentDetails, as described in the
    // Channel resource: https://developers.google.com/youtube/v3/docs/channels
    var playlistId = item.contentDetails.relatedPlaylists.uploads;

    var nextPageToken = '';

    // This loop retrieves a set of playlist items and checks the nextPageToken in the
    // response to determine whether the list contains additional items. It repeats that process
    // until it has retrieved all of the items in the list.
    while (nextPageToken != null) {
      var playlistResponse = YouTube.PlaylistItems.list('snippet', {
        playlistId: playlistId,
        maxResults: 25,
        pageToken: nextPageToken
      });

      for (var j = 0; j < playlistResponse.items.length; j++) {
        var playlistItem = playlistResponse.items[j];
        Logger.log('[%s] Title: %s',
                   playlistItem.snippet.resourceId.videoId,
                   playlistItem.snippet.title);

      }
      nextPageToken = playlistResponse.nextPageToken;
    }
  }
}

依關鍵字搜尋

這個函式會搜尋與關鍵字 'dogs' 相關的影片。搜尋結果的影片 ID 和標題會記錄到 Apps Script 的記錄中。

請注意,這個範例會將結果限制在 25 個。如要傳回更多結果,請按照「Search:list」一文所述,傳遞其他參數。
/**
 * This function searches for videos related to the keyword 'dogs'. The video IDs and titles
 * of the search results are logged to Apps Script's log.
 *
 * Note that this sample limits the results to 25. To return more results, pass
 * additional parameters as documented here:
 *   https://developers.google.com/youtube/v3/docs/search/list
 */
function searchByKeyword() {
  var results = YouTube.Search.list('id,snippet', {q: 'dogs', maxResults: 25});
  for(var i in results.items) {
    var item = results.items[i];
    Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
  }
}

依主題搜尋

這個函式會搜尋與特定 Freebase 主題相關聯的影片,並將影片 ID 和標題記錄到 Apps Script 記錄檔。本範例使用 Google Apps Script 的專題 ID。

請注意,這個範例會將結果限制在 25 個。如要傳回更多結果,請按照「Search:list」一文所述,傳遞其他參數。
/**
 * This function searches for videos that are associated with a particular Freebase
 * topic, logging their video IDs and titles to the Apps Script log. This example uses
 * the topic ID for Google Apps Script.
 *
 * Note that this sample limits the results to 25. To return more results, pass
 * additional parameters as documented here:
 *   https://developers.google.com/youtube/v3/docs/search/list
 */
function searchByTopic() {
  var mid = '/m/0gjf126';
  var results = YouTube.Search.list('id,snippet', {topicId: mid, maxResults: 25});
  for(var i in results.items) {
    var item = results.items[i];
    Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
  }
}

訂閱頻道

這個範例會將活躍使用者訂閱由 channelId 指定的 Google Developers YouTube 頻道。
/**
 * This sample subscribes the active user to the Google Developers
 * YouTube channel, specified by the channelId.
 */
function addSubscription() {
  // Replace this channel ID with the channel ID you want to subscribe to
  var channelId = 'UC_x5XG1OV2P6uZZ5FSM9Ttw';
  var resource = {
    snippet: {
      resourceId: {
        kind: 'youtube#channel',
        channelId: channelId
      }
    }
  };

  try {
    var response = YouTube.Subscriptions.insert(resource, 'snippet');
    Logger.log(response);
  } catch (e) {
    if(e.message.match('subscriptionDuplicate')) {
      Logger.log('Cannot subscribe; already subscribed to channel: ' + channelId);
    } else {
      Logger.log('Error adding subscription: ' + e.message);
    }
  }
}

更新影片

這個範例會找出使用中的上傳內容,然後附加字串來更新最近一次上傳內容的說明。
/**
 * This sample finds the active user's uploads, then updates the most recent
 * upload's description by appending a string.
 */
function updateVideo() {
  // 1. Fetch all the channels owned by active user
  var myChannels = YouTube.Channels.list('contentDetails', {mine: true});
  // 2. Iterate through the channels and get the uploads playlist ID
  for (var i = 0; i < myChannels.items.length; i++) {
    var item = myChannels.items[i];
    var uploadsPlaylistId = item.contentDetails.relatedPlaylists.uploads;

    var playlistResponse = YouTube.PlaylistItems.list('snippet', {
      playlistId: uploadsPlaylistId,
      maxResults: 1
    });

    // Get the videoID of the first video in the list
    var video = playlistResponse.items[0];
    var originalDescription = video.snippet.description;
    var updatedDescription = originalDescription + ' Description updated via Google Apps Script';

    video.snippet.description = updatedDescription;

    var resource = {
      snippet: {
        title: video.snippet.title,
        description: updatedDescription,
        categoryId: '22'
      },
      id: video.snippet.resourceId.videoId
    };
    YouTube.Videos.update(resource, 'id,snippet');
  }
}