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="
27 WOLFRAM_API_KEY = "4EU37Y-TX9WJG3JH3"
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',
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',
38 :desc => "Number of hits to return from Google searches")
39 Config.register Config::IntegerValue.new('google.first_par',
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',
44 :desc => "Number of hits to return from Wikipedia searches")
45 Config.register Config::IntegerValue.new('wikipedia.first_par',
47 :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
49 def help(plugin, topic="")
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>"
57 "gcalc <equation> => use the google calculator to find the answer to <equation>"
59 "gdef <term(s)> => use the google define mechanism to find a definition of <term(s)>"
61 "gtime <location> => use the google clock to find the current time at <location>"
63 "wa <string> => searches WolframAlpha for <string>"
65 "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
67 "unpedia <string> => search for <string> on Uncyclopedia"
69 "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"
73 def duckduckgo(m, params)
74 what = params[:words].to_s
75 terms = CGI.escape what
76 url = DDG_API_SEARCH + terms
78 hits = @bot.config['duckduckgo.hits']
79 first_pars = params[:firstpar] || @bot.config['duckduckgo.first_par']
80 single = params[:lucky] || (hits == 1 and first_pars == 1)
83 feed = @bot.httputil.get(url)
86 m.reply "error duckduckgoing for #{what}"
91 xml = REXML::Document.new feed
92 heading = xml.elements['//Heading/text()'].to_s
93 # answer is returned for calculations
94 answer = xml.elements['//Answer/text()'].to_s
95 # abstract is returned for definitions etc
96 abstract = xml.elements['//AbstractText/text()'].to_s
97 unless abstract.empty?
98 absrc = xml.elements['//AbstractSource/text()']
99 aburl = xml.elements['//AbstractURL/text()']
101 # but also definition (yes, you can have both, see e.g. printf)
102 definition = xml.elements['//Definition/text()'].to_s
103 unless definition.empty?
104 defsrc = xml.elements['//Definition/@source/text()'].to_s
105 defurl = xml.elements['//Definition/@url/text()'].to_s
108 if heading.empty? and answer.empty? and abstract.empty? and definition.empty?
113 # if we got a one-shot answer (e.g. a calculation, return it)
119 # otherwise, return the abstract, followed by as many hits as found
120 unless heading.empty? or abstract.empty?
121 m.reply "%{bold}%{heading}:%{bold} %{abstract} -- %{absrc} %{aburl}" % {
122 :bold => Bold, :heading => heading,
123 :abstract => abstract, :absrc => absrc, :aburl => aburl
126 unless heading.empty? or definition.empty?
127 m.reply "%{bold}%{heading}:%{bold} %{abstract} -- %{absrc} %{aburl}" % {
128 :bold => Bold, :heading => heading,
129 :abstract => definition, :absrc => defsrc, :aburl => defurl
132 # return zeroclick search results
133 links, texts = [], []
134 xml.elements.each("//Results/Result/FirstURL") { |element|
135 links << element.text
136 break if links.size == hits
138 return if links.empty?
140 xml.elements.each("//Results/Result/Text") { |element|
141 texts << " #{element.text}"
142 break if links.size == hits
144 # TODO see treatment of `single` in google search
146 single ||= (links.length == 1)
148 links.each_with_index do |u, i|
150 pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
151 :n => (single ? "" : "#{i}. "),
152 :sep => (single ? " -- " : ": "),
153 :b => Bold, :t => t, :u => u
157 result_string = pretty.join(" | ")
159 # If we return a single, full result, change the output to a more compact representation
161 fp = first_pars > 0 ? " -- #{Utils.get_first_pars(links, first_pars)}" : ""
162 m.reply("Result for %{what}: %{string}%{fp}" % {
163 :what => what, :string => result_string, :fp => fp
164 }, :overlong => :truncate)
168 m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
170 return unless first_pars > 0
172 Utils.get_first_pars urls, first_pars, :message => m
175 def google(m, params)
176 what = params[:words].to_s
177 if what.match(/^define:/)
178 return google_define(m, what, params)
181 searchfor = CGI.escape what
182 # This method is also called by other methods to restrict searching to some sites
184 site = "site:#{params[:site]}+"
188 # It is also possible to choose a filter to remove constant parts from the titles
189 # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
190 filter = params[:filter] || ""
192 url = GOOGLE_WAP_SEARCH + site + searchfor
194 hits = params[:hits] || @bot.config['google.hits']
195 hits = 1 if params[:lucky]
197 first_pars = params[:firstpar] || @bot.config['google.first_par']
199 single = params[:lucky] || (hits == 1 and first_pars == 1)
202 wml = @bot.httputil.get(url)
205 m.reply "error googling for #{what}"
208 results = wml.scan(GOOGLE_WAP_LINK)
210 if results.length == 0
211 m.reply "no results found for #{what}"
215 single ||= (results.length==1)
222 results.each do |res|
223 t = res[1].ircify_html(:img => "[%{src} %{alt} %{dimensions}]").strip
225 if u.sub!(%r{^http://www.google.com/aclk\?},'')
226 u = CGI::parse(u)['adurl'].first
227 debug "skipping ad for #{u}"
229 elsif u.sub!(%r{^http://www.google.com/gwt/x\?},'')
230 u = CGI::parse(u)['u'].first
231 elsif u.sub!(%r{^/url\?},'')
232 u = CGI::parse(u)['q'].first
235 pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
236 :n => (single ? "" : "#{urls.length}. "),
237 :sep => (single ? " -- " : ": "),
238 :b => Bold, :t => t, :u => u
240 break if urls.length == hits
243 m.reply "failed to understand what google found for #{what}"
255 result_string = pretty.join(" | ")
257 # If we return a single, full result, change the output to a more compact representation
259 m.reply "Result for %s: %s -- %s" % [what, result_string, Utils.get_first_pars(urls, first_pars)], :overlong => :truncate
263 m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
265 return unless first_pars > 0
267 Utils.get_first_pars urls, first_pars, :message => m
271 def google_define(m, what, params)
273 wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
276 m.reply "error googling for #{what}"
281 related_index = wml.index(/Related phrases:/, 0)
282 raise unless related_index
283 defs_index = wml.index(/Definitions of <b>/, related_index)
284 raise unless defs_index
285 defs_end = wml.index(/<input/, defs_index)
286 raise unless defs_end
288 m.reply "no results found for #{what}"
292 related = wml[related_index...defs_index]
293 defs = wml[defs_index...defs_end]
295 m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
300 params.merge!(:lucky => true)
305 what = params[:words].to_s
306 searchfor = CGI.escape(what)
308 debug "Getting gcalc thing: #{searchfor.inspect}"
309 url = GOOGLE_WAP_SEARCH + searchfor
312 html = @bot.httputil.get(url)
314 m.reply "error googlecalcing #{what}"
318 debug "#{html.size} bytes of html recieved"
321 candidates = html.match(GOOGLE_CALC_RESULT)
322 debug "candidates: #{candidates.inspect}"
325 m.reply "couldn't calculate #{what}"
328 result = candidates[1]
330 debug "replying with: #{result.inspect}"
331 m.reply result.ircify_html
334 def gcount(m, params)
335 what = params[:words].to_s
336 searchfor = CGI.escape(what)
338 debug "Getting gcount thing: #{searchfor.inspect}"
339 url = GOOGLE_SEARCH + searchfor
342 html = @bot.httputil.get(url)
344 m.reply "error googlecounting #{what}"
348 debug "#{html.size} bytes of html recieved"
350 results = html.scan(GOOGLE_COUNT_RESULT)
351 debug "results: #{results.inspect}"
353 if results.length != 1
354 m.reply "couldn't count #{what}"
358 result = results[0][0].ircify_html
359 debug "replying with: #{result.inspect}"
360 m.reply "total results: #{result}"
365 what = params[:words].to_s
366 searchfor = CGI.escape("define " + what)
368 debug "Getting gdef thing: #{searchfor.inspect}"
369 url = GOOGLE_WAP_SEARCH + searchfor
372 html = @bot.httputil.get(url)
374 m.reply "error googledefining #{what}"
379 results = html.scan(GOOGLE_DEF_RESULT)
380 debug "results: #{results.inspect}"
382 if results.length != 1
383 m.reply "couldn't find a definition for #{what} on Google"
387 head = results[0][0].ircify_html
388 text = results[0][1].ircify_html
389 m.reply "#{head} -- #{text}"
392 def wolfram(m, params)
393 terms = CGI.escape(params[:words].to_s)
394 feed = Net::HTTP.get 'api.wolframalpha.com',
395 "/v2/query?input=#{terms}&appid=#{WOLFRAM_API_KEY}&format=plaintext"
396 "&scantimeout=3.0&podtimeout=4.0&formattimeout=8.0&parsetimeout=5.0"
397 "&excludepodid=SeriesRepresentations:*"
398 if feed.nil? or feed.empty?
399 m.reply "error connecting"
402 xml = REXML::Document.new feed
403 if xml.elements['/queryresult'].attributes['error'] == "true"
404 m.reply xml.elements['/queryresult/error/text()'].to_s
407 unless xml.elements['/queryresult'].attributes['success'] == "true"
408 m.reply "no data available"
412 xml.elements.each("//pod/subpod/plaintext") { |element|
413 answer << element.text
415 # strip spaces and line breaks
416 answer[1].gsub!(/\n/, Bold + ' :: ' + Bold )
417 answer[1].gsub!(/\t/, ' ')
418 answer[1].gsub!(/\s+/, ' ')
419 m.reply answer[1].to_s
422 def wikipedia(m, params)
424 site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
425 debug "Looking up things on #{site}"
427 params[:filter] = / - Wikipedia.*$/
428 params[:hits] = @bot.config['wikipedia.hits']
429 params[:firstpar] = @bot.config['wikipedia.first_par']
430 return google(m, params)
433 def unpedia(m, params)
434 site = "uncyclopedia.org"
435 debug "Looking up things on #{site}"
437 params[:filter] = / - Uncyclopedia.*$/
438 params[:hits] = @bot.config['wikipedia.hits']
439 params[:firstpar] = @bot.config['wikipedia.first_par']
440 return google(m, params)
444 where = params[:words].to_s
445 where.sub!(/^\s*in\s*/, '')
446 searchfor = CGI.escape("time in " + where)
447 url = GOOGLE_SEARCH + searchfor
450 html = @bot.httputil.get(url)
452 m.reply "Error googletiming #{where}"
457 results = html.scan(GOOGLE_TIME_RESULT)
458 debug "results: #{results.inspect}"
460 if results.length != 1
461 m.reply "Couldn't find the time for #{where} on Google"
465 time = results[0][0].ircify_html
470 plugin = SearchPlugin.new
472 plugin.map "ddg *words", :action => 'duckduckgo'
473 plugin.map "search *words", :action => 'google', :threaded => true
474 plugin.map "google *words", :action => 'google', :threaded => true
475 plugin.map "lucky *words", :action => 'lucky', :threaded => true
476 plugin.map "gcount *words", :action => 'gcount', :threaded => true
477 plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
478 plugin.map "gdef *words", :action => 'gdef', :threaded => true
479 plugin.map "gtime *words", :action => 'gtime', :threaded => true
480 plugin.map "wa *words", :action => 'wolfram'
481 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
482 plugin.map "wp *words", :action => 'wikipedia', :threaded => true
483 plugin.map "unpedia *words", :action => 'unpedia', :threaded => true