search: preliminary Wolfram Alpha support
[rbot] / data / rbot / plugins / search.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Google and Wikipedia search plugin for rbot
5 #
6 # Author:: Tom Gilbert (giblet) <tom@linuxbrit.co.uk>
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
8 #
9 # Copyright:: (C) 2002-2005 Tom Gilbert
10 # Copyright:: (C) 2006 Tom Gilbert, Giuseppe Bilotta
11 # Copyright:: (C) 2006-2007 Giuseppe Bilotta
12
13 # TODO:: use lr=lang_<code> or whatever is most appropriate to let google know
14 #        it shouldn't use the bot's location to find the preferred language
15 # TODO:: support localized uncyclopedias -- not easy because they have different names
16 #        for most languages
17
18 GOOGLE_SEARCH = "http://www.google.com/search?oe=UTF-8&q="
19 GOOGLE_WAP_SEARCH = "http://www.google.com/m/search?hl=en&q="
20 GOOGLE_WAP_LINK = /"r">(?:<div[^>]*>)?<a href="([^"]+)"[^>]*>(.*?)<\/a>/im
21 GOOGLE_CALC_RESULT = %r{<h[1-6] class="r" [^>]*>(.+?)</h}
22 GOOGLE_COUNT_RESULT = %r{<font size=-1>Results <b>1<\/b> - <b>10<\/b> of about <b>(.*)<\/b> for}
23 GOOGLE_DEF_RESULT = %r{onebox_result">\s*(.*?)\s*<br/>\s*(.*?)<table}
24 GOOGLE_TIME_RESULT = %r{alt="Clock"></td><td valign=[^>]+>(.+?)<(br|/td)>}
25
26 DDG_API_SEARCH = "http://api.duckduckgo.com/?format=xml&no_html=1&skip_disambig=1&no_redirect=0&q="
27 WOLFRAM_API_KEY = "4EU37Y-TX9WJG3JH3"
28
29 class SearchPlugin < Plugin
30   Config.register Config::IntegerValue.new('duckduckgo.hits',
31     :default => 3, :validate => Proc.new{|v| v > 0},
32     :desc => "Number of hits to return from searches")
33   Config.register Config::IntegerValue.new('duckduckgo.first_par',
34     :default => 0,
35     :desc => "When set to n > 0, the bot will return the first paragraph from the first n search hits")
36   Config.register Config::IntegerValue.new('google.hits',
37     :default => 3,
38     :desc => "Number of hits to return from Google searches")
39   Config.register Config::IntegerValue.new('google.first_par',
40     :default => 0,
41     :desc => "When set to n > 0, the bot will return the first paragraph from the first n search hits")
42   Config.register Config::IntegerValue.new('wikipedia.hits',
43     :default => 3,
44     :desc => "Number of hits to return from Wikipedia searches")
45   Config.register Config::IntegerValue.new('wikipedia.first_par',
46     :default => 1,
47     :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
48
49   def help(plugin, topic="")
50     case topic
51     when "ddg"
52       "Use '#{topic} <string>' to return a search or calculation from " +
53       "DuckDuckGo. Use #{topic} define <string> to return a definition."
54     when "search", "google"
55       "#{topic} <string> => search google for <string>"
56     when "gcalc"
57       "gcalc <equation> => use the google calculator to find the answer to <equation>"
58     when "gdef"
59       "gdef <term(s)> => use the google define mechanism to find a definition of <term(s)>"
60     when "gtime"
61       "gtime <location> => use the google clock to find the current time at <location>"
62     when "wa"
63       "wa <string> => searches WolframAlpha for <string>"
64     when "wp"
65       "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
66     when "unpedia"
67       "unpedia <string> => search for <string> on Uncyclopedia"
68     else
69       "search <string> (or: google <string>) => search google for <string> | ddg <string> to search DuckDuckGo | wp <string> => search for <string> on Wikipedia | wa <string> => search for <string> on WolframAlpha | unpedia <string> => search for <string> on Uncyclopedia"
70     end
71   end
72
73   def duckduckgo(m, params)
74     what = params[:words].to_s
75     terms = CGI.escape what
76     url = DDG_API_SEARCH + terms
77
78     hits = @bot.config['duckduckgo.hits']
79     first_pars = params[:firstpar] || @bot.config['duckduckgo.first_par']
80     single = params[:lucky] || (hits == 1 and first_pars == 1)
81
82     begin
83       feed = @bot.httputil.get(url)
84       raise unless feed
85     rescue => e
86       m.reply "error duckduckgoing for #{what}"
87       return
88     end
89     debug feed
90
91     xml = REXML::Document.new feed
92     heading = xml.elements['//Heading/text()'].to_s
93     # answer is returned for calculations
94     answer = xml.elements['//Answer/text()'].to_s
95     # abstract is returned for definitions etc
96     abstract = xml.elements['//AbstractText/text()'].to_s
97     unless abstract.empty?
98       absrc = xml.elements['//AbstractSource/text()']
99       aburl = xml.elements['//AbstractURL/text()']
100     end
101     # but also definition (yes, you can have both, see e.g. printf)
102     definition = xml.elements['//Definition/text()'].to_s
103     unless definition.empty?
104       defsrc = xml.elements['//Definition/@source/text()'].to_s
105       defurl = xml.elements['//Definition/@url/text()'].to_s
106     end
107
108     if heading.empty? and answer.empty? and abstract.empty? and definition.empty?
109       m.reply "no results"
110       return
111     end
112
113     # if we got a one-shot answer (e.g. a calculation, return it)
114     unless answer.empty?
115       m.reply answer
116       return
117     end
118
119     # otherwise, return the abstract, followed by as many hits as found
120     unless heading.empty? or abstract.empty?
121       m.reply "%{bold}%{heading}:%{bold} %{abstract} -- %{absrc} %{aburl}" % {
122         :bold => Bold, :heading => heading,
123         :abstract => abstract, :absrc => absrc, :aburl => aburl
124       }
125     end
126     unless heading.empty? or definition.empty?
127       m.reply "%{bold}%{heading}:%{bold} %{abstract} -- %{absrc} %{aburl}" % {
128         :bold => Bold, :heading => heading,
129         :abstract => definition, :absrc => defsrc, :aburl => defurl
130       }
131     end
132     # return zeroclick search results
133     links, texts = [], []
134     xml.elements.each("//Results/Result/FirstURL") { |element|
135       links << element.text
136       break if links.size == hits
137     }
138     return if links.empty?
139
140     xml.elements.each("//Results/Result/Text") { |element|
141       texts << " #{element.text}"
142       break if links.size == hits
143     }
144     # TODO see treatment of `single` in google search
145
146     single ||= (links.length == 1)
147     pretty = []
148     links.each_with_index do |u, i|
149       t = texts[i]
150       pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
151         :n => (single ? "" : "#{i}. "),
152         :sep => (single ? " -- " : ": "),
153         :b => Bold, :t => t, :u => u
154       })
155     end
156
157     result_string = pretty.join(" | ")
158
159     # If we return a single, full result, change the output to a more compact representation
160     if single
161       fp = first_pars > 0 ? " --  #{Utils.get_first_pars(links, first_pars)}" : ""
162       m.reply("Result for %{what}: %{string}%{fp}" % {
163         :what => what, :string => result_string, :fp => fp
164       }, :overlong => :truncate)
165       return
166     end
167
168     m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
169
170     return unless first_pars > 0
171
172     Utils.get_first_pars urls, first_pars, :message => m
173   end
174
175   def google(m, params)
176     what = params[:words].to_s
177     if what.match(/^define:/)
178       return google_define(m, what, params)
179     end
180
181     searchfor = CGI.escape what
182     # This method is also called by other methods to restrict searching to some sites
183     if params[:site]
184       site = "site:#{params[:site]}+"
185     else
186       site = ""
187     end
188     # It is also possible to choose a filter to remove constant parts from the titles
189     # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
190     filter = params[:filter] || ""
191
192     url = GOOGLE_WAP_SEARCH + site + searchfor
193
194     hits = params[:hits] || @bot.config['google.hits']
195     hits = 1 if params[:lucky]
196
197     first_pars = params[:firstpar] || @bot.config['google.first_par']
198
199     single = params[:lucky] || (hits == 1 and first_pars == 1)
200
201     begin
202       wml = @bot.httputil.get(url)
203       raise unless wml
204     rescue => e
205       m.reply "error googling for #{what}"
206       return
207     end
208     results = wml.scan(GOOGLE_WAP_LINK)
209
210     if results.length == 0
211       m.reply "no results found for #{what}"
212       return
213     end
214
215     single ||= (results.length==1)
216     pretty = []
217
218     begin
219       urls = Array.new
220
221       debug results
222       results.each do |res|
223         t = res[1].ircify_html(:img => "[%{src} %{alt} %{dimensions}]").strip
224         u = res[0]
225         if u.sub!(%r{^http://www.google.com/aclk\?},'')
226           u = CGI::parse(u)['adurl'].first
227           debug "skipping ad for #{u}"
228           next
229         elsif u.sub!(%r{^http://www.google.com/gwt/x\?},'')
230           u = CGI::parse(u)['u'].first
231         elsif u.sub!(%r{^/url\?},'')
232           u = CGI::parse(u)['q'].first
233         end
234         urls.push(u)
235         pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
236           :n => (single ? "" : "#{urls.length}. "),
237           :sep => (single ? " -- " : ": "),
238           :b => Bold, :t => t, :u => u
239         })
240         break if urls.length == hits
241       end
242     rescue => e
243       m.reply "failed to understand what google found for #{what}"
244       error e
245       debug wml
246       debug results
247       return
248     end
249
250     if params[:lucky]
251       m.reply pretty.first
252       return
253     end
254
255     result_string = pretty.join(" | ")
256
257     # If we return a single, full result, change the output to a more compact representation
258     if single
259       m.reply "Result for %s: %s -- %s" % [what, result_string, Utils.get_first_pars(urls, first_pars)], :overlong => :truncate
260       return
261     end
262
263     m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
264
265     return unless first_pars > 0
266
267     Utils.get_first_pars urls, first_pars, :message => m
268
269   end
270
271   def google_define(m, what, params)
272     begin
273       wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
274       raise unless wml
275     rescue => e
276       m.reply "error googling for #{what}"
277       return
278     end
279
280     begin
281       related_index = wml.index(/Related phrases:/, 0)
282       raise unless related_index
283       defs_index = wml.index(/Definitions of <b>/, related_index)
284       raise unless defs_index
285       defs_end = wml.index(/<input/, defs_index)
286       raise unless defs_end
287     rescue => e
288       m.reply "no results found for #{what}"
289       return
290     end
291
292     related = wml[related_index...defs_index]
293     defs = wml[defs_index...defs_end]
294
295     m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
296
297   end
298
299   def lucky(m, params)
300     params.merge!(:lucky => true)
301     google(m, params)
302   end
303
304   def gcalc(m, params)
305     what = params[:words].to_s
306     searchfor = CGI.escape(what)
307
308     debug "Getting gcalc thing: #{searchfor.inspect}"
309     url = GOOGLE_WAP_SEARCH + searchfor
310
311     begin
312       html = @bot.httputil.get(url)
313     rescue => e
314       m.reply "error googlecalcing #{what}"
315       return
316     end
317
318     debug "#{html.size} bytes of html recieved"
319     debug html
320
321     candidates = html.match(GOOGLE_CALC_RESULT)
322     debug "candidates: #{candidates.inspect}"
323
324     if candidates.nil?
325       m.reply "couldn't calculate #{what}"
326       return
327     end
328     result = candidates[1]
329
330     debug "replying with: #{result.inspect}"
331     m.reply result.ircify_html
332   end
333
334   def gcount(m, params)
335     what = params[:words].to_s
336     searchfor = CGI.escape(what)
337
338     debug "Getting gcount thing: #{searchfor.inspect}"
339     url = GOOGLE_SEARCH + searchfor
340
341     begin
342       html = @bot.httputil.get(url)
343     rescue => e
344       m.reply "error googlecounting #{what}"
345       return
346     end
347
348     debug "#{html.size} bytes of html recieved"
349
350     results = html.scan(GOOGLE_COUNT_RESULT)
351     debug "results: #{results.inspect}"
352
353     if results.length != 1
354       m.reply "couldn't count #{what}"
355       return
356     end
357
358     result = results[0][0].ircify_html
359     debug "replying with: #{result.inspect}"
360     m.reply "total results: #{result}"
361
362   end
363
364   def gdef(m, params)
365     what = params[:words].to_s
366     searchfor = CGI.escape("define " + what)
367
368     debug "Getting gdef thing: #{searchfor.inspect}"
369     url = GOOGLE_WAP_SEARCH + searchfor
370
371     begin
372       html = @bot.httputil.get(url)
373     rescue => e
374       m.reply "error googledefining #{what}"
375       return
376     end
377
378     debug html
379     results = html.scan(GOOGLE_DEF_RESULT)
380     debug "results: #{results.inspect}"
381
382     if results.length != 1
383       m.reply "couldn't find a definition for #{what} on Google"
384       return
385     end
386
387     head = results[0][0].ircify_html
388     text = results[0][1].ircify_html
389     m.reply "#{head} -- #{text}"
390   end
391
392   def wolfram(m, params)
393     terms = CGI.escape(params[:words].to_s)
394     feed = Net::HTTP.get 'api.wolframalpha.com',
395            "/v2/query?input=#{terms}&appid=#{WOLFRAM_API_KEY}&format=plaintext"
396            "&scantimeout=3.0&podtimeout=4.0&formattimeout=8.0&parsetimeout=5.0"
397            "&excludepodid=SeriesRepresentations:*"
398     if feed.nil? or feed.empty?
399       m.reply "error connecting"
400       return
401     end
402     xml = REXML::Document.new feed
403     if xml.elements['/queryresult'].attributes['error'] == "true"
404       m.reply xml.elements['/queryresult/error/text()'].to_s
405       return
406     end
407     unless xml.elements['/queryresult'].attributes['success'] == "true"
408       m.reply "no data available"
409       return
410     end
411     answer = []
412     xml.elements.each("//pod/subpod/plaintext") { |element|
413       answer << element.text
414     }
415     # strip spaces and line breaks
416     answer[1].gsub!(/\n/, Bold + ' :: ' + Bold )
417     answer[1].gsub!(/\t/, ' ')
418     answer[1].gsub!(/\s+/, ' ')
419     m.reply answer[1].to_s
420   end
421
422   def wikipedia(m, params)
423     lang = params[:lang]
424     site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
425     debug "Looking up things on #{site}"
426     params[:site] = site
427     params[:filter] = / - Wikipedia.*$/
428     params[:hits] = @bot.config['wikipedia.hits']
429     params[:firstpar] = @bot.config['wikipedia.first_par']
430     return google(m, params)
431   end
432
433   def unpedia(m, params)
434     site = "uncyclopedia.org"
435     debug "Looking up things on #{site}"
436     params[:site] = site
437     params[:filter] = / - Uncyclopedia.*$/
438     params[:hits] = @bot.config['wikipedia.hits']
439     params[:firstpar] = @bot.config['wikipedia.first_par']
440     return google(m, params)
441   end
442
443   def gtime(m, params)
444     where = params[:words].to_s
445     where.sub!(/^\s*in\s*/, '')
446     searchfor = CGI.escape("time in " + where)
447     url = GOOGLE_SEARCH + searchfor
448
449     begin
450       html = @bot.httputil.get(url)
451     rescue => e
452       m.reply "Error googletiming #{where}"
453       return
454     end
455
456     debug html
457     results = html.scan(GOOGLE_TIME_RESULT)
458     debug "results: #{results.inspect}"
459
460     if results.length != 1
461       m.reply "Couldn't find the time for #{where} on Google"
462       return
463     end
464
465     time = results[0][0].ircify_html
466     m.reply "#{time}"
467   end
468 end
469
470 plugin = SearchPlugin.new
471
472 plugin.map "ddg *words", :action => 'duckduckgo'
473 plugin.map "search *words", :action => 'google', :threaded => true
474 plugin.map "google *words", :action => 'google', :threaded => true
475 plugin.map "lucky *words", :action => 'lucky', :threaded => true
476 plugin.map "gcount *words", :action => 'gcount', :threaded => true
477 plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
478 plugin.map "gdef *words", :action => 'gdef', :threaded => true
479 plugin.map "gtime *words", :action => 'gtime', :threaded => true
480 plugin.map "wa *words", :action => 'wolfram'
481 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
482 plugin.map "wp *words", :action => 'wikipedia', :threaded => true
483 plugin.map "unpedia *words", :action => 'unpedia', :threaded => true