Dịch vụ YouTube

Dịch vụ YouTube cho phép bạn sử dụng API dữ liệu YouTubeAPI phát trực tiếp trên YouTube trong Apps Script. API này cho phép người dùng quản lý video, danh sách phát, kênh và sự kiện trực tiếp của họ.

Tài liệu tham khảo

Để biết thông tin chi tiết về dịch vụ này, hãy xem tài liệu tham khảo sau:

Giống như tất cả các dịch vụ nâng cao trong Apps Script, dịch vụ YouTube sử dụng các đối tượng, phương thức và tham số giống như API công khai. Để biết thêm thông tin, hãy xem bài viết Cách xác định chữ ký phương thức.

Để báo cáo sự cố và tìm hỗ trợ khác, hãy xem các trang hỗ trợ tương ứng:

Mã mẫu

Mã mẫu bên dưới sử dụng phiên bản 3 của API Dữ liệu YouTube.

Tìm kiếm theo từ khoá

Chức năng này tìm kiếm video về chó, sau đó ghi nhật ký mã video và tiêu đề. Xin lưu ý rằng mẫu này giới hạn kết quả là 25. Để trả về nhiều kết quả hơn, hãy truyền các thông số bổ sung như trong tài liệu tham khảo về API dữ liệu YouTube.

advanced/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) {
      console.log('Unable to search videos');
      return;
    }
    results.items.forEach((item)=> {
      console.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
    });
  } catch (err) {
    // TODO (developer) - Handle exceptions from Youtube API
    console.log('Failed with an error %s', err.message);
  }
}

Truy xuất tệp đã tải lên

Hàm này truy xuất video đã tải lên của người dùng. Bạn có thể thực hiện việc này theo các bước sau:

  1. Tìm nạp kênh của người dùng
  2. Tìm nạp danh sách phát uploads của người dùng
  3. Lặp lại thông qua danh sách phát này và ghi lại tiêu đề cũng như mã video
  4. Nếu có trang kết quả tiếp theo, hãy tìm nạp rồi quay lại bước 3
advanced/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) {
      console.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) {
          console.log('No Playlist found.');
          break;
        }
        for (let j = 0; j < playlistResponse.items.length; j++) {
          const playlistItem = playlistResponse.items[j];
          console.log('[%s] Title: %s',
              playlistItem.snippet.resourceId.videoId,
              playlistItem.snippet.title);
        }
        nextPageToken = playlistResponse.nextPageToken;
      } while (nextPageToken);
    }
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed with err %s', err.message);
  }
}

Đăng ký kênh

Mẫu này sẽ đăng ký cho người dùng kênh Google Developers trên YouTube.

advanced/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');
    console.log('Added subscription for channel title : %s', response.snippet.title);
  } catch (e) {
    if (e.message.match('subscriptionDuplicate')) {
      console.log('Cannot subscribe; already subscribed to channel: ' +
        channelId);
    } else {
      // TODO (developer) - Handle exception
      console.log('Error adding subscription: ' + e.message);
    }
  }
}