Advertisement
agunq

Youtube api

Mar 12th, 2017 (edited)
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.87 KB | None | 0 0
  1. require 'json'
  2. require 'uri'
  3. require 'net/http'
  4.  
  5. class Youtube
  6.    
  7.     def initialize
  8.         @authkey = "YOUR API KEY"
  9.     end
  10.    
  11.     def search(query)
  12.         search = query.split(" ")
  13.         uri = URI('https://www.googleapis.com/youtube/v3/search')
  14.         params = {
  15.             "q" => search.join("+"),
  16.             "part" => "snippet",
  17.             "key" => @authkey
  18.         }
  19.         uri.query = URI.encode_www_form(params)
  20.         response = Net::HTTP.get_response(uri).body
  21.         data = JSON.parse(response)
  22.         for d in data["items"]
  23.             if d["id"].key?("videoId")
  24.                 duration, views, like = details d["id"]["videoId"]
  25.                 title = d["snippet"]["title"]
  26.                 link = "http://www.youtube.com/watch?v=" + d["id"]["videoId"]
  27.                 uploader = d["snippet"]["channelTitle"]
  28.                 return "#{title} Uploaded by #{uploader} [#{duration}, #{like}♥, #{views}👁]. #{link}"
  29.             end
  30.         end
  31.     end
  32.    
  33.     def details(videoid)
  34.         uri = URI('https://www.googleapis.com/youtube/v3/videos')
  35.         params = {
  36.             "id" => videoid,
  37.             "part" => "contentDetails,statistics",
  38.             "key" => @authkey
  39.         }
  40.         uri.query = URI.encode_www_form(params)
  41.         response = Net::HTTP.get_response(uri).body
  42.         data = JSON.parse(response)
  43.         for d in data["items"]
  44.             duration = d["contentDetails"]["duration"].gsub(/[^0-9]/, ":").split(":").reject { |c| c.empty? }.join(":")
  45.             views = d["statistics"]["viewCount"]
  46.             like = d["statistics"]["likeCount"]
  47.             dislike = d["statistics"]["dislikeCount"]
  48.             favorite = d["statistics"]["favoriteCount"]
  49.             comment = d["statistics"]["commentCount"]
  50.             return duration, views, like
  51.         end
  52.     end
  53. end
  54.  
  55. #puts Youtube.new.search("naruto")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement