Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How Pick a Random YouTube Comment https://youtu.be/_dvQpqoJkc4
A recursive async function for picking a random YouTube comment https://youtu.be/_dvQpqoJkc4
Run it by adding your GCP project API key and video ID, then open the HTML page in a browser.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.0/lodash.min.js"></script>
<style>
body {
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
hr {
width: 100%;
border: 1px solid gainsboro;
}
</style>
</head>
<body>
<img width="50px">
<h1></h1>
<p></p>
<hr>
<em></em>
<hr>
<button onclick="pickWinner()">Request Winner</button>
<script src="pick-winner.js"></script>
</body>
</html>
const getComments = async(pageToken = '') => {
const key = 'API_KEY'
const videoId = 'VIDEO_ID'
const params = new URLSearchParams({
key,
videoId,
part: 'snippet',
pageToken
});
const api = 'https://www.googleapis.com/youtube/v3'
const url = new URL(`${api}/commentThreads?${params.toString()}`)
const res = await fetch(url);
const { items, nextPageToken } = await res.json();
const snippets = items.map(v => v.snippet.topLevelComment.snippet);
comments = [...snippets, ...comments]
if (nextPageToken) {
await getComments(nextPageToken)
}
}
let comments = [];
getComments();
const pickWinner = () => {
const main = document.querySelector('h1');
const info = document.querySelector('p');
main.innerHTML = '🙏 Awaiting the Swag Gods Decision 🙏';
// Add a timeout just to add to the suspense
setTimeout(() => {
// Using Lodash here to keep it simple
const uniq = _.uniqBy(comments, obj => obj.authorChannelId.value)
console.log(uniq)
const choice = Math.floor(Math.random() * (uniq.length - 1))
const winner = uniq[choice];
main.innerHTML = `🎉 ${winner.authorDisplayName} 🎉`;
info.innerHTML = `You are the chosen one. Index ${choice} of ${uniq.length} souls. May this shirt bring you many years of warmth, fashion, and comfort.`
console.log(choice)
document.querySelector('img').src = winner.authorProfileImageUrl
document.querySelector('em').innerHTML = winner.textDisplay
}, 5000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment