4 # :title: Googlefight plugin for rbot
6 # Author:: Raine Virta <rane@kapsi.fi
7 # Copyright:: (C) 2009 Raine Virta
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!"
16 keywords = parse_keywords(params)
17 return if keywords.nil?
23 m.reply output(keywords)
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,")
35 unless result[0][1].zero?
36 str << _(" -- %{keyword} wins!") % {
37 :keyword => Bold+result[0][0]+Bold
40 str << _(" -- no winner here!")
44 def parse_keywords(params)
45 str = params[:keywords].join(" ")
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
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{Results <b>1</b> - <b>\d+</b> of(?: about)? <b>([\d,]+)</b>})
58 res.to_s.tr(",", "").to_i
62 plugin = GoogleFightPlugin.new
63 plugin.map "googlefight *keywords", :action => "fight",
64 :requirements => { :keywords => /^[\w\s"]+? (?:(?:(?:\||vs\.) )?[\w\s"]+?)+/ }