Skip to content

Instantly share code, notes, and snippets.

@learncodeacademy
Created May 24, 2017 19:13
Show Gist options
  • Select an option

  • Save learncodeacademy/fdaabccee54dd3d497a7da4665ec1f98 to your computer and use it in GitHub Desktop.

Select an option

Save learncodeacademy/fdaabccee54dd3d497a7da4665ec1f98 to your computer and use it in GitHub Desktop.
YouTube Random Comment Selector
const axios = require("axios");
const key = "AIzaSyB9e-dHIvdxxrbmorjYHWipwBKq7LJBhNk"
function getComments(pageToken, allItems = {}) {
const params = {
key,
videoId: "a4haLJdDRmc",
part: "snippet",
maxResults: 100,
pageToken,
textFormat: "plainText",
};
console.log(`Fetching page: ${pageToken || "First Page"}`);
console.log(`Total Comments: ${Object.keys(allItems).length}`);
return axios.get("https://www.googleapis.com/youtube/v3/commentThreads/", {params})
.then(({ data: { nextPageToken, items } }) => {
items.forEach((item) => {
const id = item.snippet.topLevelComment.snippet.authorChannelId.value;
//store user ID by key to prevent duplicates
allItems[id] = item.snippet.topLevelComment.snippet;
});
if (nextPageToken) {
return getComments(nextPageToken, allItems)
}
return allItems;
})
.catch(({response: {data}}) => console.log(data.error))
;
}
getComments().then((allComments) => {
const totalCount = Object.keys(allComments).length;
const winner = Math.floor(Math.random() * (totalCount-1) ) + 0;
const winningId = Object.keys(allComments)[winner];
const winnerName = allComments[winningId].authorDisplayName;
const winnerText = allComments[winningId].textDisplay;
console.log(`\n\nTotal Unique Entries: ${totalCount}`);
console.log(`Winner Number: ${winner}`);
console.log(`Winning ID: ${winningId}`);
process.stdout.write("\nAnd the winner is...");
const dotsInterval = setInterval(() => { process.stdout.write(".");}, 300);
setTimeout(() => {
clearInterval(dotsInterval);
console.log(`
${winnerName}
winning comment: "${winnerText}"
`);
}, 5000)
});
@mxvsh
Copy link
Copy Markdown

mxvsh commented Feb 25, 2020

does it work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment