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_XPATH_DEF = "//img[@id='flex_text_audio_icon_chunk']/../../../../div[3]//text()"
23 DDG_API_SEARCH = "http://api.duckduckgo.com/?format=xml&no_html=1&skip_disambig=1&no_redirect=0&q="
24 WOLFRAM_API_SEARCH = "http://api.wolframalpha.com/v2/query?input=%{terms}&appid=%{key}&format=plaintext" +
25 "&scantimeout=3.0&podtimeout=4.0&formattimeout=8.0&parsetimeout=5.0" +
26 "&excludepodid=SeriesRepresentations:*"
27 WOLFRAM_API_KEY = "9RW6XR-QTL2JT7J4W"
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 "wa <string> => searches WolframAlpha for <string>"
63 "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
65 "unpedia <string> => search for <string> on Uncyclopedia"
67 "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"
71 def duckduckgo(m, params)
72 what = params[:words].to_s
73 terms = CGI.escape what
74 url = DDG_API_SEARCH + terms
76 hits = @bot.config['duckduckgo.hits']
77 first_pars = params[:firstpar] || @bot.config['duckduckgo.first_par']
78 single = params[:lucky] || (hits == 1 and first_pars == 1)
81 feed = @bot.httputil.get(url)
84 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
95 unless abstract.empty?
96 absrc = xml.elements['//AbstractSource/text()'].to_s
97 aburl = xml.elements['//AbstractURL/text()'].to_s
98 unless absrc.empty? and aburl.empty?
100 abfrom << " " << absrc unless absrc.empty?
101 abfrom << " " << aburl unless aburl.empty?
105 # but also definition (yes, you can have both, see e.g. printf)
106 definition = xml.elements['//Definition/text()'].to_s
108 unless definition.empty?
109 defsrc = xml.elements['//Definition/@source/text()'].to_s
110 defurl = xml.elements['//Definition/@url/text()'].to_s
111 unless defsrc.empty? and defurl.empty?
113 deffrom << " " << defsrc unless defsrc.empty?
114 deffrom << " " << defurl unless defurl.empty?
118 if heading.empty? and answer.empty? and abstract.empty? and definition.empty?
123 # if we got a one-shot answer (e.g. a calculation, return it)
129 # otherwise, return the abstract, followed by as many hits as found
130 unless heading.empty? or abstract.empty?
131 m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
132 :bold => Bold, :heading => heading,
133 :abstract => abstract, :abfrom => abfrom
136 unless heading.empty? or definition.empty?
137 m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
138 :bold => Bold, :heading => heading,
139 :abstract => definition, :abfrom => deffrom
142 # return zeroclick search results
143 links, texts = [], []
144 xml.elements.each("//Results/Result/FirstURL") { |element|
145 links << element.text
146 break if links.size == hits
148 return if links.empty?
150 xml.elements.each("//Results/Result/Text") { |element|
151 texts << " #{element.text}"
152 break if links.size == hits
154 # TODO see treatment of `single` in google search
156 single ||= (links.length == 1)
158 links.each_with_index do |u, i|
160 pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
161 :n => (single ? "" : "#{i}. "),
162 :sep => (single ? " -- " : ": "),
163 :b => Bold, :t => t, :u => u
167 result_string = pretty.join(" | ")
169 # If we return a single, full result, change the output to a more compact representation
171 fp = first_pars > 0 ? " -- #{Utils.get_first_pars(@bot, links, first_pars)}" : ""
172 m.reply("Result for %{what}: %{string}%{fp}" % {
173 :what => what, :string => result_string, :fp => fp
174 }, :overlong => :truncate)
178 m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
180 return unless first_pars > 0
182 Utils.get_first_pars(@bot, urls, first_pars, :message => m)
185 def google(m, params)
186 what = params[:words].to_s
187 if what.match(/^define:/)
188 return google_define(m, what, params)
191 searchfor = CGI.escape what
192 # This method is also called by other methods to restrict searching to some sites
194 site = "site:#{params[:site]}+"
198 # It is also possible to choose a filter to remove constant parts from the titles
199 # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
200 filter = params[:filter] || ""
202 url = GOOGLE_WAP_SEARCH + site + searchfor
204 hits = params[:hits] || @bot.config['google.hits']
205 hits = 1 if params[:lucky]
207 first_pars = params[:firstpar] || @bot.config['google.first_par']
209 single = params[:lucky] || (hits == 1 and first_pars == 1)
212 wml = @bot.httputil.get(url)
215 m.reply "error googling for #{what}"
218 results = wml.scan(GOOGLE_WAP_LINK)
220 if results.length == 0
221 m.reply "no results found for #{what}"
225 results = results.map {|result|
226 url = CGI::parse(Utils.decode_html_entities(result[0]))['q'].first
227 title = Utils.decode_html_entities(result[1].gsub(/<\/?[^>]+>/, ''))
228 [url, title] unless url.empty? or title.empty?
229 }.reject {|item| not item}[0..hits]
231 result_string = results.map {|url, title| "#{Bold}#{title}#{NormalText}: #{url}"}
234 m.reply result_string.first
235 Utils.get_first_pars(@bot, [results.map {|url, title| url}.first], first_pars, :message => m)
239 m.reply "Results for #{what}: #{result_string.join(' | ')}", :split_at => /\s+\|\s+/
241 return unless first_pars > 0
243 Utils.get_first_pars(@bot, results.map {|url, title| url}, first_pars, :message => m)
246 def google_define(m, what, params)
248 wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
251 m.reply "error googling for #{what}"
256 related_index = wml.index(/Related phrases:/, 0)
257 raise unless related_index
258 defs_index = wml.index(/Definitions of <b>/, related_index)
259 raise unless defs_index
260 defs_end = wml.index(/<input/, defs_index)
261 raise unless defs_end
263 m.reply "no results found for #{what}"
267 related = wml[related_index...defs_index]
268 defs = wml[defs_index...defs_end]
270 m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
275 params.merge!(:lucky => true)
280 what = params[:words].to_s
281 searchfor = CGI.escape(what)
283 debug "Getting gcalc thing: #{searchfor.inspect}"
284 url = GOOGLE_WAP_SEARCH + searchfor
287 html = @bot.httputil.get(url)
289 m.reply "error googlecalcing #{what}"
293 debug "#{html.size} bytes of html recieved"
296 candidates = html.match(GOOGLE_CALC_RESULT)
297 debug "candidates: #{candidates.inspect}"
300 m.reply "couldn't calculate #{what}"
303 result = candidates[1].remove_nonascii
305 debug "replying with: #{result.inspect}"
306 m.reply result.ircify_html
310 what = params[:words].to_s
311 searchfor = CGI.escape("define " + what)
313 debug "Getting gdef thing: #{searchfor.inspect}"
314 url = GOOGLE_WAP_SEARCH + searchfor
317 resp = @bot.httputil.get(url, resp: true)
319 m.reply "error googledefining #{what}"
323 results = resp.xpath(GOOGLE_XPATH_DEF).map(&:content)
326 m.reply "couldn't find a definition for #{what} on Google"
328 m.reply "#{results.first} -- #{results[1..-1].join(' ')}"
332 def wolfram(m, params)
333 what = params[:words].to_s
334 terms = CGI.escape what
335 url = WOLFRAM_API_SEARCH % {
336 :terms => terms, :key => WOLFRAM_API_KEY
340 feed = @bot.httputil.get(url)
343 m.reply "error asking WolframAlfa about #{what}"
348 xml = REXML::Document.new feed
349 if xml.elements['/queryresult'].attributes['error'] == "true"
350 m.reply xml.elements['/queryresult/error/text()'].to_s
353 unless xml.elements['/queryresult'].attributes['success'] == "true"
354 m.reply "no data available"
357 answer_type, answer = [], []
358 xml.elements.each("//pod") { |element|
359 answer_type << element.attributes['title']
360 answer << element.elements['subpod/plaintext'].text
362 # find the first answer that isn't nil,
363 # starting on the second pod in the array
365 answer[1..-1].each { |a|
373 # strip spaces, pipes, and line breaks
374 sep = Bold + ' :: ' + Bold
375 chars = [ [/\n/, sep], [/\t/, " "], [/\s+/, " "], ["|", "-"] ]
376 chars.each { |c| answer[n].gsub!(c[0], c[1]) }
377 m.reply answer_type[n] + sep + answer[n]
380 def wikipedia(m, params)
382 site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
383 debug "Looking up things on #{site}"
385 params[:filter] = / - Wikipedia.*$/
386 params[:hits] = @bot.config['wikipedia.hits']
387 params[:firstpar] = @bot.config['wikipedia.first_par']
388 return google(m, params)
391 def unpedia(m, params)
392 site = "uncyclopedia.org"
393 debug "Looking up things on #{site}"
395 params[:filter] = / - Uncyclopedia.*$/
396 params[:hits] = @bot.config['wikipedia.hits']
397 params[:firstpar] = @bot.config['wikipedia.first_par']
398 return google(m, params)
402 plugin = SearchPlugin.new
404 plugin.map "ddg *words", :action => 'duckduckgo', :threaded => true
405 plugin.map "search *words", :action => 'google', :threaded => true
406 plugin.map "google *words", :action => 'google', :threaded => true
407 plugin.map "lucky *words", :action => 'lucky', :threaded => true
408 plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
409 plugin.map "gdef *words", :action => 'gdef', :threaded => true
410 plugin.map "wa *words", :action => 'wolfram', :threaded => true
411 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
412 plugin.map "wp *words", :action => 'wikipedia', :threaded => true
413 plugin.map "unpedia *words", :action => 'unpedia', :threaded => true