-
-
Save warrienelly/bdf5a7a436db464f67e5cdb80195a216 to your computer and use it in GitHub Desktop.
Full code snippet Pullling Youtube Channel Data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const default_part = 'snippet,contentDetails,Statistics' // default part name for query | |
// get channelID(s) from google sheet | |
function getChannelIDs() | |
{ | |
var activeSheet = SpreadsheetApp.getActiveSheet(); | |
const startRow = 2; | |
const startCol =2; | |
var numRow= activeSheet.getLastRow() -1; //row_number with last non_empty value. | |
const numCol= 1 | |
var col_channel_ids = activeSheet.getSheetValues( startRow,startCol, numRow ,numCol); | |
return col_channel_ids; | |
} | |
//get data from channelID using the youtube API | |
function getDataFromChannelID(part, channel_id) | |
{ | |
/* | |
Get the the following details: | |
title, | |
PublishedDate, | |
Number of Subscribers, | |
Number of Views, | |
Number of video, | |
and Upload PlaylistID | |
from the youtube api using the channelID. | |
*/ | |
params = {'id': channel_id}; //specify query parameter based on url_type | |
response = YouTube.Channels.list(part,params); | |
channelDetails = response['items'][0]; // pull out details from the response by indexing 0 | |
result = [ | |
channelDetails['snippet']['title'], | |
channelDetails['snippet']['publishedAt'], | |
channelDetails['statistics']['subscriberCount'], | |
channelDetails['statistics']['viewCount'], | |
channelDetails['statistics']['videoCount'], | |
channelDetails['contentDetails']['relatedPlaylists']['uploads'] | |
] | |
return result; | |
} | |
function getUploadedVideoIDs(uploadsPlaylistID){ | |
/* | |
Using uploadsPlaylistID to retrieve | |
- all videoIds of uploads | |
- last uploaded date | |
*/ | |
var nextPageToken = ''; // retrieve the lastuploaded date from the first page where nextPageToken='' as defined in the intial value | |
var part = 'snippet,contentDetails' | |
var array_uploaded_videoIds = []; // empty array to store all video Id | |
// Loop through the videos in the Channel to get the Video IDs | |
while (nextPageToken !== undefined) | |
{ | |
var params = | |
{ | |
'playlistId':uploadsPlaylistID, | |
'pageToken': nextPageToken, | |
'maxResults': 50 // maximum result(videoid) for each page is 50 | |
} | |
response = YouTube.PlaylistItems.list(part,params) // query api for uploaded videos | |
videoList = response['items'] | |
if (nextPageToken === ''){ | |
var last_uploaded_date = videoList[0]['contentDetails']['videoPublishedAt'] // retrieve the lastuploaded date from the first page where nextPageToken='' as defined line 8 | |
} | |
nextPageToken = response['nextPageToken'] | |
videoIds_per_page = videoList.map(function(videoDetail){ // loop through videolist to get each video in the page | |
result = videoDetail['contentDetails']['videoId']; | |
return result; | |
}) | |
array_uploaded_videoIds = array_uploaded_videoIds.concat(videoIds_per_page) // append the videoIds to a single array. | |
} | |
return [array_uploaded_videoIds, last_uploaded_date] // return the list of video ids and the last uploaded date. | |
} | |
function getHighestViewedFromID(videoIds){ | |
/* | |
Using videoIds to retrieve | |
- Title of video with highest view. | |
- View count of highest-viewed video. | |
*/ | |
var part = 'snippet,statistics'; | |
var batchedVideoIds; | |
var params = | |
{ | |
'id':batchedVideoIds, | |
'maxResults': 50 // specify the number of batch for video Id | |
} | |
arrray_videos_count_title = []; | |
// loop through the list of ID in a batch of 50 to get the details of video | |
for (let i = 0; i < videoIds.length; i = i+params['maxResults']){ | |
batchedVideoIds = videoIds.slice(i,params['maxResults']+i); //retreive 50 unique videoIds from the videoids list | |
params['id']= batchedVideoIds; | |
response = YouTube.Videos.list(part,params); // query api for video detail | |
video_count_title = response['items'].map(function(item){ // loop through response item(list of videos) and extract the video title and view count. | |
video_detail = [item['snippet']['title'],parseInt(item['statistics']['viewCount'])]; | |
return video_detail | |
}) | |
arrray_videos_count_title = arrray_videos_count_title.concat(video_count_title) | |
} | |
arrray_videos_count_title.sort(function(a,b){ // sort array by viewcount | |
return a[1] - b[1]; | |
}); | |
return (arrray_videos_count_title.pop()) // return the highest-viewed video detail | |
} | |
function writeDataToApi(result){ | |
/* | |
Pass in a 2-D array as input | |
and write the data into the worksheet | |
*/ | |
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); | |
ss.getRange(2,3,result.length,result[0].length).setValues(result) | |
// .setValues(result) | |
console.log(result) | |
} | |
function executeAll(){ | |
// loop through channelId's in the list of channelIDS from the sheet and get the details of each channel | |
channelIDs = getChannelIDs() // get channelIDs from sheet | |
channel_details = channelIDs.map(function(c_id){ // Loop through each channel | |
data_from_channel_id = getDataFromChannelID(default_part,c_id); // Get preliminary data from channel ID | |
uploaded_playlist_id = data_from_channel_id[5] // extract uploaded Playlist Id | |
video_ids_latest_dt = getUploadedVideoIDs(uploaded_playlist_id); // get uploaded video id and last uploaded date | |
// pull out the video ids and the latest_upload_date as a seperate variable | |
video_ids_array = video_ids_latest_dt[0]; | |
lastest_upload_date = video_ids_latest_dt[1]; | |
highest_viewed_detail = getHighestViewedFromID(video_ids_array) // get video with the highest view | |
// combine and return all information together in an array containing | |
// [title, Published_date, number_of_subscribers, views_count, | |
// video_count, uploaded_playlist_id,lastest_upload_date, | |
// highest_viewed_video_title, highest_viewed_video_count ] | |
return(data_from_channel_id.concat(lastest_upload_date,highest_viewed_detail)) | |
console.log(all_details); | |
}) | |
writeDataToApi(channel_details); // write the data to the sheet | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment