Last active
November 6, 2022 11:52
-
-
Save cliffordp/c953c2e4020935727948afe29bd0f192 to your computer and use it in GitHub Desktop.
Google Sheets Custom Functions: Get YouTube Channel ID or Channel Title from a YT Video ID
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
// This code: https://gist.github.com/cliffordp/c953c2e4020935727948afe29bd0f192 | |
// Could use YouTube Service instead: https://developers.google.com/apps-script/advanced/youtube | |
// https://developers.google.com/youtube/v3/docs | |
const YouTubeApiKey = '...'; | |
// `=getChannelIdFromVideoId( A1 )` | |
// Could link if you wish: `="https://www.youtube.com/channel/"&B1` | |
function getChannelIdFromVideoId( videoId ) { | |
const data = getDataFromVideoId( videoId ); | |
if( isString( data ) ) { | |
return data; | |
} | |
return data.items[0].snippet.channelId; | |
} | |
// `=getChannelTitleFromVideoId( A1 )` | |
function getChannelTitleFromVideoId( videoId ) { | |
const data = getDataFromVideoId( videoId ); | |
if( isString( data ) ) { | |
return data; | |
} | |
return data.items[0].snippet?.channelTitle; | |
} | |
// https://developers.google.com/apps-script/guides/services/external | |
function getDataFromVideoId( videoId ) { | |
const apiUrl = getApiCallUrl( videoId ); | |
// https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app | |
const response = UrlFetchApp.fetch( apiUrl, { 'muteHttpExceptions': true } ); | |
const json = response.getContentText(); | |
const data = JSON.parse(json); | |
const apiErrorMessage = getApiErrorMessage( data ); | |
if( apiErrorMessage !== '' ) { | |
return 'ERROR: ' + apiErrorMessage; | |
} | |
if( data.items.length === 0 ) { | |
console.log( 'Video not found.' ); | |
return ''; | |
} | |
return data; | |
} | |
function getApiCallUrl( videoId ) { | |
return 'https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=' + videoId + '&key=' + YouTubeApiKey; | |
} | |
// https://developers.google.com/youtube/v3/getting-started#quota | |
function getApiErrorMessage( data ) { | |
console.log( data); | |
if( data.error?.errors.length > 0 ) { | |
return data.error.errors[0].reason; // e.g. "quotaExceeded" | |
} | |
return ''; | |
} | |
function isString(s) { | |
return typeof(s) === 'string' || s instanceof String; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment