Skip to content

Instantly share code, notes, and snippets.

@jaynetics
Created June 27, 2023 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaynetics/6f62e7fa79646c1c8a13e34ab76ba85c to your computer and use it in GitHub Desktop.
Save jaynetics/6f62e7fa79646c1c8a13e34ab76ba85c to your computer and use it in GitHub Desktop.
download all comments of a youtube video
#!/usr/bin/env ruby
# usage: script.rb <video_id> <api_key>
require 'json'
require 'net/http'
video_id = ARGV[0].tap { |s| s&.length&.<(13) || fail('pass video id as first argument') }
key = ARGV[1].tap { |s| s&.length&.>(13) || fail('pass api key as second argument') }
url = "https://youtube.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId=#{video_id}&key=#{key}"
items = []
Net::HTTP.start(URI.parse(url).host, use_ssl: true) do |http|
loop do
puts "downloading comments page #{@next_page_token}"
response = http.get("#{url}#{@next_page_token && "&pageToken=#{@next_page_token}"}")
response.code.to_i == 200 || fail("#{response.code}: #{response.body}")
data = JSON(response.body)
items += data['items']
break if data['items'].none? || (@next_page_token = data['nextPageToken']).to_s.empty?
end
end
File.write("#{video_id}_comments.json", items.to_json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment