Home > database >  Google Apps Script: Retrieve most recent video ids from Youtube API v3 as array
Google Apps Script: Retrieve most recent video ids from Youtube API v3 as array

Time:01-25

I am working on a project where I have an external application call a Google Apps Script Function whose purpose is to retrieve the id's of the most recent uploads on a youtube channel. The script provided by google works very well at getting the video id's:

/**
 * This function retrieves the user's uploaded videos by:
 * 1. Fetching the user's channel's.
 * 2. Fetching the user's "uploads" playlist.
 * 3. Iterating through this playlist and logs the video IDs and titles.
 * 4. If there is a next page of resuts, fetching it and returns to step 3.
 */
function retrieveMyUploads() {
  try {
    // @see https://developers.google.com/youtube/v3/docs/channels/list
    const results = YouTube.Channels.list('contentDetails', {
      mine: true
    });
    if (!results || results.items.length === 0) {
      console.log('No Channels found.');
      return;
    }
    for (let i = 0; i < results.items.length; i  ) {
      const item = results.items[i];
      /** Get the channel ID - it's nested in contentDetails, as described in the
       * Channel resource: https://developers.google.com/youtube/v3/docs/channels.
       */
      const playlistId = item.contentDetails.relatedPlaylists.uploads;
      let nextPageToken = null;
      do {
        // @see: https://developers.google.com/youtube/v3/docs/playlistItems/list
        const playlistResponse = YouTube.PlaylistItems.list('snippet', {
          playlistId: playlistId,
          maxResults: 25,
          pageToken: nextPageToken
        });
        if (!playlistResponse || playlistResponse.items.length === 0) {
          console.log('No Playlist found.');
          break;
        }
        for (let j = 0; j < playlistResponse.items.length; j  ) {
          const playlistItem = playlistResponse.items[j];
          console.log('[%s] Title: %s',
              playlistItem.snippet.resourceId.videoId,
              playlistItem.snippet.title);
        }
        nextPageToken = playlistResponse.nextPageToken;
      } while (nextPageToken);
    }
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed with err %s', err.message);
  }
}

Unfortunately, I cannot figure out how to actually use the output of this function for my application. From what I can see, the function simply prints the id's to the execution log, but I am wondering if there is a way to put the output into an array? I have seen this SO post that accomplishing the same task. However, I am wondering if it can be done using the script that google provides in their documentation.

CodePudding user response:

If I understand your question...you want an array of uploaded videos from a given channel. If so, you need to create an array where to store the results.

Here is a tested fucntion that gets the uploaded videos from a given channel:

function getUploadedVideos() {
  try {
    // Call uploaded videos from channel "Listen To This": 

    /** Array with the data. */
    var array_videos = [];

    /** Token pagination. */
    var nextPageToken = "";

    /** Channel "Listen To This". */
    var channel_id = "UC6ZVjGqRf7elKAcYTXCaIsw";

    /** "upload" playlist = it's the channel_id, but change the first letters "UC" to "UU" */
    var uploads_playlist_id = ("UU"   channel_id.substr(2, channel_id.length));

    /**
     * Get all uploaded videos by the channel.
     */
    do {
      const playlistResponse = YouTube.PlaylistItems.list('snippet', {
        playlistId: uploads_playlist_id, // also works with "mine: true" for get YOUR uploaded videos.
        maxResults: 50,
        // Here, the first time the call is made, the "nextPageToken" value 
        // is empty. In every iteration (if "nextPageToken" is retrieved), 
        // the "nextPageToken" is used - in order to get the next page.
        pageToken: nextPageToken
      });
      if (!playlistResponse || playlistResponse == undefined) {
        Logger.log('No playlist found.');
        SpreadsheetApp.getUi().alert("No playlist found.");
        break;
      }

      // Write the videos returned in the response: 
      for (let j = 0; j < playlistResponse.items.length; j  ) {
        const mySubItem = playlistResponse.items[j];
        array_videos.push(mySubItem.snippet.resourceId.videoId);
      }

      // Check the token: 
      try {
        if (playlistResponse.nextPageToken != null || playlistResponse.nextPageToken != undefined) {
          nextPageToken = playlistResponse.nextPageToken;
        } else {
          nextPageToken = undefined;
          break;
        }
      } catch (ex_page) {
        // An error occurred. Check closely the code.
        Logger.log("An error occurred. Check closely the code.");
      }
    } while (nextPageToken != undefined);

    // Print the results: 
    Logger.log(array_videos);
  } catch (ex) {
    Logger.log("Error at getting Marvel videos: %"   ex);
  }
}

Result:

