Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'json'
- require 'uri'
- require 'net/http'
- class Youtube
- def initialize
- @authkey = "YOUR API KEY"
- end
- def search(query)
- search = query.split(" ")
- uri = URI('https://www.googleapis.com/youtube/v3/search')
- params = {
- "q" => search.join("+"),
- "part" => "snippet",
- "key" => @authkey
- }
- uri.query = URI.encode_www_form(params)
- response = Net::HTTP.get_response(uri).body
- data = JSON.parse(response)
- for d in data["items"]
- if d["id"].key?("videoId")
- duration, views, like = details d["id"]["videoId"]
- title = d["snippet"]["title"]
- link = "http://www.youtube.com/watch?v=" + d["id"]["videoId"]
- uploader = d["snippet"]["channelTitle"]
- return "#{title} Uploaded by #{uploader} [#{duration}, #{like}♥, #{views}👁]. #{link}"
- end
- end
- end
- def details(videoid)
- uri = URI('https://www.googleapis.com/youtube/v3/videos')
- params = {
- "id" => videoid,
- "part" => "contentDetails,statistics",
- "key" => @authkey
- }
- uri.query = URI.encode_www_form(params)
- response = Net::HTTP.get_response(uri).body
- data = JSON.parse(response)
- for d in data["items"]
- duration = d["contentDetails"]["duration"].gsub(/[^0-9]/, ":").split(":").reject { |c| c.empty? }.join(":")
- views = d["statistics"]["viewCount"]
- like = d["statistics"]["likeCount"]
- dislike = d["statistics"]["dislikeCount"]
- favorite = d["statistics"]["favoriteCount"]
- comment = d["statistics"]["commentCount"]
- return duration, views, like
- end
- end
- end
- #puts Youtube.new.search("naruto")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement