Last active
March 11, 2023 22:32
-
-
Save ShreyanJain9/c1a2d53179cb8c399e97ec1347344013 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
#!/bin/ruby | |
#This program calls the Bing API and returns some search json_results. | |
require "net/https" #These are just some dependencies | |
require "uri" | |
require "cgi" | |
require "json" | |
#API Info | |
def search(term, safesearch, where) | |
accessKey = ENV["BING_API_KEY"] | |
uri = "https://api.bing.microsoft.com" | |
path = "/v7.0/search" | |
#term = "MineCraft" | |
# options.push("SafeSearch=" + (form.safe.checked ? "strict" : "moderate")) | |
option = "&SafeSearch=" | |
if (safesearch.to_i >= 1) | |
option = option + "strict" | |
else | |
option = option + "moderate" | |
end | |
market = "&mkt=" + where | |
count = "&count=10" | |
offset = "&offset=0" | |
uri = URI(uri + path + "?q=" + CGI.escape(term) + option + market + count + offset) | |
puts "Searching the Web for: " + term | |
puts uri | |
request = Net::HTTP::Get.new(uri) | |
request["Ocp-Apim-Subscription-Key"] = accessKey | |
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == "https") do |http| | |
http.request(request) | |
end | |
#puts "\nRelevant Headers:\n\n" | |
# response.each_header do |key, value| | |
# if key.start_with?("bingapis-") or key.start_with?("x-msedge-") then | |
# puts key + ": " + value | |
# end | |
# end | |
#puts "\nJSON Response:\n\n" | |
#puts JSON::pretty_generate(JSON(response.body)) | |
#STEP 3 detect failure or success. | |
#if failure: | |
#alert and exit | |
# elsif success: | |
results = [] | |
json_results = JSON.parse(response.body) | |
if json_results && json_results["webPages"] && json_results["webPages"]["value"] | |
data = json_results["webPages"]["value"] | |
puts "number of results" + data.length.to_s | |
i = 1 | |
# results = [] | |
count = 1000 | |
if (data.length < 1000) | |
count = data.length | |
end | |
while (i < count) | |
# for i in 1..10 | |
new_result = Result.new | |
new_result.title = data[i - 1]["name"] | |
new_result.snippet = data[i - 1]["snippet"] | |
new_result.date = Time.now | |
new_result.url = data[i - 1]["url"] | |
new_result.engine = "bing" | |
results.push new_result | |
# i = i + 1 | |
# @json_results.push new_result | |
# end | |
# puts i.to_s + "\. " + data[i - 1]["name"] | |
# puts | |
# puts data[i - 1]["url"] | |
# puts | |
# puts data[i - 1]["snippet"] | |
# puts | |
i = i + 1 | |
end | |
end | |
return results | |
end | |
# parse(json_results) | |
# show(json_results) to(user) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment