]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/search.rb
Initial implementation of proper caching based on last-modified and etag HTTP headers
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / search.rb
1 require 'uri'
2
3 Net::HTTP.version_1_2
4
5 GOOGLE_WAP_LINK = /<a accesskey="(\d)" href=".*?u=(.*?)">(.*?)<\/a>/im
6
7 class SearchPlugin < Plugin
8   def help(plugin, topic="")
9     case topic
10     when "search"
11     "search <string> => search google for <string>"
12     when "google"
13     "google <string> => search google for <string>"
14     when "wp"
15       "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
16     else
17     "search <string> (or: google <string>) => search google for <string> | wp <string> => search for <string> on Wikipedia"
18     end
19   end
20
21   def google(m, params)
22     what = params[:words].to_s
23     searchfor = URI.escape what
24     # This method is also called by other methods to restrict searching to some sites
25     if params[:site]
26       site = "site:#{params[:site]}+"
27     else
28       site = ""
29     end
30     # It is also possible to choose a filter to remove constant parts from the titles
31     # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
32     filter = params[:filter] || ""
33
34     url = "http://www.google.com/wml/search?q=#{site}#{searchfor}"
35
36
37     begin
38       wml = @bot.httputil.get_cached(url)
39     rescue => e
40       m.reply "error googling for #{what}"
41       return
42     end
43     results = wml.scan(GOOGLE_WAP_LINK)
44     if results.length == 0
45       m.reply "no results found for #{what}"
46       return
47     end
48     results = results[0...3].map { |res|
49       n = res[0]
50       t = Utils.decode_html_entities res[2].gsub(filter, '').strip
51       u = URI.unescape res[1]
52       "#{n}. #{Bold}#{t}#{Bold}: #{u}"
53     }.join(" | ")
54
55     m.reply "Results for #{what}: #{results}"
56   end
57
58   def wikipedia(m, params)
59     lang = params[:lang]
60     site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
61     params[:site] = site
62     params[:filter] = / - Wikipedia.*$/
63     return google(m, params)
64   end
65 end
66
67 plugin = SearchPlugin.new
68
69 plugin.map "search *words", :action => 'google'
70 plugin.map "google *words", :action => 'google'
71 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }
72 plugin.map "wp *words", :action => 'wikipedia'
73