I believe your goal as follows.
- You want to add the video IDs by checking the playlist.
- You want to retrieve the additional video IDs from the column "A" of the active sheet on Google Spreadsheet.
- When the video IDs are existing in the playlist, you don't want to add them.
- When the video IDs are not existing in the playlist, you want to add them.
Modification points:
- In this case, I think that at first, it is required to retrieve the list from the playlist. And then, when the additional video ID is not existing in the playlist, the video ID is added.
When above points are reflected to your script, it becomes as follows.
Modified script:
function addVideoToYouTubePlaylist() {
// 1. Retrieve list from the playlist.
var playlistId = "PL6bCFcS8yqQxSPjwZ9IXFMfVm6kaNGLfi";
var list = [];
var pageToken = "";
do {
var res = YouTube.PlaylistItems.list(["snippet"], {playlistId: playlistId, maxResults: 50, pageToken: pageToken});
if (res.items.length > 0) list = list.concat(res.items);
pageToken = res.nextPageToken || "";
} while (pageToken);
var obj = list.reduce((o, e) => Object.assign(o, {[e.snippet.resourceId.videoId]: e.snippet.resourceId.videoId}), {});
// 2. Retrieve URLs like `https://www.youtube.com/watch?v=###` from the column "A" of the active sheet.
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
// 3. Check whether the additional video ID is existing in the playlist and add it.
data.forEach(([a]) => {
var videoId = extractVideoID(a);
if (videoId && !obj[videoId]) { // <--- Modified
YouTube.PlaylistItems.insert({
snippet: {
playlistId: playlistId,
resourceId: {
kind: "youtube#video",
videoId: videoId
}
}
}, "snippet");
}
});
}
function extractVideoID(url){
var regExp = /^.*((youtu.be/)|(v/)|(/u/w/)|(embed/)|(watch?))??v?=?([^#&?]*).*/;
var match = url.match(regExp);
if (!match) return; // <--- Added
if ( match && match[7].length == 11 ){
return match[7];
} else {
console.log("Could not extract video ID.");
var trimmedVideoID = url.replace("https://youtu.be/", "");
trimmedVideoID = trimmedVideoID.replace('https://www.youtube.com/watch?v=', "");
trimmedVideoID = trimmedVideoID.replace('https://youtube.com/watch?v=', "");
trimmedVideoID = trimmedVideoID.replace("&feature=youtu.be", "");
trimmedVideoID = trimmedVideoID.replace("&feature=share", "");
console.log(trimmedVideoID);
return trimmedVideoID;
}
}
Note:
- If you have a lot of additional video IDs, to use the batch request might be useful. Ref
References:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…