module BingImageSearch

Public Class Methods

imageurl(key="abc",term = "Bing",page = 0) click to toggle source
# File lib/bingImageSearch.rb, line 4
def self.imageurl (key="abc",term = "Bing",page = 0)

      uri  = "https://api.cognitive.microsoft.com"
      path = "/bing/v7.0/images/search"

      if key.length != 32 then
       puts "Invalid Bing Search API subscription key!"
   return "error: wrong accessKey"
      end
      if term == "Bing"
              return "error: provide search term"
      end
      page = Random.rand(3)
      off = page * 10

      uri = URI(uri + path + "?q=" + URI.escape(term)+"&count="+URI.escape("10")+"&offset="+URI.escape(off.to_s))
      
      

      request = Net::HTTP::Get.new(uri)
      request['Ocp-Apim-Subscription-Key'] = key

      response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
      http.request(request)
      end
      search = JSON.parse(JSON::pretty_generate(JSON(response.body)))
      
      if search["statusCode"] == 401
             return("false api key")
       end
      
      i = Random.rand(9)
      results = (search["value"][i]["contentUrl"])
      
      
      return(results)
      
end