3 # TODO: use lr=lang_<code> or whatever is most appropriate to let google know
4 # it shouldn't use the bot's location to find the preferred language
9 GOOGLE_WAP_LINK = /<a accesskey="(\d)" href=".*?u=(.*?)">(.*?)<\/a>/im
11 class SearchPlugin < Plugin
12 BotConfig.register BotConfigIntegerValue.new('google.hits',
14 :desc => "Number of hits to return from Google searches")
15 BotConfig.register BotConfigIntegerValue.new('google.first_par',
17 :desc => "When set to n > 0, the bot will return the first paragraph from the first n search hits")
18 BotConfig.register BotConfigIntegerValue.new('wikipedia.hits',
20 :desc => "Number of hits to return from Wikipedia searches")
21 BotConfig.register BotConfigIntegerValue.new('wikipedia.first_par',
23 :desc => "When set to n > 0, the bot will return the first paragraph from the first n wikipedia search hits")
25 def help(plugin, topic="")
27 when "search", "google"
28 "#{topic} <string> => search google for <string>"
30 "wp [<code>] <string> => search for <string> on Wikipedia. You can select a national <code> to only search the national Wikipedia"
32 "search <string> (or: google <string>) => search google for <string> | wp <string> => search for <string> on Wikipedia"
37 what = params[:words].to_s
38 searchfor = URI.escape what
39 # This method is also called by other methods to restrict searching to some sites
41 site = "site:#{params[:site]}+"
45 # It is also possible to choose a filter to remove constant parts from the titles
46 # e.g.: "Wikipedia, the free encyclopedia" when doing Wikipedia searches
47 filter = params[:filter] || ""
49 url = "http://www.google.com/wml/search?q=#{site}#{searchfor}"
51 hits = params[:hits] || @bot.config['google.hits']
54 wml = @bot.httputil.get_cached(url)
56 m.reply "error googling for #{what}"
59 results = wml.scan(GOOGLE_WAP_LINK)
60 if results.length == 0
61 m.reply "no results found for #{what}"
65 results = results[0...hits].map { |res|
67 t = Utils.decode_html_entities res[2].gsub(filter, '').strip
68 u = URI.unescape res[1]
70 "#{n}. #{Bold}#{t}#{Bold}: #{u}"
73 m.reply "Results for #{what}: #{results}", :split_at => /\s+\|\s+/
75 first_pars = params[:firstpar] || @bot.config['google.first_par']
77 return unless first_pars > 0
79 Utils.get_first_pars urls, first_pars, :http_util => @bot.httputil, :message => m
83 def wikipedia(m, params)
85 site = "#{lang.nil? ? '' : lang + '.'}wikipedia.org"
86 debug "Looking up things on #{site}"
88 params[:filter] = / - Wikipedia.*$/
89 params[:hits] = @bot.config['wikipedia.hits']
90 params[:firstpar] = @bot.config['wikipedia.first_par']
91 return google(m, params)
95 plugin = SearchPlugin.new
97 plugin.map "search *words", :action => 'google'
98 plugin.map "google *words", :action => 'google'
99 plugin.map "wp :lang *words", :action => 'wikipedia', :requirements => { :lang => /^\w\w\w?$/ }
100 plugin.map "wp *words", :action => 'wikipedia'