]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/search.rb
plugin(search): fix search and gcalc, closes #28, #29
[user/henk/code/ruby/rbot.git] / 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 = "https://www.google.com/search?hl=en&oe=UTF-8&ie=UTF-8&gbv=1&q="
19 GOOGLE_WAP_SEARCH = "https://www.google.com/m/search?hl=en&ie=UTF-8&gbv=1&q="
20 GOOGLE_WAP_LINK = /<a\s+href="\/url\?(q=[^"]+)"[^>]*>\s*<div[^>]*>(.*?)\s*<\/div>/im
21 GOOGLE_CALC_RESULT = />Calculator<\/span>(?:<\/?[^>]+>\s*)+([^<]+)/ 
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
94     xml = REXML::Document.new feed
95     heading = xml.elements['//Heading/text()'].to_s
96     # answer is returned for calculations
97     answer = xml.elements['//Answer/text()'].to_s
98     # abstract is returned for definitions etc
99     abstract = xml.elements['//AbstractText/text()'].to_s
100     abfrom = ""
101     unless abstract.empty?
102       absrc = xml.elements['//AbstractSource/text()'].to_s
103       aburl = xml.elements['//AbstractURL/text()'].to_s
104       unless absrc.empty? and aburl.empty?
105         abfrom = " --"
106         abfrom << " " << absrc unless absrc.empty?
107         abfrom << " " << aburl unless aburl.empty?
108       end
109     end
110
111     # but also definition (yes, you can have both, see e.g. printf)
112     definition = xml.elements['//Definition/text()'].to_s
113     deffrom = ""
114     unless definition.empty?
115       defsrc = xml.elements['//Definition/@source/text()'].to_s
116       defurl = xml.elements['//Definition/@url/text()'].to_s
117       unless defsrc.empty? and defurl.empty?
118         deffrom = " --"
119         deffrom << " " << defsrc unless defsrc.empty?
120         deffrom << " " << defurl unless defurl.empty?
121       end
122     end
123
124     if heading.empty? and answer.empty? and abstract.empty? and definition.empty?
125       m.reply "no results"
126       return
127     end
128
129     # if we got a one-shot answer (e.g. a calculation, return it)
130     unless answer.empty?
131       m.reply answer
132       return
133     end
134
135     # otherwise, return the abstract, followed by as many hits as found
136     unless heading.empty? or abstract.empty?
137       m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
138         :bold => Bold, :heading => heading,
139         :abstract => abstract, :abfrom => abfrom
140       }
141     end
142     unless heading.empty? or definition.empty?
143       m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
144         :bold => Bold, :heading => heading,
145         :abstract => definition, :abfrom => deffrom
146       }
147     end
148     # return zeroclick search results
149     links, texts = [], []
150     xml.elements.each("//Results/Result/FirstURL") { |element|
151       links << element.text
152       break if links.size == hits
153     }
154     return if links.empty?
155
156     xml.elements.each("//Results/Result/Text") { |element|
157       texts << " #{element.text}"
158       break if links.size == hits
159     }
160     # TODO see treatment of `single` in google search
161
162     single ||= (links.length == 1)
163     pretty = []
164     links.each_with_index do |u, i|
165       t = texts[i]
166       pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
167         :n => (single ? "" : "#{i}. "),
168         :sep => (single ? " -- " : ": "),
169         :b => Bold, :t => t, :u => u
170       })
171     end
172
173     result_string = pretty.join(" | ")
174
175     # If we return a single, full result, change the output to a more compact representation
176     if single
177       fp = first_pars > 0 ? " --  #{Utils.get_first_pars(links, first_pars)}" : ""
178       m.reply("Result for %{what}: %{string}%{fp}" % {
179         :what => what, :string => result_string, :fp => fp
180       }, :overlong => :truncate)
181       return
182     end
183
184     m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
185
186     return unless first_pars > 0
187
188     Utils.get_first_pars urls, first_pars, :message => m
189   end
190
191   def google(m, params)
192     what = params[:words].to_s
193     if what.match(/^define:/)
194       return google_define(m, what, params)
195     end
196
197     searchfor = CGI.escape what
198     # This method is also called by other methods to restrict searching to some sites
199     if params[:site]
200       site = "site:#{params[:site]}+"
201     else
202       site = ""
203     end
204     # It is also possible to choose a filter to remove constant parts from the titles
205     # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
206     filter = params[:filter] || ""
207
208     url = GOOGLE_WAP_SEARCH + site + searchfor
209
210     hits = params[:hits] || @bot.config['google.hits']
211     hits = 1 if params[:lucky]
212
213     first_pars = params[:firstpar] || @bot.config['google.first_par']
214
215     single = params[:lucky] || (hits == 1 and first_pars == 1)
216
217     begin
218       wml = @bot.httputil.get(url)
219       raise unless wml
220     rescue => e
221       m.reply "error googling for #{what}"
222       return
223     end
224     results = wml.scan(GOOGLE_WAP_LINK)
225
226     if results.length == 0
227       m.reply "no results found for #{what}"
228       return
229     end
230
231     results = results.map {|result|
232       url = CGI::parse(Utils.decode_html_entities(result[0]))['q'].first
233       title = Utils.decode_html_entities(result[1].gsub(/<\/?[^>]+>/, ''))
234       [url, title] unless url.empty? or title.empty?
235     }.reject {|item| not item}[0..hits]
236
237     result_string = results.map {|url, title| "#{Bold}#{title}#{NormalText}: #{url}"}
238
239     if params[:lucky]
240       m.reply result_string.first
241       Utils.get_first_pars([results.map {|url, title| url}.first], first_pars, :message => m)
242       return
243     end
244
245     m.reply "Results for #{what}: #{result_string.join(' | ')}", :split_at => /\s+\|\s+/
246
247     return unless first_pars > 0
248
249     Utils.get_first_pars(results.map {|url, title| url}, first_pars, :message => m)
250   end
251
252   def google_define(m, what, params)
253     begin
254       wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
255       raise unless wml
256     rescue => e
257       m.reply "error googling for #{what}"
258       return
259     end
260
261     begin
262       related_index = wml.index(/Related phrases:/, 0)
263       raise unless related_index
264       defs_index = wml.index(/Definitions of <b>/, related_index)
265       raise unless defs_index
266       defs_end = wml.index(/<input/, defs_index)
267       raise unless defs_end
268     rescue => e
269       m.reply "no results found for #{what}"
270       return
271     end
272
273     related = wml[related_index...defs_index]
274     defs = wml[defs_index...defs_end]
275
276     m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
277
278   end
279
280   def lucky(m, params)
281     params.merge!(:lucky => true)
282     google(m, params)
283   end
284
285   def gcalc(m, params)
286     what = params[:words].to_s
287     searchfor = CGI.escape(what)
288
289     debug "Getting gcalc thing: #{searchfor.inspect}"
290     url = GOOGLE_WAP_SEARCH + searchfor
291
292     begin
293       html = @bot.httputil.get(url)
294     rescue => e
295       m.reply "error googlecalcing #{what}"
296       return
297     end
298
299     debug "#{html.size} bytes of html recieved"
300     debug html
301
302     candidates = html.match(GOOGLE_CALC_RESULT)
303     debug "candidates: #{candidates.inspect}"
304
305     if candidates.nil?
306       m.reply "couldn't calculate #{what}"
307       return
308     end
309     result = candidates[1].remove_nonascii
310
311     debug "replying with: #{result.inspect}"
312     m.reply result.ircify_html
313   end
314
315   def gcount(m, params)
316     what = params[:words].to_s
317     searchfor = CGI.escape(what)
318
319     debug "Getting gcount thing: #{searchfor.inspect}"
320     url = GOOGLE_SEARCH + searchfor
321
322     begin
323       html = @bot.httputil.get(url)
324     rescue => e
325       m.reply "error googlecounting #{what}"
326       return
327     end
328
329     debug "#{html.size} bytes of html recieved"
330
331     results = html.scan(GOOGLE_COUNT_RESULT)
332     debug "results: #{results.inspect}"
333
334     if results.length != 1
335       m.reply "couldn't count #{what}"
336       return
337     end
338
339     result = results[0][0].ircify_html
340     debug "replying with: #{result.inspect}"
341     m.reply "total results: #{result}"
342
343   end
344
345   def gdef(m, params)
346     what = params[:words].to_s
347     searchfor = CGI.escape("define " + what)
348
349     debug "Getting gdef thing: #{searchfor.inspect}"
350     url = GOOGLE_WAP_SEARCH + searchfor
351
352     begin
353       html = @bot.httputil.get(url)
354     rescue => e
355       m.reply "error googledefining #{what}"
356       return
357     end
358
359     debug html
360     results = html.scan(GOOGLE_DEF_RESULT)
361     debug "results: #{results.inspect}"
362
363     if results.length != 1
364       m.reply "couldn't find a definition for #{what} on Google"
365       return
366     end
367
368     head = results[0][0].ircify_html
369     text = results[0][1].ircify_html
370     m.reply "#{head} -- #{text}"
371   end
372
373   def wolfram(m, params)
374     what = params[:words].to_s
375     terms = CGI.escape what
376     url = WOLFRAM_API_SEARCH % {
377       :terms => terms, :key => WOLFRAM_API_KEY
378     }
379
380     begin
381       feed = @bot.httputil.get(url)
382       raise unless feed
383     rescue => e
384       m.reply "error asking WolframAlfa about #{what}"
385       return
386     end
387     debug feed
388
389     xml = REXML::Document.new feed
390     if xml.elements['/queryresult'].attributes['error'] == "true"
391       m.reply xml.elements['/queryresult/error/text()'].to_s
392       return
393     end
394     unless xml.elements['/queryresult'].attributes['success'] == "true"
395       m.reply "no data available"
396       return
397     end
398     answer_type, answer = [], []
399     xml.elements.each("//pod") { |element|
400       answer_type << element.attributes['title']
401       answer << element.elements['subpod/plaintext'].text
402     }
403     # find the first answer that isn't nil,
404     # starting on the second pod in the array
405     n = 1
406     answer[1..-1].each { |a|
407       break unless a.nil?
408       n += 1
409     }
410     if answer[n].nil?
411       m.reply "no results"
412       return
413     end
414     # strip spaces, pipes, and line breaks
415     sep = Bold + ' :: ' + Bold
416     chars = [ [/\n/, sep], [/\t/, " "], [/\s+/, " "], ["|", "-"] ]
417     chars.each { |c| answer[n].gsub!(c[0], c[1]) }
418     m.reply answer_type[n] + sep + answer[n]
419   end
420
421   def wikipedia(m, params)
422     lang = params[:lang]
423     site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
424     debug "Looking up things on #{site}"
425     params[:site] = site
426     params[:filter] = / - Wikipedia.*$/
427     params[:hits] = @bot.config['wikipedia.hits']
428     params[:firstpar] = @bot.config['wikipedia.first_par']
429     return google(m, params)
430   end
431
432   def unpedia(m, params)
433     site = "uncyclopedia.org"
434     debug "Looking up things on #{site}"
435     params[:site] = site
436     params[:filter] = / - Uncyclopedia.*$/
437     params[:hits] = @bot.config['wikipedia.hits']
438     params[:firstpar] = @bot.config['wikipedia.first_par']
439     return google(m, params)
440   end
441
442   def gtime(m, params)
443     where = params[:words].to_s
444     where.sub!(/^\s*in\s*/, '')
445     searchfor = CGI.escape("time in " + where)
446     url = GOOGLE_SEARCH + searchfor
447
448     begin
449       html = @bot.httputil.get(url)
450     rescue => e
451       m.reply "Error googletiming #{where}"
452       return
453     end
454
455     debug html
456     results = html.scan(GOOGLE_TIME_RESULT)
457     debug "results: #{results.inspect}"
458
459     if results.length != 1
460       m.reply "Couldn't find the time for #{where} on Google"
461       return
462     end
463
464     time = results[0][0].ircify_html
465     m.reply "#{time}"
466   end
467 end
468
469 plugin = SearchPlugin.new
470
471   plugin.map "ddg *words", :action => 'duckduckgo', :threaded => true
472   plugin.map "search *words", :action => 'google', :threaded => true
473   plugin.map "google *words", :action => 'google', :threaded => true
474   plugin.map "lucky *words", :action => 'lucky', :threaded => true
475
476 # Broken:
477 plugin.map "gcount *words", :action => 'gcount', :threaded => true
478
479 plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
480 plugin.map "gdef *words", :action => 'gdef', :threaded => true
481 plugin.map "gtime *words", :action => 'gtime', :threaded => true
482 plugin.map "wa *words", :action => 'wolfram', :threaded => true
483 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
484 plugin.map "wp *words", :action => 'wikipedia', :threaded => true
485 plugin.map "unpedia *words", :action => 'unpedia', :threaded => true