如何使用 Google Apps 脚本将视频上传到 YouTube?

How to upload a video to YouTube using Google Apps Script?

我想使用 Google Apps 脚本将视频上传到 YouTube。这是我的代码,包括我尝试过的以及错误是什么。

Code.gs
/**
 * @see https://developers.google.com/youtube/v3/docs/videos/insert
 * @param { String } sourceUrl url location of the source video file in google drive
 * @returns { Video }
 */
const uploadVideo2youtube = sourceId => {
  const sourceFile = DriveApp.getFileById( sourceId, ).getBlob();
  const videoResource = {
    snippet: {
      title: 'Summer vacation in California',
      description: 'Had a great time surfing in Santa Cruz',
      tags: [ 'surfing', 'Santa Cruz', ],
      categoryId: '22',
    },
  };
  // const status = { privacyStatus: 'Private', };
  const status = { privacyStatus: 'private', };

  // here are all my attempts and the errors with each one...
  // const newVideo = YouTube.Videos.insert( videoResource, status, sourceFile, ); // GoogleJsonResponseException: API call to youtube.videos.insert failed with error: '{privacyStatus=private}' (line 229, file "Code")
  // const newVideo = YouTube.Videos.insert( videoResource, sourceFile, ); // GoogleJsonResponseException: API call to youtube.videos.insert failed with error: Blob (line 230, file "Code")
  const newVideo = YouTube.Videos.insert( videoResource, [ status ], sourceFile, ); // GoogleJsonResponseException: API call to youtube.videos.insert failed with error: '{privacyStatus=private}' (line 231, file "Code")

  Logger.log('(line 213) newVideo:\n%s', JSON.stringify( newVideo ),);
}
const upload2youtube_test = () => upload2youtube( <fileId>, )

从代码中可以看出,YouTube.Videos.insert()方法我已经进行了多次尝试。但是每次尝试都会引发错误。是的,我在我的资源选项卡下启用了 YouTube 数据 API v3 资源并将脚本授权给 运行.

我做错了什么?

这个修改怎么样?

修改点:

  • 请在videoResource中包含status
  • YouTube.Videos.insert(resource, part, mediaData) 的第二个参数是 part。在这种情况下,它是 "snippet,status".

修改后的脚本:

const sourceFile = DriveApp.getFileById(sourceId).getBlob();
const videoResource = {
  snippet: {
    title: 'Summer vacation in California',
    description: 'Had a great time surfing in Santa Cruz',
    tags: [ 'surfing', 'Santa Cruz', ],
    categoryId: '22',
  },
  status: {privacyStatus: 'private'}  // Added
};
const newVideo = YouTube.Videos.insert( videoResource, "snippet,status", sourceFile);  // Modified

注:

  • 在这种情况下,需要在高级 Google 服务中启用 YouTube 数据 API v3。请注意这一点。 Ref

参考文献: