MCPcopy Create free account
hub / github.com/analyticswithadam/App_Script / getYouTubeComments

Function getYouTubeComments

YOuTube Comment Code with Likes.js:1–43  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls 1

insertCommentsToSheetFunction · 0.70

Tested by

no test coverage detected