]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/search.rb
search plugin now exploits the new sendmsg improvements
[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 ::String
8   def ircify_html
9     txt = self
10
11     # bold and strong -> bold
12     txt.gsub!(/<\/?(?:b|strong)\s*>/, "#{Bold}")
13
14     # italic, emphasis and underline -> underline
15     txt.gsub!(/<\/?(?:i|em|u)\s*>/, "#{Underline}")
16
17     ## This would be a nice addition, but the results are horrible
18     ## Maybe make it configurable?
19     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
20
21     # Paragraph and br tags are converted to whitespace.
22     txt.gsub!(/<\/?(p|br)\s*\/?\s*>/, ' ')
23     txt.gsub!("\n", ' ')
24
25     # All other tags are just removed
26     txt.gsub!(/<[^>]+>/, '')
27
28     # Remove double formatting options, since they only waste bytes
29     txt.gsub!(/#{Bold}\s*#{Bold}/,"")
30     txt.gsub!(/#{Underline}\s*#{Underline}/,"")
31
32     # And finally whitespace is squeezed
33     txt.gsub!(/\s+/, ' ')
34
35     # Decode entities and strip whitespace
36     return Utils.decode_html_entities(txt).strip!
37   end
38 end
39
40 class SearchPlugin < Plugin
41   BotConfig.register BotConfigIntegerValue.new('google.hits',
42     :default => 3,
43     :desc => "Number of hits to return from Google searches")
44   BotConfig.register BotConfigIntegerValue.new('google.first_par',
45     :default => 0,
46     :desc => "When set to n > 0, the bot will return the first paragraph from the first n search hits")
47   BotConfig.register BotConfigIntegerValue.new('wikipedia.hits',
48     :default => 3,
49     :desc => "Number of hits to return from Wikipedia searches")
50   BotConfig.register BotConfigIntegerValue.new('wikipedia.first_par',
51     :default => 1,
52     :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
53
54   def help(plugin, topic="")
55     case topic
56     when "search", "google"
57       "#{topic} <string> => search google for <string>"
58     when "wp"
59       "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
60     else
61       "search <string> (or: google <string>) => search google for <string> | wp <string> => search for <string> on Wikipedia"
62     end
63   end
64
65   def google(m, params)
66     what = params[:words].to_s
67     searchfor = URI.escape what
68     # This method is also called by other methods to restrict searching to some sites
69     if params[:site]
70       site = "site:#{params[:site]}+"
71     else
72       site = ""
73     end
74     # It is also possible to choose a filter to remove constant parts from the titles
75     # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
76     filter = params[:filter] || ""
77
78     url = "http://www.google.com/wml/search?q=#{site}#{searchfor}"
79
80     hits = params[:hits] || @bot.config['google.hits']
81
82     begin
83       wml = @bot.httputil.get_cached(url)
84     rescue => e
85       m.reply "error googling for #{what}"
86       return
87     end
88     results = wml.scan(GOOGLE_WAP_LINK)
89     if results.length == 0
90       m.reply "no results found for #{what}"
91       return
92     end
93     urls = Array.new
94     results = results[0...hits].map { |res|
95       n = res[0]
96       t = Utils.decode_html_entities res[2].gsub(filter, '').strip
97       u = URI.unescape res[1]
98       urls.push(u)
99       "#{n}. #{Bold}#{t}#{Bold}: #{u}"
100     }.join(" | ")
101
102     m.reply "Results for #{what}: #{results}", :split_at => /\s+\|\s+/
103
104     first_pars = params[:firstpar] || @bot.config['google.first_par']
105
106     idx = 0
107     while first_pars > 0 and urls.length > 0
108       url.replace(urls.shift)
109       idx += 1
110
111       # FIXME what happens if some big file is returned? We should share
112       # code with the url plugin to only retrieve partial file content!
113       xml = @bot.httputil.get_cached(url)
114       if xml.nil?
115         debug "Unable to retrieve #{url}"
116         next
117       end
118       # We get the first par after the first main heading, if possible
119       header_found = xml.match(/<h1(?:\s+[^>]*)?>(.*?)<\/h1>/im)
120       txt = String.new
121       if header_found
122         debug "Found header: #{header_found[1].inspect}"
123         while txt.empty? 
124           header_found = $'
125           candidate = header_found[/<p(?:\s+[^>]*)?>.*?<\/p>/im]
126           break unless candidate
127           txt.replace candidate.ircify_html
128         end
129       end
130       # If we haven't found a first par yet, try to get it from the whole
131       # document
132       if txt.empty?
133         header_found = xml
134         while txt.empty? 
135           candidate = header_found[/<p(?:\s+[^>]*)?>.*?<\/p>/im]
136           break unless candidate
137           txt.replace candidate.ircify_html
138           header_found = $'
139         end
140       end
141       # Nothing yet, try title
142       if txt.empty?
143         debug "No first par found\n#{xml}"
144         # FIXME only do this if the 'url' plugin is loaded
145         txt.replace @bot.plugins['url'].get_title_from_html(xml)
146         next if txt.empty?
147       end
148       m.reply "[#{idx}] #{txt}", :overlong => :truncate
149       first_pars -=1
150     end
151   end
152
153   def wikipedia(m, params)
154     lang = params[:lang]
155     site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
156     debug "Looking up things on #{site}"
157     params[:site] = site
158     params[:filter] = / - Wikipedia.*$/
159     params[:hits] = @bot.config['wikipedia.hits']
160     params[:firstpar] = @bot.config['wikipedia.first_par']
161     return google(m, params)
162   end
163 end
164
165 plugin = SearchPlugin.new
166
167 plugin.map "search *words", :action => 'google'
168 plugin.map "google *words", :action => 'google'
169 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }
170 plugin.map "wp *words", :action => 'wikipedia'
171