]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/search.rb
Searches now can return the first paragraph of the first 'n' hits. Wikipedia and...
[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     txt.gsub!(/<\/?b\s*>/, "#{Bold}")
19     txt.gsub!(/<\/?i\s*>/, "#{Underline}")
20     ## This would be a nice addition, but the results are horrible
21     ## Maybe make it configurable?
22     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
23     txt.gsub!(/<\/?(p|br)>/, ' ')
24     txt.gsub!("\n", ' ')
25     txt.gsub!(/<[^>]+>/, '')
26     txt.gsub!(/\s+/, ' ')
27     return Utils.decode_html_entities(txt).strip!
28   end
29 end
30
31 class SearchPlugin < Plugin
32   BotConfig.register BotConfigIntegerValue.new('google.hits',
33     :default => 3,
34     :desc => "Number of hits to return from Google searches")
35   BotConfig.register BotConfigIntegerValue.new('google.first_par',
36     :default => 0,
37     :desc => "When set to n > 0, the bot will return the first paragraph from the first n search hits")
38   BotConfig.register BotConfigIntegerValue.new('wikipedia.hits',
39     :default => 3,
40     :desc => "Number of hits to return from Wikipedia searches")
41   BotConfig.register BotConfigIntegerValue.new('wikipedia.first_par',
42     :default => 1,
43     :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
44
45   def help(plugin, topic="")
46     case topic
47     when "search", "google"
48       "#{topic} <string> => search google for <string>"
49     when "wp"
50       "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
51     else
52       "search <string> (or: google <string>) => search google for <string> | wp <string> => search for <string> on Wikipedia"
53     end
54   end
55
56   def google(m, params)
57     what = params[:words].to_s
58     searchfor = URI.escape what
59     # This method is also called by other methods to restrict searching to some sites
60     if params[:site]
61       site = "site:#{params[:site]}+"
62     else
63       site = ""
64     end
65     # It is also possible to choose a filter to remove constant parts from the titles
66     # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
67     filter = params[:filter] || ""
68
69     url = "http://www.google.com/wml/search?q=#{site}#{searchfor}"
70
71     hits = params[:hits] || @bot.config['google.hits']
72
73     begin
74       wml = @bot.httputil.get_cached(url)
75     rescue => e
76       m.reply "error googling for #{what}"
77       return
78     end
79     results = wml.scan(GOOGLE_WAP_LINK)
80     if results.length == 0
81       m.reply "no results found for #{what}"
82       return
83     end
84     urls = Array.new
85     results = results[0...hits].map { |res|
86       n = res[0]
87       t = Utils.decode_html_entities res[2].gsub(filter, '').strip
88       u = URI.unescape res[1]
89       urls.push(u)
90       "#{n}. #{Bold}#{t}#{Bold}: #{u}"
91     }.join(" | ")
92
93     m.reply "Results for #{what}: #{results}"
94
95     first_pars = params[:firstpar] || @bot.config['google.first_par']
96
97     idx = 0
98     while first_pars > 0 and urls.length > 0
99       url.replace(urls.shift)
100       idx += 1
101       xml = @bot.httputil.get_cached(url)
102       if xml.nil?
103         debug "Unable to retrieve #{url}"
104         next
105       end
106       # We get the first par after the first main heading, if possible
107       header_found = xml.match(/<h1( [^>]*)?>.*?<\/h1>/im)
108       txt = nil
109       if header_found
110         txt = header_found.post_match[/<p( [^>]*)?>.*?<\/p>/im]
111       end
112       # If we haven't found a first par yet, try to get it from the whole
113       # document
114       unless txt
115         txt = xml[/<p( [^>]*)?>.*?<\/p>/im]
116       end
117       # Nothing yet, give up
118       unless txt
119         debug "No first par found\n#{xml}"
120         next
121       end
122       m.reply "[#{idx}] #{txt.ircify_html}".omissis_after(400)
123       first_pars -=1
124     end
125   end
126
127   def wikipedia(m, params)
128     lang = params[:lang]
129     site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
130     debug "Looking up things on #{site}"
131     params[:site] = site
132     params[:filter] = / - Wikipedia.*$/
133     params[:hits] = @bot.config['wikipedia.hits']
134     params[:firstpar] = @bot.config['wikipedia.first_par']
135     return google(m, params)
136   end
137 end
138
139 plugin = SearchPlugin.new
140
141 plugin.map "search *words", :action => 'google'
142 plugin.map "google *words", :action => 'google'
143 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }
144 plugin.map "wp *words", :action => 'wikipedia'
145