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
101 unless abstract.empty?
102 absrc = xml.elements['//AbstractSource/text()']
103 aburl = xml.elements['//AbstractURL/text()']
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
112 if heading.empty? and answer.empty? and abstract.empty? and definition.empty?
117 # if we got a one-shot answer (e.g. a calculation, return it)
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
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
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
142 return if links.empty?
144 xml.elements.each("//Results/Result/Text") { |element|
145 texts << " #{element.text}"
146 break if links.size == hits
148 # TODO see treatment of `single` in google search
150 single ||= (links.length == 1)
152 links.each_with_index do |u, i|
154 pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
155 :n => (single ? "" : "#{i}. "),
156 :sep => (single ? " -- " : ": "),
157 :b => Bold, :t => t, :u => u
161 result_string = pretty.join(" | ")
163 # If we return a single, full result, change the output to a more compact representation
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)
172 m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
174 return unless first_pars > 0
176 Utils.get_first_pars urls, first_pars, :message => m
179 def google(m, params)
180 what = params[:words].to_s
181 if what.match(/^define:/)
182 return google_define(m, what, params)
185 searchfor = CGI.escape what
186 # This method is also called by other methods to restrict searching to some sites
188 site = "site:#{params[:site]}+"
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] || ""
196 url = GOOGLE_WAP_SEARCH + site + searchfor
198 hits = params[:hits] || @bot.config['google.hits']
199 hits = 1 if params[:lucky]
201 first_pars = params[:firstpar] || @bot.config['google.first_par']
203 single = params[:lucky] || (hits == 1 and first_pars == 1)
206 wml = @bot.httputil.get(url)
209 m.reply "error googling for #{what}"
212 results = wml.scan(GOOGLE_WAP_LINK)
214 if results.length == 0
215 m.reply "no results found for #{what}"
219 single ||= (results.length==1)
226 results.each do |res|
227 t = res[1].ircify_html(:img => "[%{src} %{alt} %{dimensions}]").strip
229 if u.sub!(%r{^http://www.google.com/aclk\?},'')
230 u = CGI::parse(u)['adurl'].first
231 debug "skipping ad for #{u}"
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
239 pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
240 :n => (single ? "" : "#{urls.length}. "),
241 :sep => (single ? " -- " : ": "),
242 :b => Bold, :t => t, :u => u
244 break if urls.length == hits
247 m.reply "failed to understand what google found for #{what}"
259 result_string = pretty.join(" | ")
261 # If we return a single, full result, change the output to a more compact representation
263 m.reply "Result for %s: %s -- %s" % [what, result_string, Utils.get_first_pars(urls, first_pars)], :overlong => :truncate
267 m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
269 return unless first_pars > 0
271 Utils.get_first_pars urls, first_pars, :message => m
275 def google_define(m, what, params)
277 wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
280 m.reply "error googling for #{what}"
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
292 m.reply "no results found for #{what}"
296 related = wml[related_index...defs_index]
297 defs = wml[defs_index...defs_end]
299 m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
304 params.merge!(:lucky => true)
309 what = params[:words].to_s
310 searchfor = CGI.escape(what)
312 debug "Getting gcalc thing: #{searchfor.inspect}"
313 url = GOOGLE_WAP_SEARCH + searchfor
316 html = @bot.httputil.get(url)
318 m.reply "error googlecalcing #{what}"
322 debug "#{html.size} bytes of html recieved"
325 candidates = html.match(GOOGLE_CALC_RESULT)
326 debug "candidates: #{candidates.inspect}"
329 m.reply "couldn't calculate #{what}"
332 result = candidates[1]
334 debug "replying with: #{result.inspect}"
335 m.reply result.ircify_html
338 def gcount(m, params)
339 what = params[:words].to_s
340 searchfor = CGI.escape(what)
342 debug "Getting gcount thing: #{searchfor.inspect}"
343 url = GOOGLE_SEARCH + searchfor
346 html = @bot.httputil.get(url)
348 m.reply "error googlecounting #{what}"
352 debug "#{html.size} bytes of html recieved"
354 results = html.scan(GOOGLE_COUNT_RESULT)
355 debug "results: #{results.inspect}"
357 if results.length != 1
358 m.reply "couldn't count #{what}"
362 result = results[0][0].ircify_html
363 debug "replying with: #{result.inspect}"
364 m.reply "total results: #{result}"
369 what = params[:words].to_s
370 searchfor = CGI.escape("define " + what)
372 debug "Getting gdef thing: #{searchfor.inspect}"
373 url = GOOGLE_WAP_SEARCH + searchfor
376 html = @bot.httputil.get(url)
378 m.reply "error googledefining #{what}"
383 results = html.scan(GOOGLE_DEF_RESULT)
384 debug "results: #{results.inspect}"
386 if results.length != 1
387 m.reply "couldn't find a definition for #{what} on Google"
391 head = results[0][0].ircify_html
392 text = results[0][1].ircify_html
393 m.reply "#{head} -- #{text}"
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
404 feed = @bot.httputil.get(url)
407 m.reply "error asking WolframAlfa about #{what}"
412 xml = REXML::Document.new feed
413 if xml.elements['/queryresult'].attributes['error'] == "true"
414 m.reply xml.elements['/queryresult/error/text()'].to_s
417 unless xml.elements['/queryresult'].attributes['success'] == "true"
418 m.reply "no data available"
422 xml.elements.each("//pod/subpod/plaintext") { |element|
423 answer << element.text
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
432 def wikipedia(m, params)
434 site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
435 debug "Looking up things on #{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)
443 def unpedia(m, params)
444 site = "uncyclopedia.org"
445 debug "Looking up things on #{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)
454 where = params[:words].to_s
455 where.sub!(/^\s*in\s*/, '')
456 searchfor = CGI.escape("time in " + where)
457 url = GOOGLE_SEARCH + searchfor
460 html = @bot.httputil.get(url)
462 m.reply "Error googletiming #{where}"
467 results = html.scan(GOOGLE_TIME_RESULT)
468 debug "results: #{results.inspect}"
470 if results.length != 1
471 m.reply "Couldn't find the time for #{where} on Google"
475 time = results[0][0].ircify_html
480 plugin = SearchPlugin.new
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