Googlefight plugin fix
[rbot] / data / rbot / plugins / googlefight.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Googlefight plugin for rbot
5 #
6 # Author:: Raine Virta <rane@kapsi.fi
7 # Copyright:: (C) 2009 Raine Virta
8 # License:: GPL v2
9
10 class GoogleFightPlugin < Plugin
11   def help(plugin, topic)
12     "googlefight <keyword 1> <keyword 2> [... <keyword n+1>] => battles given keywords based on amount of google search results and announces the winner!"
13   end
14
15   def fight(m, params)
16     keywords = parse_keywords(params)
17     return if keywords.nil?
18
19     keywords.map! do |k|
20       [k, google_count(k)]
21     end
22
23     m.reply output(keywords)
24   end
25
26   def output(result)
27     result = result.sort_by { |e| e[1] }.reverse
28     str = result.map do |kw|
29       "%{keyword} (%{count})" % {
30         :keyword => Bold+kw[0]+Bold,
31         :count   => kw[1].to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1,")
32       }
33     end.join(" vs. ")
34
35     unless result[0][1].zero?
36       str << _(" -- %{keyword} wins!") % {
37         :keyword => Bold+result[0][0]+Bold
38       }
39     else
40       str << _(" -- no winner here!")
41     end
42   end
43
44   def parse_keywords(params)
45     str = params[:keywords].join(" ")
46
47     # foo "foo bar" bar
48     # no separators so assume they're all separate keywords
49     if str.match(/(?:"[\w\s]+"|\w+)(?: (?:"[\w\s]+"|\w+))+/)
50       str.scan(/"[^"]+"|\S+/).flatten
51     end
52   end
53
54   def google_count(query)
55     url  = 'http://www.google.com/search?hl=en&safe=off&btnG=Search&q=' << CGI.escape(query)
56     html = Net::HTTP.get(URI.parse((url)))
57     res  = html.scan(%r{of about <b>([\d,]+)<\/b>})
58     res[0][0].to_s.tr(",", "").to_i
59   end
60 end
61
62 plugin = GoogleFightPlugin.new
63 plugin.map "googlefight *keywords", :action => "fight",
64   :requirements => { :keywords => /^[\w\s"]+? (?:(?:(?:\||vs\.) )?[\w\s"]+?)+/ }