Class: Lita::Handlers::DanishImageSearch

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

Constant Summary collapse

URL =

insert handler code here

"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



28
29
30
31
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
# File 'lib/lita/handlers/danish_image_search.rb', line 28

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: 'a0ee38aab0d0f7bcc',
    key: 'AIzaSyDyY2ijQCoSf9z5rqaE2aeKX9Ul-pEUnWQ'
  }

  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



24
25
26
# File 'lib/lita/handlers/danish_image_search.rb', line 24

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