]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/search.rb
search plugin: enhance 'lucky' output
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / search.rb
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
18 GOOGLE_SEARCH = "http://www.google.com/search?oe=UTF-8&q="
19 GOOGLE_WAP_SEARCH = "http://www.google.com/m/search?hl=en&q="
20 # GOOGLE_WAP_LINK = /<a accesskey="(\d)" href=".*?u=(.*?)">(.*?)<\/a>/im
21 GOOGLE_WAP_LINK = /<a href="(?:.*?u=(.*?)|(http:\/\/.*?))">(.*?)<\/a>/im
22 GOOGLE_CALC_RESULT = %r{<img src=/images/calc_img\.gif(?: width=40 height=30 alt="")?>.*?<h2 class=r[^>]*><b>(.+?)</b>}
23 GOOGLE_COUNT_RESULT = %r{<font size=-1>Results <b>1<\/b> - <b>10<\/b> of about <b>(.*)<\/b> for}
24 GOOGLE_DEF_RESULT = %r{<p> (Web definitions for .*?)<br/>(.*?)<br/>(.*?)\s-\s+<a href}
25 GOOGLE_TIME_RESULT = %r{alt="Clock"></td><td valign=[^>]+>(.+?)<(br|/td)>}
26
27 class SearchPlugin < Plugin
28   Config.register Config::IntegerValue.new('google.hits',
29     :default => 3,
30     :desc => "Number of hits to return from Google searches")
31   Config.register Config::IntegerValue.new('google.first_par',
32     :default => 0,
33     :desc => "When set to n > 0, the bot will return the first paragraph from the first n search hits")
34   Config.register Config::IntegerValue.new('wikipedia.hits',
35     :default => 3,
36     :desc => "Number of hits to return from Wikipedia searches")
37   Config.register Config::IntegerValue.new('wikipedia.first_par',
38     :default => 1,
39     :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
40
41   def help(plugin, topic="")
42     case topic
43     when "search", "google"
44       "#{topic} <string> => search google for <string>"
45     when "gcalc"
46       "gcalc <equation> => use the google calculator to find the answer to <equation>"
47     when "gdef"
48       "gdef <term(s)> => use the google define mechanism to find a definition of <term(s)>"
49     when "gtime"
50       "gtime <location> => use the google clock to find the current time at <location>"
51     when "wp"
52       "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
53     when "unpedia"
54       "unpedia <string> => search for <string> on Uncyclopedia"
55     else
56       "search <string> (or: google <string>) => search google for <string> | wp <string> => search for <string> on Wikipedia | unpedia <string> => search for <string> on Uncyclopedia"
57     end
58   end
59
60   def google(m, params)
61     what = params[:words].to_s
62     searchfor = CGI.escape what
63     # This method is also called by other methods to restrict searching to some sites
64     if params[:site]
65       site = "site:#{params[:site]}+"
66     else
67       site = ""
68     end
69     # It is also possible to choose a filter to remove constant parts from the titles
70     # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
71     filter = params[:filter] || ""
72
73     url = GOOGLE_WAP_SEARCH + site + searchfor
74
75     hits = params[:hits] || @bot.config['google.hits']
76     hits = 1 if params[:lucky]
77
78     first_pars = params[:firstpar] || @bot.config['google.first_par']
79
80     single = params[:lucky] || (hits == 1 and first_pars == 1)
81
82     begin
83       wml = @bot.httputil.get(url)
84       raise unless wml
85     rescue => e
86       m.reply "error googling for #{what}"
87       return
88     end
89     results = wml.scan(GOOGLE_WAP_LINK)
90     if results.length == 0
91       m.reply "no results found for #{what}"
92       return
93     end
94     single ||= (results.length==1)
95     urls = Array.new
96     n = 0
97     results = results[0...hits].map { |res|
98       n += 1
99       t = Utils.decode_html_entities res[2].gsub(filter, '').strip
100       u = URI.unescape(res[0] || res[1])
101       urls.push(u)
102       "%{n}%{b}%{t}%{b}%{sep}%{u}" % {
103         :n => (single ? "" : "#{n}. "),
104         :sep => (single ? " -- " : ": "),
105         :b => Bold, :t => t, :u => u
106       }
107     }.join(" | ")
108
109     if params[:lucky]
110       m.reply results.first
111       return
112     end
113
114     # If we return a single, full result, change the output to a more compact representation
115     if single
116       m.reply "Result for %s: %s -- %s" % [what, results, Utils.get_first_pars(urls, first_pars)], :overlong => :truncate
117       return
118     end
119
120     m.reply "Results for #{what}: #{results}", :split_at => /\s+\|\s+/
121
122     return unless first_pars > 0
123
124     Utils.get_first_pars urls, first_pars, :message => m
125
126   end
127
128   def lucky(m, params)
129     params.merge!(:lucky => true)
130     google(m, params)
131   end
132
133   def gcalc(m, params)
134     what = params[:words].to_s
135     searchfor = CGI.escape(what)
136
137     debug "Getting gcalc thing: #{searchfor.inspect}"
138     url = GOOGLE_SEARCH + searchfor
139
140     begin
141       html = @bot.httputil.get(url)
142     rescue => e
143       m.reply "error googlecalcing #{what}"
144       return
145     end
146
147     debug "#{html.size} bytes of html recieved"
148
149     results = html.scan(GOOGLE_CALC_RESULT)
150     debug "results: #{results.inspect}"
151
152     if results.length != 1
153       m.reply "couldn't calculate #{what}"
154       return
155     end
156
157     result = results[0][0].ircify_html
158     debug "replying with: #{result.inspect}"
159     m.reply "#{result}"
160   end
161
162   def gcount(m, params)
163     what = params[:words].to_s
164     searchfor = CGI.escape(what)
165
166     debug "Getting gcount thing: #{searchfor.inspect}"
167     url = GOOGLE_SEARCH + searchfor
168
169     begin
170       html = @bot.httputil.get(url)
171     rescue => e
172       m.reply "error googlecounting #{what}"
173       return
174     end
175
176     debug "#{html.size} bytes of html recieved"
177
178     results = html.scan(GOOGLE_COUNT_RESULT)
179     debug "results: #{results.inspect}"
180
181     if results.length != 1
182       m.reply "couldn't count #{what}"
183       return
184     end
185
186     result = results[0][0].ircify_html
187     debug "replying with: #{result.inspect}"
188     m.reply "total results: #{result}"
189
190   end
191
192   def gdef(m, params)
193     what = params[:words].to_s
194     searchfor = CGI.escape("define " + what)
195
196     debug "Getting gdef thing: #{searchfor.inspect}"
197     url = GOOGLE_WAP_SEARCH + searchfor
198
199     begin
200       html = @bot.httputil.get(url)
201     rescue => e
202       m.reply "error googledefining #{what}"
203       return
204     end
205
206     debug html
207     results = html.scan(GOOGLE_DEF_RESULT)
208     debug "results: #{results.inspect}"
209
210     if results.length != 1
211       m.reply "couldn't find a definition for #{what} on Google"
212       return
213     end
214
215     head = results[0][0].ircify_html
216     text = results[0][1].ircify_html
217     link = results[0][2]
218     m.reply "#{head} -- #{link}\n#{text}"
219   end
220
221   def wikipedia(m, params)
222     lang = params[:lang]
223     site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
224     debug "Looking up things on #{site}"
225     params[:site] = site
226     params[:filter] = / - Wikipedia.*$/
227     params[:hits] = @bot.config['wikipedia.hits']
228     params[:firstpar] = @bot.config['wikipedia.first_par']
229     return google(m, params)
230   end
231
232   def unpedia(m, params)
233     site = "uncyclopedia.org"
234     debug "Looking up things on #{site}"
235     params[:site] = site
236     params[:filter] = / - Uncyclopedia.*$/
237     params[:hits] = @bot.config['wikipedia.hits']
238     params[:firstpar] = @bot.config['wikipedia.first_par']
239     return google(m, params)
240   end
241
242   def gtime(m, params)
243     where = params[:words].to_s
244     where.sub!(/^\s*in\s*/, '')
245     searchfor = CGI.escape("time in " + where)
246     url = GOOGLE_SEARCH + searchfor
247
248     begin
249       html = @bot.httputil.get(url)
250     rescue => e
251       m.reply "Error googletiming #{where}"
252       return
253     end
254
255     debug html
256     results = html.scan(GOOGLE_TIME_RESULT)
257     debug "results: #{results.inspect}"
258
259     if results.length != 1
260       m.reply "Couldn't find the time for #{where} on Google"
261       return
262     end
263
264     time = results[0][0].ircify_html
265     m.reply "#{time}"
266   end
267 end
268
269 plugin = SearchPlugin.new
270
271 plugin.map "search *words", :action => 'google', :threaded => true
272 plugin.map "google *words", :action => 'google', :threaded => true
273 plugin.map "lucky *words", :action => 'lucky', :threaded => true
274 plugin.map "gcount *words", :action => 'gcount', :threaded => true
275 plugin.map "gcalc *words", :action => 'gcalc', :threaded => true
276 plugin.map "gdef *words", :action => 'gdef', :threaded => true
277 plugin.map "gtime *words", :action => 'gtime', :threaded => true
278 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }, :threaded => true
279 plugin.map "wp *words", :action => 'wikipedia', :threaded => true
280 plugin.map "unpedia *words", :action => 'unpedia', :threaded => true
281