Class: Lita::Handlers::Wikipedia

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

Constant Summary collapse

API_URL =
"https://en.wikipedia.org/w/api.php"

Instance Method Summary collapse

Instance Method Details

#wikipedia(response) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/lita/handlers/wikipedia.rb', line 13

def wikipedia(response)
  term = response.matches[0][0]
  search = http.get(
    API_URL,
    search: term,
    action: "opensearch",
    format: "json"
  )
  titles = MultiJson.load(search.body)[1]
  return response.reply("No Wikipedia entry found for '#{term}'") if titles.empty?
  query = http.get(
    API_URL,
    titles: titles[0],
    action: "query",
    prop: "extracts|info",
    exintro: nil,
    inprop: "url",
    redirects: nil,
    format: "json"
  )
  page = MultiJson.load(query.body)["query"]["pages"].values[0]
  html = Nokogiri::HTML(page["extract"])
  extract = Sanitize.fragment(html.xpath("//p[1]")[0]).strip
  url = page["fullurl"]
  response.reply(extract)
  response.reply("Source: #{url}")
end