4 # :title: Google and Wikipedia search plugin for rbot
6 # Author:: Tom Gilbert (giblet) <tom@linuxbrit.co.uk>
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
9 # Copyright:: (C) 2002-2005 Tom Gilbert
10 # Copyright:: (C) 2006 Tom Gilbert, Giuseppe Bilotta
11 # Copyright:: (C) 2006-2007 Giuseppe Bilotta
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
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)>}
26 DDG_API_SEARCH = "http://api.duckduckgo.com/?format=xml&no_html=1&skip_disambig=1&no_redirect=0&q="
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"
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',
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',
42 :desc => "Number of hits to return from Google searches")
43 Config.register Config::IntegerValue.new('google.first_par',
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',
48 :desc => "Number of hits to return from Wikipedia searches")
49 Config.register Config::IntegerValue.new('wikipedia.first_par',
51 :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
53 def help(plugin, topic="")
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>"
61 "gcalc <equation> => use the google calculator to find the answer to <equation>"
63 "gdef <term(s)> => use the google define mechanism to find a definition of <term(s)>"
65 "gtime <location> => use the google clock to find the current time at <location>"
67 "wa <string> => searches WolframAlpha for <string>"
69 "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
71 "unpedia <string> => search for <string> on Uncyclopedia"
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"
77 def duckduckgo(m, params)
78 what = params[:words].to_s
79 terms = CGI.escape what
80 url = DDG_API_SEARCH + terms
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)
87 feed = @bot.httputil.get(url)
90 m.reply "error duckduckgoing for #{what}"
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
102 unless abstract.empty?
103 absrc = xml.elements['//AbstractSource/text()'].to_s
104 aburl = xml.elements['//AbstractURL/text()'].to_s
105 unless absrc.empty? and aburl.empty?
107 abfrom << " " << absrc unless absrc.empty?
108 abfrom << " " << aburl unless aburl.empty?
112 # but also definition (yes, you can have both, see e.g. printf)
113 definition = xml.elements['//Definition/text()'].to_s
115 unless definition.empty?
116 defsrc = xml.elements['//Definition/@source/text()'].to_s
117 defurl = xml.elements['//Definition/@url/text()'].to_s
118 unless defsrc.empty? and defurl.empty?
120 deffrom << " " << defsrc unless defsrc.empty?
121 deffrom << " " << defurl unless defurl.empty?
125 if heading.empty? and answer.empty? and abstract.empty? and definition.empty?
130 # if we got a one-shot answer (e.g. a calculation, return it)
136 # otherwise, return the abstract, followed by as many hits as found
137 unless heading.empty? or abstract.empty?
138 m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
139 :bold => Bold, :heading => heading,
140 :abstract => abstract, :abfrom => abfrom
143 unless heading.empty? or definition.empty?
144 m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
145 :bold => Bold, :heading => heading,
146 :abstract => definition, :abfrom => deffrom
149 # return zeroclick search results
150 links, texts = [], []
151 xml.elements.each("//Results/Result/FirstURL") { |element|
152 links << element.text
153 break if links.size == hits
155 return if links.empty?
157 xml.elements.each("//Results/Result/Text") { |element|
158 texts << " #{element.text}"
159 break if links.size == hits
161 # TODO see treatment of `single` in google search
163 single ||= (links.length == 1)
165 links.each_with_index do |u, i|
167 pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
168 :n => (single ? "" : "#{i}. "),
169 :sep => (single ? " -- " : ": "),
170 :b => Bold, :t => t, :u => u
174 result_string = pretty.join(" | ")
176 # If we return a single, full result, change the output to a more compact representation
178 fp = first_pars > 0 ? " -- #{Utils.get_first_pars(links, first_pars)}" : ""
179 m.reply("Result for %{what}: %{string}%{fp}" % {
180 :what => what, :string => result_string, :fp => fp
181 }, :overlong => :truncate)
185 m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
187 return unless first_pars > 0
189 Utils.get_first_pars urls, first_pars, :message => m
192 def google(m, params)
193 what = params[:words].to_s
194 if what.match(/^define:/)
195 return google_define(m, what, params)
198 searchfor = CGI.escape what
199 # This method is also called by other methods to restrict searching to some sites
201 site = "site:#{params[:site]}+"
205 # It is also possible to choose a filter to remove constant parts from the titles
206 # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
207 filter = params[:filter] || ""
209 url = GOOGLE_WAP_SEARCH + site + searchfor
211 hits = params[:hits] || @bot.config['google.hits']
212 hits = 1 if params[:lucky]
214 first_pars = params[:firstpar] || @bot.config['google.first_par']
216 single = params[:lucky] || (hits == 1 and first_pars == 1)
219 wml = @bot.httputil.get(url)
222 m.reply "error googling for #{what}"
225 results = wml.scan(GOOGLE_WAP_LINK)
227 if results.length == 0
228 m.reply "no results found for #{what}"
232 single ||= (results.length==1)
239 results.each do |res|
240 t = res[1].ircify_html(:img => "[%{src} %{alt} %{dimensions}]").strip
242 if u.sub!(%r{^http://www.google.com/aclk\?},'')
243 u = CGI::parse(u)['adurl'].first
244 debug "skipping ad for #{u}"
246 elsif u.sub!(%r{^http://www.google.com/gwt/x\?},'')
247 u = CGI::parse(u)['u'].first
248 elsif u.sub!(%r{^/url\?},'')
249 u = CGI::parse(u)['q'].first
252 pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
253 :n => (single ? "" : "#{urls.length}. "),
254 :sep => (single ? " -- " : ": "),
255 :b => Bold, :t => t, :u => u
257 break if urls.length == hits
260 m.reply "failed to understand what google found for #{what}"
272 result_string = pretty.join(" | ")
274 # If we return a single, full result, change the output to a more compact representation
276 m.reply "Result for %s: %s -- %s" % [what, result_string, Utils.get_first_pars(urls, first_pars)], :overlong => :truncate
280 m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
282 return unless first_pars > 0
284 Utils.get_first_pars urls, first_pars, :message => m
288 def google_define(m, what, params)
290 wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
293 m.reply "error googling for #{what}"
298 related_index = wml.index(/Related phrases:/, 0)
299 raise unless related_index
300 defs_index = wml.index(/Definitions of <b>/, related_index)
301 raise unless defs_index
302 defs_end = wml.index(/<input/, defs_index)
303 raise unless defs_end
305 m.reply "no results found for #{what}"
309 related = wml[related_index...defs_index]
310 defs = wml[defs_index...defs_end]
312 m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
317 params.merge!(:lucky => true)
322 what = params[:words].to_s
323 searchfor = CGI.escape(what)
325 debug "Getting gcalc thing: #{searchfor.inspect}"
326 url = GOOGLE_WAP_SEARCH + searchfor
329 html = @bot.httputil.get(url)
331 m.reply "error googlecalcing #{what}"
335 debug "#{html.size} bytes of html recieved"
338 candidates = html.match(GOOGLE_CALC_RESULT)
339 debug "candidates: #{candidates.inspect}"
342 m.reply "couldn't calculate #{what}"
345 result = candidates[1]
347 debug "replying with: #{result.inspect}"
348 m.reply result.ircify_html
351 def gcount(m, params)
352 what = params[:words].to_s
353 searchfor = CGI.escape(what)
355 debug "Getting gcount thing: #{searchfor.inspect}"
356 url = GOOGLE_SEARCH + searchfor
359 html = @bot.httputil.get(url)
361 m.reply "error googlecounting #{what}"
365 debug "#{html.size} bytes of html recieved"
367 results = html.scan(GOOGLE_COUNT_RESULT)
368 debug "results: #{results.inspect}"
370 if results.length != 1
371 m.reply "couldn't count #{what}"
375 result = results[0][0].ircify_html
376 debug "replying with: #{result.inspect}"
377 m.reply "total results: #{result}"
382 what = params[:words].to_s
383 searchfor = CGI.escape("define " + what)
385 debug "Getting gdef thing: #{searchfor.inspect}"
386 url = GOOGLE_WAP_SEARCH + searchfor
389 html = @bot.httputil.get(url)
391 m.reply "error googledefining #{what}"
396 results = html.scan(GOOGLE_DEF_RESULT)
397 debug "results: #{results.inspect}"
399 if results.length != 1
400 m.reply "couldn't find a definition for #{what} on Google"
404 head = results[0][0].ircify_html
405 text = results[0][1].ircify_html
406 m.reply "#{head} -- #{text}"
409 def wolfram(m, params)
410 what = params[:words].to_s
411 terms = CGI.escape what
412 url = WOLFRAM_API_SEARCH % {
413 :terms => terms, :key => WOLFRAM_API_KEY
417 feed = @bot.httputil.get(url)
420 m.reply "error asking WolframAlfa about #{what}"
425 xml = REXML::Document.new feed
426 if xml.elements['/queryresult'].attributes['error'] == "true"
427 m.reply xml.elements['/queryresult/error/text()'].to_s
430 unless xml.elements['/queryresult'].attributes['success'] == "true"
431 m.reply "no data available"
434 answer_type, answer = [], []
435 xml.elements.each("//pod") { |element|
436 answer_type << element.attributes['title']
437 answer << element.elements['subpod/plaintext'].text
439 # find the first answer that isn't nil,
440 # starting on the second pod in the array
442 answer[1..-1].each { |a|
450 # strip spaces, pipes, and line breaks
451 sep = Bold + ' :: ' + Bold
452 chars = [ [/\n/, sep], [/\t/, " "], [/\s+/, " "], ["|", "-"] ]
453 chars.each { |c| answer[n].gsub!(c[0], c[1]) }
454 m.reply answer_type[n] + sep + answer[n]
457 def wikipedia(m, params)
459 site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
460 debug "Looking up things on #{site}"
462 params[:filter] = / - Wikipedia.*$/
463 params[:hits] = @bot.config['wikipedia.hits']
464 params[:firstpar] = @bot.config['wikipedia.first_par']
465 return google(m, params)
468 def unpedia(m, params)
469 site = "uncyclopedia.org"
470 debug "Looking up things on #{site}"
472 params[:filter] = / - Uncyclopedia.*$/
473 params[:hits] = @bot.config['wikipedia.hits']
474 params[:firstpar] = @bot.config['wikipedia.first_par']
475 return google(m, params)
479 where = params[:words].to_s
480 where.sub!(/^\s*in\s*/, '')
481 searchfor = CGI.escape("time in " + where)
482 url = GOOGLE_SEARCH + searchfor
485 html = @bot.httputil.get(url)
487 m.reply "Error googletiming #{where}"
492 results = html.scan(GOOGLE_TIME_RESULT)
493 debug "results: #{results.inspect}"
495 if results.length != 1
496 m.reply "Couldn't find the time for #{where} on Google"
500 time = results[0][0].ircify_html
505 plugin = SearchPlugin.new
507 plugin.map "ddg *words", :action => 'duckduckgo', :threaded => true
508 plugin.map "search *words", :action => 'google', :threaded => true
509 plugin.map "google *words", :action => 'google', :threaded => true
510 plugin.map "lucky *words", :action => 'lucky', :threaded => true
511 plugin.map "gcount *words", :action => 'gcount', :threaded => true
512 plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
513 plugin.map "gdef *words", :action => 'gdef', :threaded => true
514 plugin.map "gtime *words", :action => 'gtime', :threaded => true
515 plugin.map "wa *words", :action => 'wolfram', :threaded => true
516 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
517 plugin.map "wp *words", :action => 'wikipedia', :threaded => true
518 plugin.map "unpedia *words", :action => 'unpedia', :threaded => true