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 class SearchPlugin < Plugin
27 Config.register Config::IntegerValue.new('duckduckgo.hits',
28 :default => 3, :validate => Proc.new{|v| v > 0},
29 :desc => "Number of hits to return from searches")
30 Config.register Config::IntegerValue.new('google.hits',
32 :desc => "Number of hits to return from Google searches")
33 Config.register Config::IntegerValue.new('google.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('wikipedia.hits',
38 :desc => "Number of hits to return from Wikipedia searches")
39 Config.register Config::IntegerValue.new('wikipedia.first_par',
41 :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
43 def help(plugin, topic="")
46 "Use '#{topic} <string>' to return a search or calculation from " +
47 "DuckDuckGo. Use #{topic} define <string> to return a definition."
48 when "search", "google"
49 "#{topic} <string> => search google for <string>"
51 "gcalc <equation> => use the google calculator to find the answer to <equation>"
53 "gdef <term(s)> => use the google define mechanism to find a definition of <term(s)>"
55 "gtime <location> => use the google clock to find the current time at <location>"
57 "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
59 "unpedia <string> => search for <string> on Uncyclopedia"
61 "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"
65 def duckduckgo(m, params)
66 terms = params[:words].to_s
67 # DuckDuckGo is picky about white spaces
68 # in the url, so we can't use CGI.escape.
69 terms.gsub!(/\%/, '%25') if terms.include? "%"
70 terms.gsub!(/\+|\s\+\s|\s\+|\+\s/, ' %2B ') if terms.include? "+"
71 terms.gsub!(/\-|\s\-\s|\s\-|\-\s/, ' %2D ') if terms.include? "-"
72 terms.gsub!(/\!/, '%21') if terms.include? "!"
73 terms.gsub!(/\%/, ' %') if terms.include? "%"
74 feed = Net::HTTP.get 'api.duckduckgo.com',
75 "/?q=#{terms}&format=xml&skip_disambig=1&no_html=1&no_redirect=0"
76 if feed.nil? or feed.empty?
77 m.reply "error connecting"
80 xml = REXML::Document.new feed
81 heading = xml.elements['//Heading/text()'].to_s
82 # answer is returned for calculations
83 answer = xml.elements['//Answer/text()'].to_s
84 if heading.empty? and answer.empty?
90 m.reply "no definition found"
93 # Format and return a different string if it is a definition search.
94 definition = xml.elements['//AbstractText/text()'].to_s
95 source = " -- #{xml.elements['//AbstractURL/text()']}"
96 m.reply Bold + heading + ": " + Bold + definition + source
98 # return a calculation
101 # else, return a zeroclick search
103 hits = @bot.config['duckduckgo.hits']
104 xml.elements.each("//RelatedTopics/RelatedTopic/FirstURL") { |element|
105 links << element.text
107 xml.elements.each("//RelatedTopics/RelatedTopic/Text") { |element|
108 text << " #{element.text}"
111 m.reply Bold + heading + ": " + Bold
113 m.reply links[num] + text[num]
119 def google(m, params)
120 what = params[:words].to_s
121 if what.match(/^define:/)
122 return google_define(m, what, params)
125 searchfor = CGI.escape what
126 # This method is also called by other methods to restrict searching to some sites
128 site = "site:#{params[:site]}+"
132 # It is also possible to choose a filter to remove constant parts from the titles
133 # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
134 filter = params[:filter] || ""
136 url = GOOGLE_WAP_SEARCH + site + searchfor
138 hits = params[:hits] || @bot.config['google.hits']
139 hits = 1 if params[:lucky]
141 first_pars = params[:firstpar] || @bot.config['google.first_par']
143 single = params[:lucky] || (hits == 1 and first_pars == 1)
146 wml = @bot.httputil.get(url)
149 m.reply "error googling for #{what}"
152 results = wml.scan(GOOGLE_WAP_LINK)
154 if results.length == 0
155 m.reply "no results found for #{what}"
159 single ||= (results.length==1)
166 results.each do |res|
167 t = res[1].ircify_html(:img => "[%{src} %{alt} %{dimensions}]").strip
169 if u.sub!(%r{^http://www.google.com/aclk\?},'')
170 u = CGI::parse(u)['adurl'].first
171 debug "skipping ad for #{u}"
173 elsif u.sub!(%r{^http://www.google.com/gwt/x\?},'')
174 u = CGI::parse(u)['u'].first
175 elsif u.sub!(%r{^/url\?},'')
176 u = CGI::parse(u)['q'].first
179 pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
180 :n => (single ? "" : "#{urls.length}. "),
181 :sep => (single ? " -- " : ": "),
182 :b => Bold, :t => t, :u => u
184 break if urls.length == hits
187 m.reply "failed to understand what google found for #{what}"
199 result_string = pretty.join(" | ")
201 # If we return a single, full result, change the output to a more compact representation
203 m.reply "Result for %s: %s -- %s" % [what, result_string, Utils.get_first_pars(urls, first_pars)], :overlong => :truncate
207 m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
209 return unless first_pars > 0
211 Utils.get_first_pars urls, first_pars, :message => m
215 def google_define(m, what, params)
217 wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
220 m.reply "error googling for #{what}"
225 related_index = wml.index(/Related phrases:/, 0)
226 raise unless related_index
227 defs_index = wml.index(/Definitions of <b>/, related_index)
228 raise unless defs_index
229 defs_end = wml.index(/<input/, defs_index)
230 raise unless defs_end
232 m.reply "no results found for #{what}"
236 related = wml[related_index...defs_index]
237 defs = wml[defs_index...defs_end]
239 m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
244 params.merge!(:lucky => true)
249 what = params[:words].to_s
250 searchfor = CGI.escape(what)
252 debug "Getting gcalc thing: #{searchfor.inspect}"
253 url = GOOGLE_WAP_SEARCH + searchfor
256 html = @bot.httputil.get(url)
258 m.reply "error googlecalcing #{what}"
262 debug "#{html.size} bytes of html recieved"
265 candidates = html.match(GOOGLE_CALC_RESULT)
266 debug "candidates: #{candidates.inspect}"
269 m.reply "couldn't calculate #{what}"
272 result = candidates[1]
274 debug "replying with: #{result.inspect}"
275 m.reply result.ircify_html
278 def gcount(m, params)
279 what = params[:words].to_s
280 searchfor = CGI.escape(what)
282 debug "Getting gcount thing: #{searchfor.inspect}"
283 url = GOOGLE_SEARCH + searchfor
286 html = @bot.httputil.get(url)
288 m.reply "error googlecounting #{what}"
292 debug "#{html.size} bytes of html recieved"
294 results = html.scan(GOOGLE_COUNT_RESULT)
295 debug "results: #{results.inspect}"
297 if results.length != 1
298 m.reply "couldn't count #{what}"
302 result = results[0][0].ircify_html
303 debug "replying with: #{result.inspect}"
304 m.reply "total results: #{result}"
309 what = params[:words].to_s
310 searchfor = CGI.escape("define " + what)
312 debug "Getting gdef thing: #{searchfor.inspect}"
313 url = GOOGLE_WAP_SEARCH + searchfor
316 html = @bot.httputil.get(url)
318 m.reply "error googledefining #{what}"
323 results = html.scan(GOOGLE_DEF_RESULT)
324 debug "results: #{results.inspect}"
326 if results.length != 1
327 m.reply "couldn't find a definition for #{what} on Google"
331 head = results[0][0].ircify_html
332 text = results[0][1].ircify_html
333 m.reply "#{head} -- #{text}"
336 def wikipedia(m, params)
338 site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
339 debug "Looking up things on #{site}"
341 params[:filter] = / - Wikipedia.*$/
342 params[:hits] = @bot.config['wikipedia.hits']
343 params[:firstpar] = @bot.config['wikipedia.first_par']
344 return google(m, params)
347 def unpedia(m, params)
348 site = "uncyclopedia.org"
349 debug "Looking up things on #{site}"
351 params[:filter] = / - Uncyclopedia.*$/
352 params[:hits] = @bot.config['wikipedia.hits']
353 params[:firstpar] = @bot.config['wikipedia.first_par']
354 return google(m, params)
358 where = params[:words].to_s
359 where.sub!(/^\s*in\s*/, '')
360 searchfor = CGI.escape("time in " + where)
361 url = GOOGLE_SEARCH + searchfor
364 html = @bot.httputil.get(url)
366 m.reply "Error googletiming #{where}"
371 results = html.scan(GOOGLE_TIME_RESULT)
372 debug "results: #{results.inspect}"
374 if results.length != 1
375 m.reply "Couldn't find the time for #{where} on Google"
379 time = results[0][0].ircify_html
384 plugin = SearchPlugin.new
386 plugin.map "ddg *words", :action => 'duckduckgo'
387 plugin.map "search *words", :action => 'google', :threaded => true
388 plugin.map "google *words", :action => 'google', :threaded => true
389 plugin.map "lucky *words", :action => 'lucky', :threaded => true
390 plugin.map "gcount *words", :action => 'gcount', :threaded => true
391 plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
392 plugin.map "gdef *words", :action => 'gdef', :threaded => true
393 plugin.map "gtime *words", :action => 'gtime', :threaded => true
394 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
395 plugin.map "wp *words", :action => 'wikipedia', :threaded => true
396 plugin.map "unpedia *words", :action => 'unpedia', :threaded => true