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