MCPcopy Index your code
hub / github.com/analyticswithadam/App_Script / getYouTubeComments

Function getYouTubeComments

YouTube_Comments.js:3–44  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

1//"oauthScopes": ["https://www.googleapis.com/auth/spreadsheets.currentonly", "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/documents"]
2
3function getYouTubeComments() {
4 const apiKey = 'ENTER YOUTUBE API KEY'; // Replace with your API key
5 const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
6
7 // Read and trim the video ID from cell B3
8 let videoId = sheet.getRange('B3').getValue().trim(); // Remove any whitespace and ensure no extra characters
9
10 // Ensure videoId does not contain any extra characters like backticks or quotes
11 videoId = videoId.replace(/[`'"]/g, ""); // Removes any backticks, single or double quotes if present
12
13 const maxResults = 100; // Number of comments to fetch in one API call (max 100)
14 let nextPageToken = ''; // Used for pagination
15 let comments = [];
16
17 // Clear content from row 5 downwards
18 sheet.getRange('4:5000').clearContent(); // Adjust the range as needed
19
20 do {
21 // Construct the API URL
22 let url = `https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId=${videoId}&maxResults=${maxResults}&key=${apiKey}&pageToken=${nextPageToken}`;
23
24 // Fetch the data from YouTube API
25 let response = UrlFetchApp.fetch(url);
26 let result = JSON.parse(response.getContentText());
27
28 // Extract comments and push to the array
29 result.items.forEach(item => {
30 let comment = item.snippet.topLevelComment.snippet.textDisplay;
31 let author = item.snippet.topLevelComment.snippet.authorDisplayName;
32 let publishedAt = item.snippet.topLevelComment.snippet.publishedAt;
33 comments.push([author, comment, publishedAt]);
34 });
35
36 // Set nextPageToken for pagination
37 nextPageToken = result.nextPageToken;
38
39 } while (nextPageToken);
40
41 // Log the comments or insert into Google Sheets
42 Logger.log(comments);
43 insertCommentsToSheet(comments);
44}
45
46// Helper function to insert comments into Google Sheets
47function insertCommentsToSheet(comments) {

Callers

nothing calls this directly

Calls 1

insertCommentsToSheetFunction · 0.70

Tested by

no test coverage detected