问题
I am learning how to use the YouTube Data API through Apps Script. I am now trying to modify the example provided here https://developers.google.com/youtube/v3/quickstart/apps-script to verify if the ID exists.
I slightly modified it to look at video IDs since that is more common.
With help by @Tanaike based on my last question, Tanaike helped me create a loop to allow the script to add IDs as comma-separated. Now I'm trying to add a validation.
function channelsListByVideoid(part,params){
var response = YouTube.Videos.list(part,params);
var video = response.items[0];
var dataRow = [video.id,video.status.uploadStatus, video.snippet.title, response.pageInfo.totalResults, video.snippet.channelId, video.snippet.channelTitle];
SpreadsheetApp.getActiveSheet();
SpreadsheetApp.getActiveSpreadsheet().getSheetByName().appendRow(dataRow);
function getvideo() {
var ui = SpreadsheetApp.getUi();
var videoId = ui.prompt("Enter the YouTube Video ID: ").getResponseText();
var values = videoId.split(",");
for (var i = 0; i < values.length; i++) {
channelsListByVideoid('snippet,status,contentDetails,statistics', {'id': values[i].trim()});
Sometimes, a video ID such as https://www.youtube.com/watch?v=--fPZOu_H8g is not available. Running that ID within the apps-script example will throw an error TypeError: Cannot read property 'id' of undefined
which will stop the script from running.
I was thinking about how to use video.list.response Property:
{
"kind": "youtube#videoListResponse",
"etag": etag,
"nextPageToken": string,
"prevPageToken": string,
"pageInfo": {
"totalResults": integer,
"resultsPerPage": integer
},
"items": [
video Resource
]
}
The totalResults and the resultsPerPage will show as 1 if the video is valid and 0 if invalid:
"pageInfo": {
"totalResults": 0,
"resultsPerPage": 0
which can be verified through the API explorer (https://developers.google.com/youtube/v3/docs/videos/list?apix_params=%7B%22part%22%3A%22snippet%2CcontentDetails%2Cstatistics%22%2C%22id%22%3A%22--fPZOu_H8g%22%7D)
I added ```` response.pageInfo.totalResults,
Logically to me, I need to add a
````var response````
to my getvideo() and add the validation check within the loop.
I'm not clear if you can write it as simply as
if response.pageinfo.totalResults = 1 then "valid" ELSE "Invalid"
and then how to allow the code to skip the error that is generated.
Thank you!
来源:https://stackoverflow.com/questions/56563450/creating-a-youtube-video-or-channel-id-validation-in-apps-script