YouTube 服务

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

借助 YouTube 服务,您可以在 Apps 脚本中使用 YouTube Data APIYouTube Live Streaming API。借助此 API,用户可以管理自己的视频、播放列表、频道和直播活动。

参考

如需详细了解此服务,请参阅以下参考文档:

与 Apps 脚本中的所有高级服务一样,YouTube 服务使用与公共 API 相同的对象、方法和参数。如需了解详情,请参阅如何确定方法签名

要报告问题并查找其他支持,请参阅相应的支持页面:

示例代码

以下示例代码使用 YouTube Data API 版本 3

按关键字进行搜索

此函数会搜索有关狗的视频,然后记录视频 ID 和标题。请注意,此示例将结果限制为 25。如需返回更多结果,请传递 YouTube Data API 参考文档中所示的其他参数。

高级/youtube.gs
/**
 * Searches for videos about dogs, then logs the video IDs and title.
 * Note that this sample limits the results to 25. To return more
 * results, pass additional parameters as shown in the YouTube Data API docs.
 * @see https://developers.google.com/youtube/v3/docs/search/list
 */
function searchByKeyword() {
  try {
    const results = YouTube.Search.list('id,snippet', {
      q: 'dogs',
      maxResults: 25
    });
    if (results === null) {
      Logger.log('Unable to search videos');
      return;
    }
    results.items.forEach((item)=> {
      Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
    });
  } catch (err) {
    // TODO (developer) - Handle exceptions from Youtube API
    Logger.log('Failed with an error %s', err.message);
  }
}

检索上传内容

此函数用于检索用户上传的视频。它通过执行以下步骤来实现此目的:

  1. 获取用户的频道
  2. 获取用户的 uploads 播放列表
  3. 遍历此播放列表,并记录视频 ID 和标题
  4. 如果有下一页结果,请提取结果,然后返回到第 3 步
高级/youtube.gs
/**
 * This function retrieves the user's uploaded videos by:
 * 1. Fetching the user's channel's.
 * 2. Fetching the user's "uploads" playlist.
 * 3. Iterating through this playlist and logs the video IDs and titles.
 * 4. If there is a next page of resuts, fetching it and returns to step 3.
 */
function retrieveMyUploads() {
  try {
    // @see https://developers.google.com/youtube/v3/docs/channels/list
    const results = YouTube.Channels.list('contentDetails', {
      mine: true
    });
    if (!results || results.items.length === 0) {
      Logger.log('No Channels found.');
      return;
    }
    for (let i = 0; i < results.items.length; i++) {
      const item = results.items[i];
      /** Get the channel ID - it's nested in contentDetails, as described in the
       * Channel resource: https://developers.google.com/youtube/v3/docs/channels.
       */
      const playlistId = item.contentDetails.relatedPlaylists.uploads;
      let nextPageToken = null;
      do {
        // @see: https://developers.google.com/youtube/v3/docs/playlistItems/list
        const playlistResponse = YouTube.PlaylistItems.list('snippet', {
          playlistId: playlistId,
          maxResults: 25,
          pageToken: nextPageToken
        });
        if (!playlistResponse || playlistResponse.items.length === 0) {
          Logger.log('No Playlist found.');
          break;
        }
        for (let j = 0; j < playlistResponse.items.length; j++) {
          const playlistItem = playlistResponse.items[j];
          Logger.log('[%s] Title: %s',
              playlistItem.snippet.resourceId.videoId,
              playlistItem.snippet.title);
        }
        nextPageToken = playlistResponse.nextPageToken;
      } while (nextPageToken);
    }
  } catch (err) {
    // TODO (developer) - Handle exception
    Logger.log('Failed with err %s', err.message);
  }
}

订阅频道

此示例会将用户订阅到 YouTube 上的 Google Developers 频道。

高级/youtube.gs
/**
 * This sample subscribes the user to the Google Developers channel on YouTube.
 * @see https://developers.google.com/youtube/v3/docs/subscriptions/insert
 */
function addSubscription() {
  // Replace this channel ID with the channel ID you want to subscribe to
  const channelId = 'UC_x5XG1OV2P6uZZ5FSM9Ttw';
  const resource = {
    snippet: {
      resourceId: {
        kind: 'youtube#channel',
        channelId: channelId
      }
    }
  };

  try {
    const response = YouTube.Subscriptions.insert(resource, 'snippet');
    Logger.log('Added subscription for channel title : %s', response.snippet.title);
  } catch (e) {
    if (e.message.match('subscriptionDuplicate')) {
      Logger.log('Cannot subscribe; already subscribed to channel: ' +
        channelId);
    } else {
      // TODO (developer) - Handle exception
      Logger.log('Error adding subscription: ' + e.message);
    }
  }
}