Class: Lita::Handlers::GoogleImages

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

Constant Summary collapse

URL =
"https://www.googleapis.com/customsearch/v1"
VALID_SAFE_VALUES =
%w(high medium off)

Instance Method Summary collapse

Instance Method Details

#fetch(response, animated = false) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/lita/handlers/google_images.rb', line 32

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

  query_params = {
    v: "1.0",
    searchType: 'image',
    q: query,
    safe: config.safe_search,
    fields: 'items(link)',
    rsz: 8,
    cx: config.google_cse_id,
    key: config.google_cse_key
  }

  if animated
    animated_params = {
      fileType: "gif",
      hq: "animated",
      tbs: "itp:animated"
    }
    query_params.merge!(animated_params)
  end

  http_response = http.get(
    URL,
    query_params
  )

  data = MultiJson.load(http_response.body)

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

#fetch_anim(response) ⇒ Object



28
29
30
# File 'lib/lita/handlers/google_images.rb', line 28

def fetch_anim(response)
  fetch(response, true)
end