Created
May 3, 2012 09:20
-
-
Save orlp/2584627 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import irclib | |
| import ircbot | |
| import socket | |
| import collections | |
| import time | |
| import json | |
| import logging | |
| import pyipinfodb | |
| class IDBot(ircbot.SingleServerIRCBot): | |
| def __init__(self, server, channel, nick, password, data_file, logfile, geo_api_key): | |
| ircbot.SingleServerIRCBot.__init__(self, [server], nick, nick, 10) | |
| self.channel_target = channel | |
| self.user_aliases = collections.defaultdict(set) | |
| self.online_times = {} | |
| self.last_online_check = time.time() | |
| self.user_info = {} | |
| self.data_file = data_file | |
| self.nick = nick | |
| self.password = password | |
| self.geo_lookup = pyipinfodb.IPInfo(geo_api_key) | |
| filehandler = logging.FileHandler(filename = logfile) | |
| filehandler.setLevel(logging.WARNING) | |
| self.logger = logging.getLogger("IDBot" + logfile) | |
| self.logger.addHandler(filehandler) | |
| self.logger.warning("starting up") | |
| self.load_data() | |
| # join target channel when we join the server | |
| def on_welcome(self, connection, event): | |
| if irclib.is_channel(self.channel_target): | |
| connection.join(self.channel_target) | |
| else: | |
| self.connection.quit("") | |
| if self.password: | |
| self.connection.privmsg("NickServ", "identify %s %s" % (self.nick, self.password)) | |
| # just keep trying | |
| def on_nicknameinuse(self, conn, event): | |
| conn.nick(conn.get_nickname() + "_") | |
| # handle commands | |
| def on_pubmsg(self, conn, event): | |
| message = event.arguments()[0] | |
| if message.startswith("whois"): | |
| target = message[len("whois "):] | |
| if target and target in self.user_info: | |
| self.update_online_times() | |
| ip = self.user_info[target][1] | |
| aliases = list(reversed(sorted(self.user_aliases[ip], key = lambda x: self.online_times[ip][x])))[:5] | |
| aliases = [(alias, self.online_times[ip][alias] / 3600) for alias in aliases] | |
| self.connection.privmsg(self.channel_target, "Name: " + target) | |
| self.connection.privmsg(self.channel_target, "IP: " + ip) | |
| try: | |
| location = self.geo_lookup.GetCountry(ip) | |
| self.connection.privmsg(self.channel_target, "Country: %s" % location["CountryName"]) | |
| except: | |
| self.logger.error("Couldn't find geo location for %s" % ip) | |
| self.connection.privmsg(self.channel_target, "Uses aliases: %s" % ", ".join("%s (%.1f h)" % alias for alias in aliases)) | |
| if message.startswith("whoisip"): | |
| ip = message[len("whoisip "):] | |
| if ip and ip in self.user_aliases: | |
| aliases = list(reversed(sorted(self.user_aliases[ip], key = lambda x: self.online_times[ip][x])))[:5] | |
| aliases = [(alias, self.online_times[ip][alias] / 3600) for alias in aliases] | |
| self.connection.privmsg(self.channel_target, "IP: " + ip) | |
| self.connection.privmsg(self.channel_target, "Uses aliases: %s" % ", ".join("%s (%.1f h)" % alias for alias in aliases)) | |
| def on_namreply(self, conn, event): | |
| for name in event.arguments()[2].split(): | |
| self.connection.whois([name.lstrip("@")]) | |
| def on_whoisuser(self, conn, event): | |
| self.update_online_times() | |
| username, hostname = event.arguments()[0], event.arguments()[2] | |
| try: | |
| hostip = socket.gethostbyname(hostname) | |
| self.user_info[username] = (hostname, hostip) | |
| self.user_aliases[hostip].add(username) | |
| except socket.gaierror: | |
| self.logger.error("Unknown host: " + hostname) | |
| def on_join(self, conn, event): | |
| self.update_online_times() | |
| username, hostname = event.source().split("!")[0], event.source().split("@")[1] | |
| try: | |
| hostip = socket.gethostbyname(hostname) | |
| self.user_info[username] = (hostname, hostip) | |
| self.user_aliases[hostip].add(username) | |
| except socket.gaierror: | |
| self.logger.error("Unknown host: " + hostname) | |
| def on_nick(self, conn, event): | |
| self.update_online_times() | |
| previous, hostname, new = event.source().split("!")[0], event.source().split("@")[1], event.target() | |
| if previous in self.user_info: | |
| self.user_info[new] = self.user_info[previous] | |
| self.user_aliases[self.user_info[new][1]].add(new) | |
| del self.user_info[previous] | |
| else: | |
| try: | |
| hostip = socket.gethostbyname(hostname) | |
| self.user_info[new] = (hostname, hostip) | |
| self.user_aliases[hostip].add(new) | |
| except socket.gaierror: | |
| self.logger.error("Unknown host: " + hostname) | |
| def on_part(self, conn, event): | |
| self.update_online_times() | |
| del self.user_info[event.source().split("!")[0]] | |
| def update_online_times(self): | |
| now = time.time() | |
| time_elapsed = now - self.last_online_check | |
| self.last_online_check = now | |
| for username, info in self.user_info.items(): | |
| ip = info[1] | |
| if not ip in self.online_times: | |
| self.online_times[ip] = {} | |
| if not username in self.online_times[ip]: | |
| self.online_times[ip][username] = time_elapsed | |
| else: | |
| self.online_times[ip][username] += time_elapsed | |
| self.save_data() | |
| def save_data(self): | |
| with open(self.data_file, "w") as f: | |
| f.write(json.dumps([{username: list(aliases) for username, aliases in self.user_aliases.items()}, self.online_times])) | |
| def load_data(self): | |
| try: | |
| with open(self.data_file) as f: | |
| user_aliases, online_times = json.loads(f.read()) | |
| self.user_aliases = collections.defaultdict(set) | |
| for key, val in user_aliases.items(): | |
| self.user_aliases[key] = set(val) | |
| self.online_times = online_times | |
| except (IOError, ValueError): | |
| self.logger.error("Couldn't load data from %s", self.data_file) | |
| gg2bot = IDBot(("irc.esper.net", 6667), "#gg2", "NCbot", "**********", "data.txt", "error.log", "cec9da23b55b74aeee46a5da8f10796f0794125c26b82df0eba22cd42d14b868") | |
| gg2bot.start() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # Copyright (c) 2010, Westly Ward | |
| # All rights reserved. | |
| # | |
| # Redistribution and use in source and binary forms, with or without | |
| # modification, are permitted provided that the following conditions are met: | |
| # * Redistributions of source code must retain the above copyright | |
| # notice, this list of conditions and the following disclaimer. | |
| # * Redistributions in binary form must reproduce the above copyright | |
| # notice, this list of conditions and the following disclaimer in the | |
| # documentation and/or other materials provided with the distribution. | |
| # * Neither the name of the pyipinfodb nor the | |
| # names of its contributors may be used to endorse or promote products | |
| # derived from this software without specific prior written permission. | |
| # | |
| # THIS SOFTWARE IS PROVIDED BY Westly Ward ''AS IS'' AND ANY | |
| # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | |
| # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
| # DISCLAIMED. IN NO EVENT SHALL Westly Ward BE LIABLE FOR ANY | |
| # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |
| # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
| # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |
| # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
| # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |
| # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| import json, urllib, urllib2, socket | |
| class IPInfo() : | |
| def __init__(self, apikey) : | |
| self.apikey = apikey | |
| def GetIPInfo(self, baseurl, ip=None, timezone=False) : | |
| """Same as GetCity and GetCountry, but a baseurl is required. This is for if you want to use a different server that uses the the php scripts on ipinfodb.com.""" | |
| passdict = {"output":"json", "key":self.apikey} | |
| if ip : | |
| try : | |
| passdict["ip"] = socket.gethostbyaddr(ip)[2][0] | |
| except : passdict["ip"] = ip | |
| if timezone : | |
| passdict["timezone"] = "true" | |
| else : | |
| passdict["timezone"] = "false" | |
| urldata = urllib.urlencode(passdict) | |
| url = baseurl + "?" + urldata | |
| urlobj = urllib2.urlopen(url) | |
| data = urlobj.read() | |
| urlobj.close() | |
| datadict = json.loads(data) | |
| return datadict | |
| def GetCity(self, ip=None, timezone=False) : | |
| """Gets the location with the context of the city of the given IP. If no IP is given, then the location of the client is given. The timezone option defaults to False, to spare the server some queries.""" | |
| baseurl = "http://api.ipinfodb.com/v2/ip_query.php" | |
| return self.GetIPInfo(baseurl, ip, timezone) | |
| def GetCountry(self, ip=None, timezone=False) : | |
| """Gets the location with the context of the country of the given IP. If no IP is given, then the location of the client is given. The timezone option defaults to False, to spare the server some queries.""" | |
| baseurl = "http://api.ipinfodb.com/v2/ip_query_country.php" | |
| return self.GetIPInfo(baseurl, ip, timezone) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment