-
-
Save ytnk531/175db38b683796c2611130c058bc19cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'faraday' | |
require 'faraday_middleware' | |
class ChannelResult | |
attr_reader :channels, :next_page_token | |
def initialize(channels, next_page_token) | |
@channels = channels | |
@next_page_token = next_page_token | |
end | |
end | |
def fetch_channels(next_page_token = nil) | |
url = "https://www.googleapis.com/youtube/v3/search?part=id&type=channel&maxResults=50®ionCode=JP&key=#{API_KEY}" | |
conn = Faraday.new(url: url) { |faraday| | |
faraday.adapter Faraday.default_adapter | |
faraday.response :json | |
} | |
response = conn.get(nil, "pageToken" => next_page_token) | |
pp response.body | |
channels = response.body["items"].map { _1["id"]["channelId"] } | |
next_page_token = response.body["nextPageToken"] | |
ChannelResult.new(channels, next_page_token) | |
end | |
def channels | |
t = nil | |
(1..6).flat_map do | |
resp = fetch_channels(t) | |
t = resp.next_page_token | |
resp | |
end | |
end | |
class ChannelDetail | |
attr_reader :id, :subscribers, :title | |
def initialize(id, subscribers, title) | |
@id = id | |
@subscribers = subscribers | |
@title = title | |
end | |
def format | |
"#{title} #{subscribers}" | |
end | |
end | |
def channel_details(list) | |
ids = list.channels.join(",") | |
url = "https://www.googleapis.com/youtube/v3/channels?part=statistics,snippet&id=#{ids}&key=#{API_KEY}" | |
conn = Faraday.new(url: url) { |faraday| | |
faraday.adapter Faraday.default_adapter | |
faraday.response :json | |
} | |
response = conn.get | |
response.body["items"].map do | |
ChannelDetail.new( | |
_1["id"], | |
_1["statistics"]["subscriberCount"], | |
_1["snippet"]["title"] | |
) | |
end | |
end | |
def ch(channel_lists) | |
channel_lists.flat_map do |list| | |
channel_details(list) | |
end | |
end | |
details = ch(channels) | |
sorted = details.sort_by do | |
_1.subscribers.to_i | |
end | |
sorted.each.with_index(1) do |c, i| | |
puts "#{i} #{c.format}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment