PageRenderTime 71ms CodeModel.GetById 2ms app.highlight 64ms RepoModel.GetById 1ms app.codeStats 1ms

/data/rbot/plugins/search.rb

https://github.com/Oblomov/rbot
Ruby | 506 lines | 418 code | 61 blank | 27 comment | 50 complexity | a629e12eed06060396242fbd9ce45001 MD5 | raw file
  1#-- vim:sw=2:et
  2#++
  3#
  4# :title: Google and Wikipedia search plugin for rbot
  5#
  6# Author:: Tom Gilbert (giblet) <tom@linuxbrit.co.uk>
  7# Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
  8#
  9# Copyright:: (C) 2002-2005 Tom Gilbert
 10# Copyright:: (C) 2006 Tom Gilbert, Giuseppe Bilotta
 11# Copyright:: (C) 2006-2007 Giuseppe Bilotta
 12
 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
 16#        for most languages
 17
 18GOOGLE_SEARCH = "http://www.google.com/search?oe=UTF-8&q="
 19GOOGLE_WAP_SEARCH = "http://www.google.com/m/search?hl=en&q="
 20GOOGLE_WAP_LINK = /"r">(?:<div[^>]*>)?<a href="([^"]+)"[^>]*>(.*?)<\/a>/im
 21GOOGLE_CALC_RESULT = %r{<h[1-6] class="r" [^>]*>(.+?)</h}
 22GOOGLE_COUNT_RESULT = %r{<font size=-1>Results <b>1<\/b> - <b>10<\/b> of about <b>(.*)<\/b> for}
 23GOOGLE_DEF_RESULT = %r{onebox_result">\s*(.*?)\s*<br/>\s*(.*?)<table}
 24GOOGLE_TIME_RESULT = %r{alt="Clock"></td><td valign=[^>]+>(.+?)<(br|/td)>}
 25
 26DDG_API_SEARCH = "http://api.duckduckgo.com/?format=xml&no_html=1&skip_disambig=1&no_redirect=0&q="
 27
 28WOLFRAM_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:*"
 31WOLFRAM_API_KEY = "4EU37Y-TX9WJG3JH3"
 32
 33class 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',
 38    :default => 0,
 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',
 41    :default => 3,
 42    :desc => "Number of hits to return from Google searches")
 43  Config.register Config::IntegerValue.new('google.first_par',
 44    :default => 0,
 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',
 47    :default => 3,
 48    :desc => "Number of hits to return from Wikipedia searches")
 49  Config.register Config::IntegerValue.new('wikipedia.first_par',
 50    :default => 1,
 51    :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
 52
 53  def help(plugin, topic="")
 54    case topic
 55    when "ddg"
 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>"
 60    when "gcalc"
 61      "gcalc <equation> => use the google calculator to find the answer to <equation>"
 62    when "gdef"
 63      "gdef <term(s)> => use the google define mechanism to find a definition of <term(s)>"
 64    when "gtime"
 65      "gtime <location> => use the google clock to find the current time at <location>"
 66    when "wa"
 67      "wa <string> => searches WolframAlpha for <string>"
 68    when "wp"
 69      "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
 70    when "unpedia"
 71      "unpedia <string> => search for <string> on Uncyclopedia"
 72    else
 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"
 74    end
 75  end
 76
 77  def duckduckgo(m, params)
 78    what = params[:words].to_s
 79    terms = CGI.escape what
 80    url = DDG_API_SEARCH + terms
 81
 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)
 85
 86    begin
 87      feed = @bot.httputil.get(url)
 88      raise unless feed
 89    rescue => e
 90      m.reply "error duckduckgoing for #{what}"
 91      return
 92    end
 93    debug feed
 94
 95    xml = REXML::Document.new feed
 96    heading = xml.elements['//Heading/text()'].to_s
 97    # answer is returned for calculations
 98    answer = xml.elements['//Answer/text()'].to_s
 99    # abstract is returned for definitions etc
100    abstract = xml.elements['//AbstractText/text()'].to_s
101    abfrom = ""
102    unless abstract.empty?
103      absrc = xml.elements['//AbstractSource/text()'].to_s
104      aburl = xml.elements['//AbstractURL/text()'].to_s
105      unless absrc.empty? and aburl.empty?
106        abfrom = " --"
107        abfrom << " " << absrc unless absrc.empty?
108        abfrom << " " << aburl unless aburl.empty?
109      end
110    end
111
112    # but also definition (yes, you can have both, see e.g. printf)
113    definition = xml.elements['//Definition/text()'].to_s
114    deffrom = ""
115    unless definition.empty?
116      defsrc = xml.elements['//Definition/@source/text()'].to_s
117      defurl = xml.elements['//Definition/@url/text()'].to_s
118      unless defsrc.empty? and defurl.empty?
119        deffrom = " --"
120        deffrom << " " << defsrc unless defsrc.empty?
121        deffrom << " " << defurl unless defurl.empty?
122      end
123    end
124
125    if heading.empty? and answer.empty? and abstract.empty? and definition.empty?
126      m.reply "no results"
127      return
128    end
129
130    # if we got a one-shot answer (e.g. a calculation, return it)
131    unless answer.empty?
132      m.reply answer
133      return
134    end
135
136    # otherwise, return the abstract, followed by as many hits as found
137    unless heading.empty? or abstract.empty?
138      m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
139        :bold => Bold, :heading => heading,
140        :abstract => abstract, :abfrom => abfrom
141      }
142    end
143    unless heading.empty? or definition.empty?
144      m.reply "%{bold}%{heading}:%{bold} %{abstract}%{abfrom}" % {
145        :bold => Bold, :heading => heading,
146        :abstract => definition, :abfrom => deffrom
147      }
148    end
149    # return zeroclick search results
150    links, texts = [], []
151    xml.elements.each("//Results/Result/FirstURL") { |element|
152      links << element.text
153      break if links.size == hits
154    }
155    return if links.empty?
156
157    xml.elements.each("//Results/Result/Text") { |element|
158      texts << " #{element.text}"
159      break if links.size == hits
160    }
161    # TODO see treatment of `single` in google search
162
163    single ||= (links.length == 1)
164    pretty = []
165    links.each_with_index do |u, i|
166      t = texts[i]
167      pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
168        :n => (single ? "" : "#{i}. "),
169        :sep => (single ? " -- " : ": "),
170        :b => Bold, :t => t, :u => u
171      })
172    end
173
174    result_string = pretty.join(" | ")
175
176    # If we return a single, full result, change the output to a more compact representation
177    if single
178      fp = first_pars > 0 ? " --  #{Utils.get_first_pars(links, first_pars)}" : ""
179      m.reply("Result for %{what}: %{string}%{fp}" % {
180        :what => what, :string => result_string, :fp => fp
181      }, :overlong => :truncate)
182      return
183    end
184
185    m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
186
187    return unless first_pars > 0
188
189    Utils.get_first_pars urls, first_pars, :message => m
190  end
191
192  def google(m, params)
193    what = params[:words].to_s
194    if what.match(/^define:/)
195      return google_define(m, what, params)
196    end
197
198    searchfor = CGI.escape what
199    # This method is also called by other methods to restrict searching to some sites
200    if params[:site]
201      site = "site:#{params[:site]}+"
202    else
203      site = ""
204    end
205    # It is also possible to choose a filter to remove constant parts from the titles
206    # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
207    filter = params[:filter] || ""
208
209    url = GOOGLE_WAP_SEARCH + site + searchfor
210
211    hits = params[:hits] || @bot.config['google.hits']
212    hits = 1 if params[:lucky]
213
214    first_pars = params[:firstpar] || @bot.config['google.first_par']
215
216    single = params[:lucky] || (hits == 1 and first_pars == 1)
217
218    begin
219      wml = @bot.httputil.get(url)
220      raise unless wml
221    rescue => e
222      m.reply "error googling for #{what}"
223      return
224    end
225    results = wml.scan(GOOGLE_WAP_LINK)
226
227    if results.length == 0
228      m.reply "no results found for #{what}"
229      return
230    end
231
232    single ||= (results.length==1)
233    pretty = []
234
235    begin
236      urls = Array.new
237
238      debug results
239      results.each do |res|
240        t = res[1].ircify_html(:img => "[%{src} %{alt} %{dimensions}]").strip
241        u = res[0]
242        if u.sub!(%r{^http://www.google.com/aclk\?},'')
243          u = CGI::parse(u)['adurl'].first
244          debug "skipping ad for #{u}"
245          next
246        elsif u.sub!(%r{^http://www.google.com/gwt/x\?},'')
247          u = CGI::parse(u)['u'].first
248        elsif u.sub!(%r{^/url\?},'')
249          u = CGI::parse(u)['q'].first
250        end
251        urls.push(u)
252        pretty.push("%{n}%{b}%{t}%{b}%{sep}%{u}" % {
253          :n => (single ? "" : "#{urls.length}. "),
254          :sep => (single ? " -- " : ": "),
255          :b => Bold, :t => t, :u => u
256        })
257        break if urls.length == hits
258      end
259    rescue => e
260      m.reply "failed to understand what google found for #{what}"
261      error e
262      debug wml
263      debug results
264      return
265    end
266
267    if params[:lucky]
268      m.reply pretty.first
269      return
270    end
271
272    result_string = pretty.join(" | ")
273
274    # If we return a single, full result, change the output to a more compact representation
275    if single
276      m.reply "Result for %s: %s -- %s" % [what, result_string, Utils.get_first_pars(urls, first_pars)], :overlong => :truncate
277      return
278    end
279
280    m.reply "Results for #{what}: #{result_string}", :split_at => /\s+\|\s+/
281
282    return unless first_pars > 0
283
284    Utils.get_first_pars urls, first_pars, :message => m
285
286  end
287
288  def google_define(m, what, params)
289    begin
290      wml = @bot.httputil.get(GOOGLE_SEARCH + CGI.escape(what))
291      raise unless wml
292    rescue => e
293      m.reply "error googling for #{what}"
294      return
295    end
296
297    begin
298      related_index = wml.index(/Related phrases:/, 0)
299      raise unless related_index
300      defs_index = wml.index(/Definitions of <b>/, related_index)
301      raise unless defs_index
302      defs_end = wml.index(/<input/, defs_index)
303      raise unless defs_end
304    rescue => e
305      m.reply "no results found for #{what}"
306      return
307    end
308
309    related = wml[related_index...defs_index]
310    defs = wml[defs_index...defs_end]
311
312    m.reply defs.ircify_html(:a_href => Underline), :split_at => (Underline + ' ')
313
314  end
315
316  def lucky(m, params)
317    params.merge!(:lucky => true)
318    google(m, params)
319  end
320
321  def gcalc(m, params)
322    what = params[:words].to_s
323    searchfor = CGI.escape(what)
324
325    debug "Getting gcalc thing: #{searchfor.inspect}"
326    url = GOOGLE_WAP_SEARCH + searchfor
327
328    begin
329      html = @bot.httputil.get(url)
330    rescue => e
331      m.reply "error googlecalcing #{what}"
332      return
333    end
334
335    debug "#{html.size} bytes of html recieved"
336    debug html
337
338    candidates = html.match(GOOGLE_CALC_RESULT)
339    debug "candidates: #{candidates.inspect}"
340
341    if candidates.nil?
342      m.reply "couldn't calculate #{what}"
343      return
344    end
345    result = candidates[1]
346
347    debug "replying with: #{result.inspect}"
348    m.reply result.ircify_html
349  end
350
351  def gcount(m, params)
352    what = params[:words].to_s
353    searchfor = CGI.escape(what)
354
355    debug "Getting gcount thing: #{searchfor.inspect}"
356    url = GOOGLE_SEARCH + searchfor
357
358    begin
359      html = @bot.httputil.get(url)
360    rescue => e
361      m.reply "error googlecounting #{what}"
362      return
363    end
364
365    debug "#{html.size} bytes of html recieved"
366
367    results = html.scan(GOOGLE_COUNT_RESULT)
368    debug "results: #{results.inspect}"
369
370    if results.length != 1
371      m.reply "couldn't count #{what}"
372      return
373    end
374
375    result = results[0][0].ircify_html
376    debug "replying with: #{result.inspect}"
377    m.reply "total results: #{result}"
378
379  end
380
381  def gdef(m, params)
382    what = params[:words].to_s
383    searchfor = CGI.escape("define " + what)
384
385    debug "Getting gdef thing: #{searchfor.inspect}"
386    url = GOOGLE_WAP_SEARCH + searchfor
387
388    begin
389      html = @bot.httputil.get(url)
390    rescue => e
391      m.reply "error googledefining #{what}"
392      return
393    end
394
395    debug html
396    results = html.scan(GOOGLE_DEF_RESULT)
397    debug "results: #{results.inspect}"
398
399    if results.length != 1
400      m.reply "couldn't find a definition for #{what} on Google"
401      return
402    end
403
404    head = results[0][0].ircify_html
405    text = results[0][1].ircify_html
406    m.reply "#{head} -- #{text}"
407  end
408
409  def wolfram(m, params)
410    what = params[:words].to_s
411    terms = CGI.escape what
412    url = WOLFRAM_API_SEARCH % {
413      :terms => terms, :key => WOLFRAM_API_KEY
414    }
415
416    begin
417      feed = @bot.httputil.get(url)
418      raise unless feed
419    rescue => e
420      m.reply "error asking WolframAlfa about #{what}"
421      return
422    end
423    debug feed
424
425    xml = REXML::Document.new feed
426    if xml.elements['/queryresult'].attributes['error'] == "true"
427      m.reply xml.elements['/queryresult/error/text()'].to_s
428      return
429    end
430    unless xml.elements['/queryresult'].attributes['success'] == "true"
431      m.reply "no data available"
432      return
433    end
434    answer = []
435    xml.elements.each("//pod/subpod/plaintext") { |element|
436      answer << element.text
437    }
438    # strip spaces and line breaks
439    answer[1].gsub!(/\n/, Bold + ' :: ' + Bold )
440    answer[1].gsub!(/\t/, ' ')
441    answer[1].gsub!(/\s+/, ' ')
442    m.reply answer[1].to_s
443  end
444
445  def wikipedia(m, params)
446    lang = params[:lang]
447    site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
448    debug "Looking up things on #{site}"
449    params[:site] = site
450    params[:filter] = / - Wikipedia.*$/
451    params[:hits] = @bot.config['wikipedia.hits']
452    params[:firstpar] = @bot.config['wikipedia.first_par']
453    return google(m, params)
454  end
455
456  def unpedia(m, params)
457    site = "uncyclopedia.org"
458    debug "Looking up things on #{site}"
459    params[:site] = site
460    params[:filter] = / - Uncyclopedia.*$/
461    params[:hits] = @bot.config['wikipedia.hits']
462    params[:firstpar] = @bot.config['wikipedia.first_par']
463    return google(m, params)
464  end
465
466  def gtime(m, params)
467    where = params[:words].to_s
468    where.sub!(/^\s*in\s*/, '')
469    searchfor = CGI.escape("time in " + where)
470    url = GOOGLE_SEARCH + searchfor
471
472    begin
473      html = @bot.httputil.get(url)
474    rescue => e
475      m.reply "Error googletiming #{where}"
476      return
477    end
478
479    debug html
480    results = html.scan(GOOGLE_TIME_RESULT)
481    debug "results: #{results.inspect}"
482
483    if results.length != 1
484      m.reply "Couldn't find the time for #{where} on Google"
485      return
486    end
487
488    time = results[0][0].ircify_html
489    m.reply "#{time}"
490  end
491end
492
493plugin = SearchPlugin.new
494
495plugin.map "ddg *words", :action => 'duckduckgo', :threaded => true
496plugin.map "search *words", :action => 'google', :threaded => true
497plugin.map "google *words", :action => 'google', :threaded => true
498plugin.map "lucky *words", :action => 'lucky', :threaded => true
499plugin.map "gcount *words", :action => 'gcount', :threaded => true
500plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
501plugin.map "gdef *words", :action => 'gdef', :threaded => true
502plugin.map "gtime *words", :action => 'gtime', :threaded => true
503plugin.map "wa *words", :action => 'wolfram', :threaded => true
504plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
505plugin.map "wp *words", :action => 'wikipedia', :threaded => true
506plugin.map "unpedia *words", :action => 'unpedia', :threaded => true