Using Python and YouTube's API to Get Random Comments from a Video
We'll go over the code powering a CLI tool using only the Python 3 standard library and cover a few programming patterns along the way.
Not too long ago I ran a 10,000 subscribers giveaway contest on my YouTube channel. This resulted in folks commenting on the video and I picked a bunch of random winners based on who commented.
This script is what I ended up developing to automate the process. It’s available on GitHub. This video goes over both using the script and going over all of the code to make it work.
We’ll cover a bunch of general Python programming concepts like using argparse,
CLI argument validation, using map()
, making GET requests, environment
variables, loading JSON, picking random items from a list, de-duping a list and
more.
All of the above is done using Python’s standard library. There’s no 3rd party dependencies.
# Demo Video and Going Over the Python Code
Timestamps
- 0:28 – Why did I even develop this script?
- 1:23 – How the script works at a high level
- 2:16 – Installing the script
- 3:15 – Creating a YouTube API key
- 5:44 – Getting your public IP address with
curl ifconfig.me
- 6:33 – Exporting our YOUTUBE_API_KEY so the script can use it
- 7:35 – Running the script with a few different arguments
- 9:56 – Finding the entry point of the script and seeing how it all fits together
- 12:01 – Parsing arguments in Python with argparse
- 14:54 – Writing custom type validations for argparse
- 18:47 – Using Python’s map function to modify every item in a list
- 22:03 – Outputting the results with a multi-line f string
- 23:24 – Formatting the output so other programs can easily parse it
- 24:46 – Abstracting behavior into functions helps readability
- 25:34 – Handling the YOUTUBE_API_KEY ENV variable and argparse input
- 27:22 – Using YouTube’s API to get a list of top level comments
- 30:40 – Converting a dictionary of args into a URL encoded query string
- 31:24 – Making GET requests with urllib and Python’s standard library
- 33:04 – Getting the top level comments, specifically the display names
- 37:07 – Dealing with paginating over multiple pages of comments
- 39:48 – Flattening a list in Python using the chain module
- 42:04 – Creating a unique and sorted list
- 42:53 – Removing items from a list that exist in another list
- 45:09 – Tracking the count of comment authors who were omit / removed
- 45:35 – Picking the winners by randomly selecting items from a list
- 48:53 – Recap and commenting below to ask questions about the code
Reference Links
- https://github.com/nickjj/pick-random-youtube-comments
- Related video going into more details about argparse and building Python CLIs
Did you takeaway anything from this video? Let me know below.