Class: Daneel::Scripts::ImageSearch

Inherits:
Daneel::Script show all
Defined in:
lib/daneel/scripts/image_search.rb

Instance Attribute Summary

Attributes inherited from Plugin

#robot

Instance Method Summary collapse

Methods inherited from Daneel::Script

#accepts?, files, inherited, list

Methods inherited from Plugin

#logger, requires_env

Constructor Details

#initialize(robot) ⇒ ImageSearch

Returns a new instance of ImageSearch.



12
13
14
15
16
# File 'lib/daneel/scripts/image_search.rb', line 12

def initialize(robot)
  super
  @token = ENV['AZURE_API_KEY']
  @http = Net::HTTP::Persistent.new('daneel')
end

Instance Method Details

#find_image_url_for(search) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/daneel/scripts/image_search.rb', line 30

def find_image_url_for(search)
  logger.debug "Searching for images of #{search}"
  query = CGI.escape("'#{search.gsub(/'/, "\\\\'")}'")
  uri = URI("https://api.datamarket.azure.com/Bing/Search/v1/Composite")
  uri.query = "Sources=%27image%27&Adult=%27Moderate%27&$format=JSON&Query=#{query}"
  request = Net::HTTP::Get.new(uri.request_uri)
  request.basic_auth 'x', @token
  response = @http.request uri, request
  logger.debug "GET #{uri}"
  results = JSON.parse(response.body)["d"]["results"].first["Image"]
  logger.debug "got back #{results.size} images"
  # Random image from the first 50 results
  results.sample["MediaUrl"]
rescue => e
  logger.error "#{e.class}: #{e.message}"
  room.say "Sorry, something went wrong when I looked for '#{query}'"
end

#helpObject



26
27
28
# File 'lib/daneel/scripts/image_search.rb', line 26

def help
  {"find a THING" => "scours the internets for a picture of THING to show you"}
end

#receive(room, message, user) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/daneel/scripts/image_search.rb', line 18

def receive(room, message, user)
  case message.command
  when /image me (.*?)/, /^(?:find) (?:me )?(?:a |another )?(?:picture of )?(.*)$/
    room.say find_image_url_for($1)
    message.done!
  end
end