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