Class: Lita::Handlers::GoogleImages

Inherits:
Handler
  • Object
show all
Defined in:
lib/lita/handlers/google_images.rb

Constant Summary collapse

URL =
"https://ajax.googleapis.com/ajax/services/search/images"
VALID_SAFE_VALUES =
%w(active moderate off)

Instance Method Summary collapse

Instance Method Details

#fetch(response) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/lita/handlers/google_images.rb', line 21

def fetch(response)
  query = response.matches[0][0]

  http_response = http.get(
    URL,
    v: "1.0",
    q: query,
    safe: config.safe_search,
    rsz: 8
  )

  data = MultiJson.load(http_response.body)

  if data["responseStatus"] == 200
    choice = data["responseData"]["results"].sample
    if choice
      response.reply ensure_extension(choice["unescapedUrl"])
    else
      response.reply %{No images found for "#{query}".}
    end
  else
    reason = data["responseDetails"] || "unknown error"
    Lita.logger.warn(
      "Couldn't get image from Google: #{reason}"
    )
  end
end