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 class SearchPlugin < Plugin
29 Config.register Config::IntegerValue.new('duckduckgo.hits',
30 :default => 3, :validate => Proc.new{|v| v > 0},
31 :desc => "Number of hits to return from searches")
32 Config.register Config::IntegerValue.new('duckduckgo.first_par',
34 :desc => "When set to n > 0, the bot will return the first paragraph from the first n search hits")
35 Config.register Config::IntegerValue.new('google.hits',
37 :desc => "Number of hits to return from Google searches")
38 Config.register Config::IntegerValue.new('google.first_par',
40 :desc => "When set to n > 0, the bot will return the first paragraph from the first n search hits")
41 Config.register Config::IntegerValue.new('wikipedia.hits',
43 :desc => "Number of hits to return from Wikipedia searches")
44 Config.register Config::IntegerValue.new('wikipedia.first_par',
46 :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
48 def help(plugin, topic="")
51 "Use '#{topic} <string>' to return a search or calculation from " +
52 "DuckDuckGo. Use #{topic} define <string> to return a definition."
53 when "search", "google"
54 "#{topic} <string> => search google for <string>"
56 "gcalc <equation> => use the google calculator to find the answer to <equation>"
58 "gdef <term(s)> => use the google define mechanism to find a definition of <term(s)>"
60 "gtime <location> => use the google clock to find the current time at <location>"
62 "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
64 "unpedia <string> => search for <string> on Uncyclopedia"
66 "search <string> (or: google <string>) => search google for <string> | ddg <string> to search DuckDuckGo | wp <string> => search for <string> on Wikipedia | unpedia <string> => search for <string> on Uncyclopedia"
70 def duckduckgo(m, params)
71 what = params[:words].to_s
72 terms = CGI.escape what
73 url = DDG_API_SEARCH + terms
75 hits = @bot.config['duckduckgo.hits']
76 first_pars = params[:firstpar] || @bot.config['duckduckgo.first_par']
77 single = params[:lucky] || (hits == 1 and first_pars == 1)
80 feed = @bot.httputil.get(url)
83 m.reply "error duckduckgoing for #{what}"
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 unless abstract.empty?
95 absrc = xml.elements['//AbstractSource/text()']
96 aburl = xml.elements['//AbstractURL/text()']
98 # but also definition (yes, you can have both, see e.g. printf)
99 definition = xml.elements['//Definition/text()'].to_s
100 unless definition.empty?
101 defsrc = xml.elements['//Definition/@source/text()'].to_s
102 defurl = xml.elements['//Definition/@url/text()'].to_s
105 if heading.empty? and answer.empty? and abstract.empty? and definition.empty?
110 # if we got a one-shot answer (e.g. a calculation, return it)
116 # otherwise, return the abstract, followed by as many hits as found
117 unless heading.empty? or abstract.empty?
118 m.reply "%{bold}%{heading}:%{bold} %{abstract} -- %{absrc} %{aburl}" % {
119 :bold => Bold, :heading => heading,
120 :abstract => abstract, :absrc => absrc, :aburl => aburl
123 unless heading.empty? or definition.empty?
124 m.reply "%{bold}%{heading}:%{bold} %{abstract} -- %{absrc} %{aburl}" % {
125 :bold => Bold, :heading => heading,
126 :abstract => definition, :absrc => defsrc, :aburl => defurl
129 # return zeroclick search results
130 links, texts = [], []
131 xml.elements.each("//Results/Result/FirstURL") { |element|
132 links << element.text
133 break if links.size == hits
135 return if links.empty?
137 xml.elements.each("//Results/Result/Text") { |element|
138 texts << " #{element.text}"
139 break if links.size == hits
141 # TODO see treatment of `single` in google search
143 single ||= (links.length == 1)
145 links.each_with_index do |u, i|
147 pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
148 :n => (single ? "" : "#{i}. "),
149 :sep => (single ? " -- " : ": "),
150 :b => Bold, :t => t, :u => u
154 result_string = pretty.join(" | ")
156 # If we return a single, full result, change the output to a more compact representation
158 fp = first_pars > 0 ? " -- #{Utils.get_first_pars(links, first_pars)}" : ""
159 m.reply("Result for %{what}: %{string}%{fp}" % {
160 :what => what, :string => result_string, :fp => fp
161 }, :overlong => :truncate)
165 m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
167 return unless first_pars > 0
169 Utils.get_first_pars urls, first_pars, :message => m
172 def google(m, params)
173 what = params[:words].to_s
174 if what.match(/^define:/)
175 return google_define(m, what, params)
178 searchfor = CGI.escape what
179 # This method is also called by other methods to restrict searching to some sites
181 site = "site:#{params[:site]}+"
185 # It is also possible to choose a filter to remove constant parts from the titles
186 # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
187 filter = params[:filter] || ""
189 url = GOOGLE_WAP_SEARCH + site + searchfor
191 hits = params[:hits] || @bot.config['google.hits']
192 hits = 1 if params[:lucky]
194 first_pars = params[:firstpar] || @bot.config['google.first_par']
196 single = params[:lucky] || (hits == 1 and first_pars == 1)
199 wml = @bot.httputil.get(url)
202 m.reply "error googling for #{what}"
205 results = wml.scan(GOOGLE_WAP_LINK)
207 if results.length == 0
208 m.reply "no results found for #{what}"
212 single ||= (results.length==1)
219 results.each do |res|
220 t = res[1].ircify_html(:img => "[%{src} %{alt} %{dimensions}]").strip
222 if u.sub!(%r{^http://www.google.com/aclk\?},'')
223 u = CGI::parse(u)['adurl'].first
224 debug "skipping ad for #{u}"
226 elsif u.sub!(%r{^http://www.google.com/gwt/x\?},'')
227 u = CGI::parse(u)['u'].first
228 elsif u.sub!(%r{^/url\?},'')
229 u = CGI::parse(u)['q'].first
232 pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
233 :n => (single ? "" : "#{urls.length}. "),
234 :sep => (single ? " -- " : ": "),
235 :b => Bold, :t => t, :u => u
237 break if urls.length == hits
240 m.reply "failed to understand what google found for #{what}"
252 result_string = pretty.join(" | ")
254 # If we return a single, full result, change the output to a more compact representation
256 m.reply "Result for %s: %s -- %s" % [what, result_string, Utils.get_first_pars(urls, first_pars)], :overlong => :truncate
260 m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
262 return unless first_pars > 0
264 Utils.get_first_pars urls, first_pars, :message => m
268 def google_define(m, what, params)
270 wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
273 m.reply "error googling for #{what}"
278 related_index = wml.index(/Related phrases:/, 0)
279 raise unless related_index
280 defs_index = wml.index(/Definitions of <b>/, related_index)
281 raise unless defs_index
282 defs_end = wml.index(/<input/, defs_index)
283 raise unless defs_end
285 m.reply "no results found for #{what}"
289 related = wml[related_index...defs_index]
290 defs = wml[defs_index...defs_end]
292 m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
297 params.merge!(:lucky => true)
302 what = params[:words].to_s
303 searchfor = CGI.escape(what)
305 debug "Getting gcalc thing: #{searchfor.inspect}"
306 url = GOOGLE_WAP_SEARCH + searchfor
309 html = @bot.httputil.get(url)
311 m.reply "error googlecalcing #{what}"
315 debug "#{html.size} bytes of html recieved"
318 candidates = html.match(GOOGLE_CALC_RESULT)
319 debug "candidates: #{candidates.inspect}"
322 m.reply "couldn't calculate #{what}"
325 result = candidates[1]
327 debug "replying with: #{result.inspect}"
328 m.reply result.ircify_html
331 def gcount(m, params)
332 what = params[:words].to_s
333 searchfor = CGI.escape(what)
335 debug "Getting gcount thing: #{searchfor.inspect}"
336 url = GOOGLE_SEARCH + searchfor
339 html = @bot.httputil.get(url)
341 m.reply "error googlecounting #{what}"
345 debug "#{html.size} bytes of html recieved"
347 results = html.scan(GOOGLE_COUNT_RESULT)
348 debug "results: #{results.inspect}"
350 if results.length != 1
351 m.reply "couldn't count #{what}"
355 result = results[0][0].ircify_html
356 debug "replying with: #{result.inspect}"
357 m.reply "total results: #{result}"
362 what = params[:words].to_s
363 searchfor = CGI.escape("define " + what)
365 debug "Getting gdef thing: #{searchfor.inspect}"
366 url = GOOGLE_WAP_SEARCH + searchfor
369 html = @bot.httputil.get(url)
371 m.reply "error googledefining #{what}"
376 results = html.scan(GOOGLE_DEF_RESULT)
377 debug "results: #{results.inspect}"
379 if results.length != 1
380 m.reply "couldn't find a definition for #{what} on Google"
384 head = results[0][0].ircify_html
385 text = results[0][1].ircify_html
386 m.reply "#{head} -- #{text}"
389 def wikipedia(m, params)
391 site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
392 debug "Looking up things on #{site}"
394 params[:filter] = / - Wikipedia.*$/
395 params[:hits] = @bot.config['wikipedia.hits']
396 params[:firstpar] = @bot.config['wikipedia.first_par']
397 return google(m, params)
400 def unpedia(m, params)
401 site = "uncyclopedia.org"
402 debug "Looking up things on #{site}"
404 params[:filter] = / - Uncyclopedia.*$/
405 params[:hits] = @bot.config['wikipedia.hits']
406 params[:firstpar] = @bot.config['wikipedia.first_par']
407 return google(m, params)
411 where = params[:words].to_s
412 where.sub!(/^\s*in\s*/, '')
413 searchfor = CGI.escape("time in " + where)
414 url = GOOGLE_SEARCH + searchfor
417 html = @bot.httputil.get(url)
419 m.reply "Error googletiming #{where}"
424 results = html.scan(GOOGLE_TIME_RESULT)
425 debug "results: #{results.inspect}"
427 if results.length != 1
428 m.reply "Couldn't find the time for #{where} on Google"
432 time = results[0][0].ircify_html
437 plugin = SearchPlugin.new
439 plugin.map "ddg *words", :action => 'duckduckgo'
440 plugin.map "search *words", :action => 'google', :threaded => true
441 plugin.map "google *words", :action => 'google', :threaded => true
442 plugin.map "lucky *words", :action => 'lucky', :threaded => true
443 plugin.map "gcount *words", :action => 'gcount', :threaded => true
444 plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
445 plugin.map "gdef *words", :action => 'gdef', :threaded => true
446 plugin.map "gtime *words", :action => 'gtime', :threaded => true
447 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
448 plugin.map "wp *words", :action => 'wikipedia', :threaded => true
449 plugin.map "unpedia *words", :action => 'unpedia', :threaded => true