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