]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/search.rb
plugin(search): fix wolfram and gdef, removed some
[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_XPATH_DEF = "//img[@id='flex_text_audio_icon_chunk']/../../../../div[3]//text()"
23 DDG_API_SEARCH = "http://api.duckduckgo.com/?format=xml&no_html=1&skip_disambig=1&no_redirect=0&q="
24 WOLFRAM_API_SEARCH = "http://api.wolframalpha.com/v2/query?input=%{terms}&appid=%{key}&format=plaintext" +
25            "&scantimeout=3.0&podtimeout=4.0&formattimeout=8.0&parsetimeout=5.0" +
26            "&excludepodid=SeriesRepresentations:*"
27 WOLFRAM_API_KEY = "9RW6XR-QTL2JT7J4W"
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 "wa"
61       "wa <string> => searches WolframAlpha for <string>"
62     when "wp"
63       "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
64     when "unpedia"
65       "unpedia <string> => search for <string> on Uncyclopedia"
66     else
67       "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"
68     end
69   end
70
71   def duckduckgo(m, params)
72     what = params[:words].to_s
73     terms = CGI.escape what
74     url = DDG_API_SEARCH + terms
75
76     hits = @bot.config['duckduckgo.hits']
77     first_pars = params[:firstpar] || @bot.config['duckduckgo.first_par']
78     single = params[:lucky] || (hits == 1 and first_pars == 1)
79
80     begin
81       feed = @bot.httputil.get(url)
82       raise unless feed
83     rescue => e
84       m.reply "error duckduckgoing for #{what}"
85       return
86     end
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     abfrom = ""
95     unless abstract.empty?
96       absrc = xml.elements['//AbstractSource/text()'].to_s
97       aburl = xml.elements['//AbstractURL/text()'].to_s
98       unless absrc.empty? and aburl.empty?
99         abfrom = " --"
100         abfrom << " " << absrc unless absrc.empty?
101         abfrom << " " << aburl unless aburl.empty?
102       end
103     end
104
105     # but also definition (yes, you can have both, see e.g. printf)
106     definition = xml.elements['//Definition/text()'].to_s
107     deffrom = ""
108     unless definition.empty?
109       defsrc = xml.elements['//Definition/@source/text()'].to_s
110       defurl = xml.elements['//Definition/@url/text()'].to_s
111       unless defsrc.empty? and defurl.empty?
112         deffrom = " --"
113         deffrom << " " << defsrc unless defsrc.empty?
114         deffrom << " " << defurl unless defurl.empty?
115       end
116     end
117
118     if heading.empty? and answer.empty? and abstract.empty? and definition.empty?
119       m.reply "no results"
120       return
121     end
122
123     # if we got a one-shot answer (e.g. a calculation, return it)
124     unless answer.empty?
125       m.reply answer
126       return
127     end
128
129     # otherwise, return the abstract, followed by as many hits as found
130     unless heading.empty? or abstract.empty?
131       m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
132         :bold => Bold, :heading => heading,
133         :abstract => abstract, :abfrom => abfrom
134       }
135     end
136     unless heading.empty? or definition.empty?
137       m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
138         :bold => Bold, :heading => heading,
139         :abstract => definition, :abfrom => deffrom
140       }
141     end
142     # return zeroclick search results
143     links, texts = [], []
144     xml.elements.each("//Results/Result/FirstURL") { |element|
145       links << element.text
146       break if links.size == hits
147     }
148     return if links.empty?
149
150     xml.elements.each("//Results/Result/Text") { |element|
151       texts << " #{element.text}"
152       break if links.size == hits
153     }
154     # TODO see treatment of `single` in google search
155
156     single ||= (links.length == 1)
157     pretty = []
158     links.each_with_index do |u, i|
159       t = texts[i]
160       pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
161         :n => (single ? "" : "#{i}. "),
162         :sep => (single ? " -- " : ": "),
163         :b => Bold, :t => t, :u => u
164       })
165     end
166
167     result_string = pretty.join(" | ")
168
169     # If we return a single, full result, change the output to a more compact representation
170     if single
171       fp = first_pars > 0 ? " --  #{Utils.get_first_pars(links, first_pars)}" : ""
172       m.reply("Result for %{what}: %{string}%{fp}" % {
173         :what => what, :string => result_string, :fp => fp
174       }, :overlong => :truncate)
175       return
176     end
177
178     m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
179
180     return unless first_pars > 0
181
182     Utils.get_first_pars urls, first_pars, :message => m
183   end
184
185   def google(m, params)
186     what = params[:words].to_s
187     if what.match(/^define:/)
188       return google_define(m, what, params)
189     end
190
191     searchfor = CGI.escape what
192     # This method is also called by other methods to restrict searching to some sites
193     if params[:site]
194       site = "site:#{params[:site]}+"
195     else
196       site = ""
197     end
198     # It is also possible to choose a filter to remove constant parts from the titles
199     # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
200     filter = params[:filter] || ""
201
202     url = GOOGLE_WAP_SEARCH + site + searchfor
203
204     hits = params[:hits] || @bot.config['google.hits']
205     hits = 1 if params[:lucky]
206
207     first_pars = params[:firstpar] || @bot.config['google.first_par']
208
209     single = params[:lucky] || (hits == 1 and first_pars == 1)
210
211     begin
212       wml = @bot.httputil.get(url)
213       raise unless wml
214     rescue => e
215       m.reply "error googling for #{what}"
216       return
217     end
218     results = wml.scan(GOOGLE_WAP_LINK)
219
220     if results.length == 0
221       m.reply "no results found for #{what}"
222       return
223     end
224
225     results = results.map {|result|
226       url = CGI::parse(Utils.decode_html_entities(result[0]))['q'].first
227       title = Utils.decode_html_entities(result[1].gsub(/<\/?[^>]+>/, ''))
228       [url, title] unless url.empty? or title.empty?
229     }.reject {|item| not item}[0..hits]
230
231     result_string = results.map {|url, title| "#{Bold}#{title}#{NormalText}: #{url}"}
232
233     if params[:lucky]
234       m.reply result_string.first
235       Utils.get_first_pars([results.map {|url, title| url}.first], first_pars, :message => m)
236       return
237     end
238
239     m.reply "Results for #{what}: #{result_string.join(' | ')}", :split_at => /\s+\|\s+/
240
241     return unless first_pars > 0
242
243     Utils.get_first_pars(results.map {|url, title| url}, first_pars, :message => m)
244   end
245
246   def google_define(m, what, params)
247     begin
248       wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
249       raise unless wml
250     rescue => e
251       m.reply "error googling for #{what}"
252       return
253     end
254
255     begin
256       related_index = wml.index(/Related phrases:/, 0)
257       raise unless related_index
258       defs_index = wml.index(/Definitions of <b>/, related_index)
259       raise unless defs_index
260       defs_end = wml.index(/<input/, defs_index)
261       raise unless defs_end
262     rescue => e
263       m.reply "no results found for #{what}"
264       return
265     end
266
267     related = wml[related_index...defs_index]
268     defs = wml[defs_index...defs_end]
269
270     m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
271
272   end
273
274   def lucky(m, params)
275     params.merge!(:lucky => true)
276     google(m, params)
277   end
278
279   def gcalc(m, params)
280     what = params[:words].to_s
281     searchfor = CGI.escape(what)
282
283     debug "Getting gcalc thing: #{searchfor.inspect}"
284     url = GOOGLE_WAP_SEARCH + searchfor
285
286     begin
287       html = @bot.httputil.get(url)
288     rescue => e
289       m.reply "error googlecalcing #{what}"
290       return
291     end
292
293     debug "#{html.size} bytes of html recieved"
294     debug html
295
296     candidates = html.match(GOOGLE_CALC_RESULT)
297     debug "candidates: #{candidates.inspect}"
298
299     if candidates.nil?
300       m.reply "couldn't calculate #{what}"
301       return
302     end
303     result = candidates[1].remove_nonascii
304
305     debug "replying with: #{result.inspect}"
306     m.reply result.ircify_html
307   end
308
309   def gdef(m, params)
310     what = params[:words].to_s
311     searchfor = CGI.escape("define " + what)
312
313     debug "Getting gdef thing: #{searchfor.inspect}"
314     url = GOOGLE_WAP_SEARCH + searchfor
315
316     begin
317       resp = @bot.httputil.get(url, resp: true)
318     rescue => e
319       m.reply "error googledefining #{what}"
320       return
321     end
322
323     results = resp.xpath(GOOGLE_XPATH_DEF).map(&:content)
324
325     if results.empty?
326       m.reply "couldn't find a definition for #{what} on Google"
327     else
328       m.reply "#{results.first} -- #{results[1..-1].join(' ')}"
329     end
330   end
331
332   def wolfram(m, params)
333     what = params[:words].to_s
334     terms = CGI.escape what
335     url = WOLFRAM_API_SEARCH % {
336       :terms => terms, :key => WOLFRAM_API_KEY
337     }
338
339     begin
340       feed = @bot.httputil.get(url)
341       raise unless feed
342     rescue => e
343       m.reply "error asking WolframAlfa about #{what}"
344       return
345     end
346     debug feed
347
348     xml = REXML::Document.new feed
349     if xml.elements['/queryresult'].attributes['error'] == "true"
350       m.reply xml.elements['/queryresult/error/text()'].to_s
351       return
352     end
353     unless xml.elements['/queryresult'].attributes['success'] == "true"
354       m.reply "no data available"
355       return
356     end
357     answer_type, answer = [], []
358     xml.elements.each("//pod") { |element|
359       answer_type << element.attributes['title']
360       answer << element.elements['subpod/plaintext'].text
361     }
362     # find the first answer that isn't nil,
363     # starting on the second pod in the array
364     n = 1
365     answer[1..-1].each { |a|
366       break unless a.nil?
367       n += 1
368     }
369     if answer[n].nil?
370       m.reply "no results"
371       return
372     end
373     # strip spaces, pipes, and line breaks
374     sep = Bold + ' :: ' + Bold
375     chars = [ [/\n/, sep], [/\t/, " "], [/\s+/, " "], ["|", "-"] ]
376     chars.each { |c| answer[n].gsub!(c[0], c[1]) }
377     m.reply answer_type[n] + sep + answer[n]
378   end
379
380   def wikipedia(m, params)
381     lang = params[:lang]
382     site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
383     debug "Looking up things on #{site}"
384     params[:site] = site
385     params[:filter] = / - Wikipedia.*$/
386     params[:hits] = @bot.config['wikipedia.hits']
387     params[:firstpar] = @bot.config['wikipedia.first_par']
388     return google(m, params)
389   end
390
391   def unpedia(m, params)
392     site = "uncyclopedia.org"
393     debug "Looking up things on #{site}"
394     params[:site] = site
395     params[:filter] = / - Uncyclopedia.*$/
396     params[:hits] = @bot.config['wikipedia.hits']
397     params[:firstpar] = @bot.config['wikipedia.first_par']
398     return google(m, params)
399   end
400 end
401
402 plugin = SearchPlugin.new
403
404 plugin.map "ddg *words", :action => 'duckduckgo', :threaded => true
405 plugin.map "search *words", :action => 'google', :threaded => true
406 plugin.map "google *words", :action => 'google', :threaded => true
407 plugin.map "lucky *words", :action => 'lucky', :threaded => true
408 plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
409 plugin.map "gdef *words", :action => 'gdef', :threaded => true
410 plugin.map "wa *words", :action => 'wolfram', :threaded => true
411 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
412 plugin.map "wp *words", :action => 'wikipedia', :threaded => true
413 plugin.map "unpedia *words", :action => 'unpedia', :threaded => true