]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/geoip.rb
geoip plugin
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / geoip.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Geo IP Plugin
5 #
6 # Author:: Raine Virta <rane@kapsi.fi>
7 # Copyright:: (C) 2008 Raine Virta
8 # License:: GPL v2
9 #
10 # Resolves the geographic locations of users and IP addresses
11
12 module GeoIP
13   GEO_IP = "http://www.geoiptool.com/en/?IP="
14
15   def self.resolve(hostname)
16     raw = Irc::Utils.bot.httputil.get(GEO_IP+hostname, :cache => true)
17
18     {
19       :country => raw.scan(%r{Country:.*?<a href=".*?" target="_blank"> (.*?)</a>}m).to_s,
20       :region  => raw.scan(%r{Region:.*?<a href=".*?" target="_blank">(.*?)</a>}m).to_s,
21       :city    => raw.scan(%r{City:.*?<td align="left" class="arial_bold">(.*?)</td>}m).to_s
22     }
23   end
24 end
25
26 class GeoIpPlugin < Plugin
27   def help(plugin, topic="")
28     "geoip [<user|hostname|ip>] => returns the geographic location of whichever has been given"
29   end
30
31   def geoip(m, params)
32     if params.empty?
33       m.reply host2output(m.source.host, m.source.nick)
34     else
35       if m.replyto.class == Channel
36         # check if there is an user with nick same as input given
37         user = m.replyto.users.find { |user| user.nick == params[:input] }
38
39         if user
40           m.reply host2output(user.host, user.nick)
41           return
42         end
43       end
44
45       if params[:input] =~ /[a-z0-9\-]+(?:\.[a-z0-9\-]+)*\.[a-z]{2,3}/i ||
46          params[:input] =~ Resolv::IPv4::Regex
47         m.reply host2output(params[:input])
48       else
49         m.reply "invalid input"
50       end
51     end
52   end
53
54   def host2output(host, nick=nil)
55     geo = GeoIP::resolve(host)
56
57     if geo[:country].empty?
58       return _("#{host} could not be resolved")
59     end
60
61     res = _("%{thing} is #{nick ? "from" : "located in"}") % {
62       :thing   => (nick ? nick : Resolv::getaddress(host)),
63       :country => geo[:country]
64     }
65
66     res << " %{city}," % {
67       :city => geo[:city]
68     } unless geo[:city].empty?
69
70     res << " %{country}" % {
71       :country => geo[:country]
72     }
73
74     res << " (%{region})" % {
75       :region  => geo[:region]
76     } unless geo[:region].empty? || geo[:region] == geo[:city]
77
78     return res
79   end
80 end
81
82 plugin = GeoIpPlugin.new
83 plugin.map "geoip [:input]", :action => 'geoip'