[lkD6zqBd15k, SalMSotJojg, 6rzKW6v_K9Q, goWF8wbNWcs, q0ElGPy6l9I, xPLOnypPgOI, rJHdvyntjZk, LzuA87yMHM8, bdgJAPXySVg, CMJbgwqmmAA, qmM_nsHTdGg, NZg5M0Vek6k, LHkZKohT5Mg, W7Oxs1O58po, lz-Q7zOE1TE, o5uZL3yUnQ8, VwMQC9Ki6-A, KfKujQcSr6I, IkPb88qUgk0, cilE6-mDiZc, sWKXnoTbgEc, MMN4HbX_UdA, EZG0nbXgJyQ, 9dCCrM8Amdo, FZquT-IN1BI, nq0F3mS4wxw, Mb70SJgZVlM, hkEV1obRwXw, ewNlaQQ4zik, ptaNPp6waws, DsGV5FnH4to, DfQWxfNUT3k, a7_O0LqeACI, Z--uRxZAMs8, PkD3a0FPEGI, MzGKo5tF_Y0, vd2fsou_Phg, HFtL2FxOk4I, q5Hy7nZmqu8, 4dKss-2FFEA, pj-4olXN0Eg, i0dYCCAuRbE, inyuMUxXiCs, LHnUZGQ4Q1g, llMrn70YKKI, -IaCwFk8ahI, DvoV4PuoJ5I, SUKmRCFx0DQ, nVbgXA_vdzo, xjTMp7YL0tc, ePIoXemhFcM, twKr8t_d_Wo, 69YMCEE7lJs, Ie61ZeWMNig, UrT7URgGr2Y, I3TdwIRHGs8, 407nKV2wXVk, RVQgmjFyxNc, H5lmadddLuE, rqCNRuO-b2g, P5LFeAUbuQQ, H3pIHb99Pwg, aixhKlvboao, WllI0h4np2s, lM6jSit1HOc, XzdmhbZPtoI, a2ky2jqPKik, WoO694aGQS0, QvNgRVDrwKk, TgndfBuHv80, a07dwCbInqw, BJijluHVN0o, peMxsRTMdAU, i4pTDiVglyQ, zCFbq7xq7WM, e2njchHP_IE, lTvvUgIt4CM, bJQG7_oydKQ, xHJHYFPn-3I, vXAPxN-b6rI, DmVPJztgqpM, BbxnEkavYcc, ZKJb3RBR5-g, traXftfW8n4, HC0-_v7oql4, ywBipoo7zKU, 0j1To_VTc2U, osmrXqRuwJA, p65aE3XWSp8, rrrtmhAtxVw, 9L13dJ2GY8Y, VCgKCtwEWZQ, 8EJJH6qrsA8, QoOOsIJbXKQ, MngpR1BS--Y, iAFIkRchafs, AtOJZDDSrsQ, h0qms723EQw, Kcqqk7FVPmA, E3K4RwL7SY4, nQAENgf-qhk, HqVr0Yrozrs, tmQqUh0xark, deBhz0mADOw, 29ntukJ8C9Q, Jj_3x8fnU0M, Q90061dShXU, ed1oIgcjlNc, WPzCfboz7BA, j9FNonwudEk, p5FTI8q4bBg, 5Mk5EMiCy3k, rD0UamFoq7M, 47EP94Kz-yw, XyitdaXLzDk, y-Faj25nOhM, SZ1jUnfybuQ, EALd5UOXEVc, Tzc1SMxCtos, bHf5mJ86fwA, 25lGn8XVWj4, lCZc9y9KpY4, HCP3NOKrdOc, N12WWl_f3QM, 1a5fIFoCyl0, AA3WjWD_hyM, JE1DystO6DA, oaNdiTLKlMA, dQsWBeMuOeU, q1egg1mlxvM, 8xzUYxx541E, UJg99jDuU7c, TaUOspOh5pU, 0EtJgT9bS3o, MzbYsoR9dPM, 9sE138cu_LU, Ej1nxBxFSKc]

CodePudding user response:

This was able to grab the id of the most recent video uploaded on a channel and is a cleaned up version of above grabbed from here:

function retrieveMyUploads3() {
  var results = YouTube.Channels.list('contentDetails', {mine: true});

  for(var i in results.items) {
    var item = results.items[i];
    // Get the playlist ID, which is nested in contentDetails, as described in the
    // Channel resource: https://developers.google.com/youtube/v3/docs/channels
    var playlistId = item.contentDetails.relatedPlaylists.uploads;
    var playlistResponse = YouTube.PlaylistItems.list(`snippet`, {
        playlistId: playlistId,
        maxResults: 1,
      });
    var chunk = playlistResponse.items.shift()
    var theID = chunk.snippet.resourceId.videoId.toString()
    return theID


    
  }
}

Not quite an array of many different one's but I am sure it can be looped to build the array of id's and serves as a condensed way to get ahold of the video id's compared to the original google version if you don't need id's beyond the first page of results

  • Related