function findPlaylist(compare) { let pageToken; while(true) { const list = YouTube.Playlists.list(['snippet'], { "maxResults": 50, "mine": true, ...(pageToken && { pageToken }) }); const item = list.items.find((row) => compare && compare(row)); if (item) { return item; } if (!list.nextPageToken) { return null; } pageToken = list.nextPageToken; } } function addPlaylist() { const title = `wl__${(new Date().getMonth()) + 1}`; const item = findPlaylist(({ snippet }) => snippet.title === title); if (item) { return item; } return YouTube.Playlists.insert( { 'snippet': { title, }, 'status': { 'privacyStatus': 'private' } }, 'snippet,status' ); } function insertVideo(playlistId, videoId) { return YouTube.PlaylistItems.insert( { "snippet": { playlistId, "resourceId": { "kind": "youtube#video", videoId } } }, 'snippet' ); } function run() { const spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); const sheet = spreadsheet.getSheets()[0]; const lastRow = sheet.getLastRow(); console.log({ lastRow }); if (lastRow < 1) { return; } // 199 because 1 request for insterting playlist const lastIndex = lastRow > 199 ? 199 : lastRow; console.log(`get range: A1:A${lastIndex}`); spreadsheet.toast(`get range: A1:A${lastIndex}`, "fill playlist"); let range = sheet.getRange(`A1:A${lastIndex}`); const rows = range.getValues().flat().filter(Boolean); console.log({ willProcessing: rows.length }); if (rows.length) { let lastAdded = 0; let error; let lastVideo; try { const pl = addPlaylist(); rows.forEach((videoId, index, arr) => { if (!videoId) { return; } try { insertVideo(pl.id, videoId, arr.length - index); lastVideo = videoId; } catch(err) { if (!err.message.includes('Video not found')) { throw err; } console.log('video not found', videoId); lastVideo = videoId; } lastAdded = index + 1; }); } catch(err) { error = err; } console.log({ lastAdded, lastVideo }); if (lastAdded > 0) { if (!lastVideo) { lastVideo = sheet.getRange('B1:B1').getValue(); } const row = sheet.getLastRow() || 1; if (lastAdded >= row) { lastAdded = row - 1; } console.log({ row, lastAdded }); if (lastAdded > 0) { sheet.deleteRows(1, lastAdded); } else { sheet.getRange('A1:A1').setValue(''); } sheet.getRange('B1:B1').setValue(lastVideo); } if (error) { throw error; } } } function init() { const spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); spreadsheet.removeMenu('YouTube'); spreadsheet.addMenu('YouTube', [ { name: 'fill playlist', functionName: 'run', } ]); } function onOpen() { init(); }