Saturday, December 11, 2021

Automatically Changing a YouTube Video's Privacy With Google Apps Script

 Recently we had posted a video that needed to be available during a specific time. The starting availability is taken care of by setting it to premiere. However there's no option for having it unavailable at the end of the time period, so we needed to write some code for that.

Google Apps Script is a good choice for this, since it has a YouTube service that you can enable as well as triggers that can run code at a certain time.

Create a new Apps Script project and paste in the following code:

// schedule this Google Apps Script function to run at a certain time to change a YouTube video's privacy status
function updateVideoPrivacy() { // enable the YouTube Data API under "Services"
var channels = YouTube.Channels.list('contentDetails', {mine: true});
for (var i=0; i<channels.items.length; i++) {
var uploadsPlaylistId = channels.items[i].contentDetails.relatedPlaylists.uploads;
var playlistResponse = YouTube.PlaylistItems.list('snippet', {playlistId: uploadsPlaylistId, maxResults: 1}); // or more than 1 if needed
var video = playlistResponse.items[0]; // the first video in the list we retrieved
var metadata = {
status: {'privacyStatus': 'private'}, // public, unlisted, private
id: video.snippet.resourceId.videoId}; // we need to include the video ID from the playlist response
YouTube.Videos.update(metadata, 'id,status') // update the video's privacy status
}
}


Then enable the YouTube Service and create a new trigger to run the updateVideoPrivacy function at a time-driven specific date and time. The code will then set your most recently uploaded YouTube video to private at the time you specified.