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 = "https://www.google.com/search?hl=en&oe=UTF-8&ie=UTF-8&gbv=1&q="
19 GOOGLE_WAP_SEARCH = "https://www.google.com/m/search?hl=en&ie=UTF-8&gbv=1&q="
20 GOOGLE_WAP_LINK = /<a\s+href="\/url\?(q=[^"]+)"[^>]*>\s*<div[^>]*>(.*?)\s*<\/div>/im
21 GOOGLE_CALC_RESULT = />Calculator<\/span>(?:<\/?[^>]+>\s*)+([^<]+)/
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}"
94 xml = REXML::Document.new feed
95 heading = xml.elements['//Heading/text()'].to_s
96 # answer is returned for calculations
97 answer = xml.elements['//Answer/text()'].to_s
98 # abstract is returned for definitions etc
99 abstract = xml.elements['//AbstractText/text()'].to_s
101 unless abstract.empty?
102 absrc = xml.elements['//AbstractSource/text()'].to_s
103 aburl = xml.elements['//AbstractURL/text()'].to_s
104 unless absrc.empty? and aburl.empty?
106 abfrom << " " << absrc unless absrc.empty?
107 abfrom << " " << aburl unless aburl.empty?
111 # but also definition (yes, you can have both, see e.g. printf)
112 definition = xml.elements['//Definition/text()'].to_s
114 unless definition.empty?
115 defsrc = xml.elements['//Definition/@source/text()'].to_s
116 defurl = xml.elements['//Definition/@url/text()'].to_s
117 unless defsrc.empty? and defurl.empty?
119 deffrom << " " << defsrc unless defsrc.empty?
120 deffrom << " " << defurl unless defurl.empty?
124 if heading.empty? and answer.empty? and abstract.empty? and definition.empty?
129 # if we got a one-shot answer (e.g. a calculation, return it)
135 # otherwise, return the abstract, followed by as many hits as found
136 unless heading.empty? or abstract.empty?
137 m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
138 :bold => Bold, :heading => heading,
139 :abstract => abstract, :abfrom => abfrom
142 unless heading.empty? or definition.empty?
143 m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
144 :bold => Bold, :heading => heading,
145 :abstract => definition, :abfrom => deffrom
148 # return zeroclick search results
149 links, texts = [], []
150 xml.elements.each("//Results/Result/FirstURL") { |element|
151 links << element.text
152 break if links.size == hits
154 return if links.empty?
156 xml.elements.each("//Results/Result/Text") { |element|
157 texts << " #{element.text}"
158 break if links.size == hits
160 # TODO see treatment of `single` in google search
162 single ||= (links.length == 1)
164 links.each_with_index do |u, i|
166 pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
167 :n => (single ? "" : "#{i}. "),
168 :sep => (single ? " -- " : ": "),
169 :b => Bold, :t => t, :u => u
173 result_string = pretty.join(" | ")
175 # If we return a single, full result, change the output to a more compact representation
177 fp = first_pars > 0 ? " -- #{Utils.get_first_pars(links, first_pars)}" : ""
178 m.reply("Result for %{what}: %{string}%{fp}" % {
179 :what => what, :string => result_string, :fp => fp
180 }, :overlong => :truncate)
184 m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
186 return unless first_pars > 0
188 Utils.get_first_pars urls, first_pars, :message => m
191 def google(m, params)
192 what = params[:words].to_s
193 if what.match(/^define:/)
194 return google_define(m, what, params)
197 searchfor = CGI.escape what
198 # This method is also called by other methods to restrict searching to some sites
200 site = "site:#{params[:site]}+"
204 # It is also possible to choose a filter to remove constant parts from the titles
205 # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
206 filter = params[:filter] || ""
208 url = GOOGLE_WAP_SEARCH + site + searchfor
210 hits = params[:hits] || @bot.config['google.hits']
211 hits = 1 if params[:lucky]
213 first_pars = params[:firstpar] || @bot.config['google.first_par']
215 single = params[:lucky] || (hits == 1 and first_pars == 1)
218 wml = @bot.httputil.get(url)
221 m.reply "error googling for #{what}"
224 results = wml.scan(GOOGLE_WAP_LINK)
226 if results.length == 0
227 m.reply "no results found for #{what}"
231 results = results.map {|result|
232 url = CGI::parse(Utils.decode_html_entities(result[0]))['q'].first
233 title = Utils.decode_html_entities(result[1].gsub(/<\/?[^>]+>/, ''))
234 [url, title] unless url.empty? or title.empty?
235 }.reject {|item| not item}[0..hits]
237 result_string = results.map {|url, title| "#{Bold}#{title}#{NormalText}: #{url}"}
240 m.reply result_string.first
241 Utils.get_first_pars([results.map {|url, title| url}.first], first_pars, :message => m)
245 m.reply "Results for #{what}: #{result_string.join(' | ')}", :split_at => /\s+\|\s+/
247 return unless first_pars > 0
249 Utils.get_first_pars(results.map {|url, title| url}, first_pars, :message => m)
252 def google_define(m, what, params)
254 wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
257 m.reply "error googling for #{what}"
262 related_index = wml.index(/Related phrases:/, 0)
263 raise unless related_index
264 defs_index = wml.index(/Definitions of <b>/, related_index)
265 raise unless defs_index
266 defs_end = wml.index(/<input/, defs_index)
267 raise unless defs_end
269 m.reply "no results found for #{what}"
273 related = wml[related_index...defs_index]
274 defs = wml[defs_index...defs_end]
276 m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
281 params.merge!(:lucky => true)
286 what = params[:words].to_s
287 searchfor = CGI.escape(what)
289 debug "Getting gcalc thing: #{searchfor.inspect}"
290 url = GOOGLE_WAP_SEARCH + searchfor
293 html = @bot.httputil.get(url)
295 m.reply "error googlecalcing #{what}"
299 debug "#{html.size} bytes of html recieved"
302 candidates = html.match(GOOGLE_CALC_RESULT)
303 debug "candidates: #{candidates.inspect}"
306 m.reply "couldn't calculate #{what}"
309 result = candidates[1].remove_nonascii
311 debug "replying with: #{result.inspect}"
312 m.reply result.ircify_html
315 def gcount(m, params)
316 what = params[:words].to_s
317 searchfor = CGI.escape(what)
319 debug "Getting gcount thing: #{searchfor.inspect}"
320 url = GOOGLE_SEARCH + searchfor
323 html = @bot.httputil.get(url)
325 m.reply "error googlecounting #{what}"
329 debug "#{html.size} bytes of html recieved"
331 results = html.scan(GOOGLE_COUNT_RESULT)
332 debug "results: #{results.inspect}"
334 if results.length != 1
335 m.reply "couldn't count #{what}"
339 result = results[0][0].ircify_html
340 debug "replying with: #{result.inspect}"
341 m.reply "total results: #{result}"
346 what = params[:words].to_s
347 searchfor = CGI.escape("define " + what)
349 debug "Getting gdef thing: #{searchfor.inspect}"
350 url = GOOGLE_WAP_SEARCH + searchfor
353 html = @bot.httputil.get(url)
355 m.reply "error googledefining #{what}"
360 results = html.scan(GOOGLE_DEF_RESULT)
361 debug "results: #{results.inspect}"
363 if results.length != 1
364 m.reply "couldn't find a definition for #{what} on Google"
368 head = results[0][0].ircify_html
369 text = results[0][1].ircify_html
370 m.reply "#{head} -- #{text}"
373 def wolfram(m, params)
374 what = params[:words].to_s
375 terms = CGI.escape what
376 url = WOLFRAM_API_SEARCH % {
377 :terms => terms, :key => WOLFRAM_API_KEY
381 feed = @bot.httputil.get(url)
384 m.reply "error asking WolframAlfa about #{what}"
389 xml = REXML::Document.new feed
390 if xml.elements['/queryresult'].attributes['error'] == "true"
391 m.reply xml.elements['/queryresult/error/text()'].to_s
394 unless xml.elements['/queryresult'].attributes['success'] == "true"
395 m.reply "no data available"
398 answer_type, answer = [], []
399 xml.elements.each("//pod") { |element|
400 answer_type << element.attributes['title']
401 answer << element.elements['subpod/plaintext'].text
403 # find the first answer that isn't nil,
404 # starting on the second pod in the array
406 answer[1..-1].each { |a|
414 # strip spaces, pipes, and line breaks
415 sep = Bold + ' :: ' + Bold
416 chars = [ [/\n/, sep], [/\t/, " "], [/\s+/, " "], ["|", "-"] ]
417 chars.each { |c| answer[n].gsub!(c[0], c[1]) }
418 m.reply answer_type[n] + sep + answer[n]
421 def wikipedia(m, params)
423 site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
424 debug "Looking up things on #{site}"
426 params[:filter] = / - Wikipedia.*$/
427 params[:hits] = @bot.config['wikipedia.hits']
428 params[:firstpar] = @bot.config['wikipedia.first_par']
429 return google(m, params)
432 def unpedia(m, params)
433 site = "uncyclopedia.org"
434 debug "Looking up things on #{site}"
436 params[:filter] = / - Uncyclopedia.*$/
437 params[:hits] = @bot.config['wikipedia.hits']
438 params[:firstpar] = @bot.config['wikipedia.first_par']
439 return google(m, params)
443 where = params[:words].to_s
444 where.sub!(/^\s*in\s*/, '')
445 searchfor = CGI.escape("time in " + where)
446 url = GOOGLE_SEARCH + searchfor
449 html = @bot.httputil.get(url)
451 m.reply "Error googletiming #{where}"
456 results = html.scan(GOOGLE_TIME_RESULT)
457 debug "results: #{results.inspect}"
459 if results.length != 1
460 m.reply "Couldn't find the time for #{where} on Google"
464 time = results[0][0].ircify_html
469 plugin = SearchPlugin.new
471 plugin.map "ddg *words", :action => 'duckduckgo', :threaded => true
472 plugin.map "search *words", :action => 'google', :threaded => true
473 plugin.map "google *words", :action => 'google', :threaded => true
474 plugin.map "lucky *words", :action => 'lucky', :threaded => true
477 plugin.map "gcount *words", :action => 'gcount', :threaded => true
479 plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
480 plugin.map "gdef *words", :action => 'gdef', :threaded => true
481 plugin.map "gtime *words", :action => 'gtime', :threaded => true
482 plugin.map "wa *words", :action => 'wolfram', :threaded => true
483 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
484 plugin.map "wp *words", :action => 'wikipedia', :threaded => true
485 plugin.map "unpedia *words", :action => 'unpedia', :threaded => true