YouTube 분석 서비스

YouTube 분석 서비스를 사용하면 Apps Script에서 YouTube Analytics API를 사용할 수 있습니다. 이 API를 사용하면 YouTube 동영상 및 채널의 시청 통계, 인기도 측정항목, 인구통계 정보를 가져올 수 있습니다.

참조

이 서비스에 관한 자세한 내용은 YouTube Analytics API의 참조 문서를 참고하세요. Apps Script의 모든 고급 서비스와 마찬가지로 YouTube 분석 서비스는 공개 API와 동일한 객체, 메서드, 매개변수를 사용합니다. 자세한 내용은 메서드 서명 결정 방법을 참고하세요.

샘플 코드

아래 샘플 코드는 YouTube Analytics API의 버전 2와 YouTube Data API의 버전 3을 사용합니다. YouTube Data API는 Apps Script의 YouTube 서비스를 통해 액세스할 수 있습니다.

문제를 신고하고 다른 지원을 확인하려면 YouTube API 지원 가이드를 참고하세요.

보고서 작성

이 함수는 채널 동영상의 일일 조회수, 시청 시간 측정항목, 신규 구독자 수를 포함하는 스프레드시트를 만듭니다.

advanced/youtubeAnalytics.gs
/**
 * Creates a spreadsheet containing daily view counts, watch-time metrics,
 * and new-subscriber counts for a channel's videos.
 */
function createReport() {
  // Retrieve info about the user's YouTube channel.
  const channels = YouTube.Channels.list('id,contentDetails', {
    mine: true
  });
  const channelId = channels.items[0].id;

  // Retrieve analytics report for the channel.
  const oneMonthInMillis = 1000 * 60 * 60 * 24 * 30;
  const today = new Date();
  const lastMonth = new Date(today.getTime() - oneMonthInMillis);

  const metrics = [
    'views',
    'estimatedMinutesWatched',
    'averageViewDuration',
    'subscribersGained'
  ];
  const result = YouTubeAnalytics.Reports.query({
    ids: 'channel==' + channelId,
    startDate: formatDateString(lastMonth),
    endDate: formatDateString(today),
    metrics: metrics.join(','),
    dimensions: 'day',
    sort: 'day'
  });

  if (!result.rows) {
    console.log('No rows returned.');
    return;
  }
  const spreadsheet = SpreadsheetApp.create('YouTube Analytics Report');
  const sheet = spreadsheet.getActiveSheet();

  // Append the headers.
  const headers = result.columnHeaders.map((columnHeader)=> {
    return formatColumnName(columnHeader.name);
  });
  sheet.appendRow(headers);

  // Append the results.
  sheet.getRange(2, 1, result.rows.length, headers.length)
      .setValues(result.rows);

  console.log('Report spreadsheet created: %s',
      spreadsheet.getUrl());
}

/**
 * Converts a Date object into a YYYY-MM-DD string.
 * @param {Date} date The date to convert to a string.
 * @return {string} The formatted date.
 */
function formatDateString(date) {
  return Utilities.formatDate(date, Session.getScriptTimeZone(), 'yyyy-MM-dd');
}

/**
 * Formats a column name into a more human-friendly name.
 * @param {string} columnName The unprocessed name of the column.
 * @return {string} The formatted column name.
 * @example "averageViewPercentage" becomes "Average View Percentage".
 */
function formatColumnName(columnName) {
  let name = columnName.replace(/([a-z])([A-Z])/g, '$1 $2');
  name = name.slice(0, 1).toUpperCase() + name.slice(1);
  return name;
}