diff --git a/.gitignore b/.gitignore index efaa6a2..e838aa1 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,6 @@ pip-log.txt #Data files data + +# Swap files +*.sw[po] diff --git a/RepBot.py b/RepBot.py deleted file mode 100755 index ba85cb4..0000000 --- a/RepBot.py +++ /dev/null @@ -1,264 +0,0 @@ -#!/usr/bin/python - -import yaml -import time -import re - -from twisted.words.protocols import irc -from twisted.internet import protocol, reactor, ssl -from twisted.internet.task import LoopingCall - -from repsys import ReputationSystem -from repcmds import get_rep_change -import admin - -def canonical_name(user): - return re.split(r"[\|`:]", user)[0].lower() - -def ident_to_name(name): - return name.split("!", 1)[0] - -def normalize_config(cfgFilename): - # Default settings - ret = { - "reps": "data/reps.txt", - "ignore": [], - "admins": [], - "replimit": 5, - "timelimit": 5.0 * 60.0, - "privonly": False, - "autorespond": False, - "nick": "RepBot", - "realname": "Reputation Bot", - "servname": "Reputation Bot", - "channels": [], - "server": "", - "port": 6667, - "ssl": False, - "spy": False, - "report": { - "channels": [], - "delay": 60*60 - }, - "savespeed": 3*60*60, - "topprivate": True - } - # Add the new stuff - ret.update(yaml.safe_load(open(cfgFilename))) - # Write the full config file, so they have a full listing - with open(cfgFilename,'w') as of: - yaml.dump(ret, of, default_flow_style=False) - # Fix set information - ret["ignore"] = sorted(set(ret["ignore"])) - ret["admins"] = sorted(set(ret["admins"])) - ret["report"]["channels"] = sorted(set(ret["report"]["channels"])) - ret["nick"] = ret["nick"].decode('ascii') - - def cleanup(item): - if isinstance(item, dict): - return {name:cleanup(val) for name, val in item.items()} - elif isinstance(item, list): - return [cleanup(x) for x in item] - elif isinstance(item, basestring): - return str(item) - else: - return item - return cleanup(ret) - - -class RepBot(irc.IRCClient): - - def __init__(self, cfg): - self.version = "0.12.0" - self.cfg = cfg - - self.users = {} - self.reps = ReputationSystem(cfg["reps"]) - self.loops = {} - - # Instance variables for irc.IRCClient - self.nickname = cfg["nick"] - self.realname = cfg["realname"] - self.sourceURL = "http://github.com/msoucy/RepBot" - self.versionName = "RepBot" - self.versionNum = self.version - - self.rebuild_wildcards() - self.changed = False - self.saver = LoopingCall(self.save) - self.saver.start(self.cfg["savespeed"]) - - def signedOn(self): - print "Signed on as {0}.".format(self.cfg["nick"]) - for chan in self.cfg["channels"]: - self.join(chan) - - def irc_unknown(self, prefix, command, params): - if command == "INVITE": - self.log("Invite to {1} from {0}".format(prefix, params[1])) - self.join(params[1]) - - def joined(self, channel): - print "Joined {0}.".format(channel) - - def log(self, msg): - print time.asctime(), msg - - def save(self): - if not self.changed: return - self.changed = False - self.reps.dump() - with open("data/settings.txt", "w") as fi: - yaml.dump(cfg, fi, default_flow_style=False) - self.log("Saved data") - - def rebuild_wildcards(self): - def wildcard_regex(w): - return w.replace('.','\\.').replace('?','.').replace('*','.*?') - def regex_list(l): - return [re.compile(wildcard_regex(x)) for x in l] - self.adminList = regex_list(self.cfg["admins"]) - self.ignoreList = regex_list(self.cfg["admins"]) - - def hasadmin(self, user): - for adm in self.adminList: - if adm.match(user): - return True - return False - - def ignores(self, user): - for ig in self.ignoreList: - if ig.match(user): - return True - return False - - def handleChange(self, user, changer): - name = changer.getUser() - if name == canonical_name(user): - self.msg(user, "Cannot change own rep") - return - currtime = time.time() - # Filter old uses - self.users[user] = [val - for val in self.users.get(user, []) - if (currtime - val) < self.cfg["timelimit"]] - if len(self.users[user]) < self.cfg["replimit"]: - self.reps.apply(changer) - self.users[user].append(currtime) - self.changed = True - else: - self.msg(user, "You have reached your rep limit. You can give more rep in {0} seconds" - .format(int(self.cfg["timelimit"] - (currtime - self.users[user][-1])))) - - def report(self, chan): - admin.admin(self, chan, "report force") - - def repcmd(self, user, channel, msg): - # Respond to private messages privately - if channel == self.cfg["nick"]: - channel = user - - args = msg.split() - cmd = args[0] if args else "" - args = args[1:] if args else [] - changer = get_rep_change(msg) - - if changer != None: - self.handleChange(user, changer) - elif cmd in ("rep",): - self.msg(channel, self.reps.tell(canonical_name(args[0] if args else user))) - elif cmd in ("top", "report"): - self.msg(user if self.cfg["topprivate"] else channel, self.reps.report(True)) - elif cmd in ("ver", "version", "about"): - self.msg(channel, 'I am RepBot version {0}'.format(self.version)) - elif cmd in ("help",): - self.msg( - channel, - 'Message me with "!rep " to get the reputation of ') - self.msg( - channel, - 'Use prefix or postfix ++/-- to change someone\'s rep. You are not able to change your own rep.') - self.msg( - channel, - 'Message me with "!version" to see my version number') - elif self.cfg["autorespond"] and channel == user: - # It's not a valid command, so let them know - # Only respond privately - self.msg( - user, - 'Invalid command. MSG me with !help for information') - - def privmsg(self, ident, channel, msg): - if not ident: - return - - try: - msg = msg.decode("utf-8") - except UnicodeDecodeError as ue: - self.log("Received non-unicode message") - return - isAdmin = False - if msg.startswith('!'): - # It's a command to RepBot itself - msg = msg[1:] - elif channel != self.cfg["nick"] and msg.startswith(self.cfg["nick"] + ":"): - # It's a command to RepBot itself - msg = msg[len(self.cfg["nick"]) + 1:].strip() - elif self.hasadmin(ident) and channel == self.cfg["nick"]: - # They have admin access, check for commands - if msg.startswith("admin"): - msg = msg.replace("admin", "", 1) - elif msg.startswith("@"): - msg = msg[1:] - else: - return - isAdmin = True - elif get_rep_change(msg) == None: - # It doesn't match a rep change - return - - user = ident_to_name(ident) - if self.ignores(ident) and not self.hasadmin(ident): - self.msg( - user, - "You have been blocked from utilizing my functionality.") - - if self.cfg["spy"]: - self.log("[{1}]\t{0}:\t{2}".format(ident, channel, msg)) - - if isAdmin: - admin.admin(self, user, msg) - elif channel == self.cfg["nick"] or not self.cfg["privonly"]: - # I'm just picking up a regular chat - # And we aren't limited to private messages only - self.repcmd(user, channel, msg) - - -class RepBotFactory(protocol.ClientFactory): - - def __init__(self, cfg): - self.cfg = cfg - - def buildProtocol(self, addr): - return RepBot(self.cfg) - - def clientConnectionLost(self, connector, reason): - print "Lost connection (%s), reconnecting." % (reason,) - connector.connect() - - def clientConnectionFailed(self, connector, reason): - print "Could not connect: %s" % (reason,) - -if __name__ == "__main__": - cfg = normalize_config("data/settings.txt") - server = cfg["server"] - port = cfg["port"] - factory = RepBotFactory(cfg) - print "Connecting to {0}:{1}".format(server, port) - if cfg["ssl"]: - print "Using SSL" - reactor.connectSSL(server, port, factory, ssl.ClientContextFactory()) - else: - print "Not using SSL" - reactor.connectTCP(server, port, factory) - reactor.run() diff --git a/RepBot/ReputationBot.py b/RepBot/ReputationBot.py new file mode 100644 index 0000000..1e686d4 --- /dev/null +++ b/RepBot/ReputationBot.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +from __future__ import print_function + +import yaml +import time +import re + +from repcmds import get_rep_change +import admin + +class ReputationBot: + + def __init__(self, repsys): + self.version = "0.13.0" + self.repsys = repsys + + def log(self, msg): + print(time.asctime(), msg) + + def save(self): + self.repsys.save() + + def handle(self, frontend, user, changer): + name = changer.getUser() + if name == frontend.canonical_name(user): + frontend.send_to(user, "Cannot change own rep") + else: + self.repsys.apply(changer) + + def admin(self, source, cmd): + admin.admin(self, source, cmd) + + def repcmd(self, frontend, source, msg, replyto=None): + + replyto = replyto or source + + args = msg.split() + cmd, args = (args[0], args[1:]) if args else ("",[]) + changer = get_rep_change(msg) + send = lambda msg: frontend.send_to(replyto, msg) + + if changer: + frontend.handle(source, changer) + elif cmd in ("rep",): + name = frontend.canonical_name(args[0] if args else source) + send("Rep for {0}: {1}".format(name, self.repsys.get(name))) + elif cmd in ("top", "report"): + send(self.repsys.report()) + elif cmd in ("ver", "version", "about"): + send('I am RepBot version {0}'.format(self.version)) + elif cmd in ("help",): + frontend.send_help(replyto) + elif source == replyto: + # It's not a valid command, so let them know + # Only respond privately + send('Invalid command. MSG me with !help for information') diff --git a/RepBot/TwistedIRCBot.py b/RepBot/TwistedIRCBot.py new file mode 100644 index 0000000..ae4436a --- /dev/null +++ b/RepBot/TwistedIRCBot.py @@ -0,0 +1,180 @@ +#!/usr/bin/python + +import time +import re + +from twisted.words.protocols import irc +from twisted.internet import protocol, reactor, ssl +from twisted.internet.task import LoopingCall + +from .repcmds import get_rep_change +from .admin import admin, get_command +from .modules import Module + +def ident_to_name(name): + return name.split("!", 1)[0] + +class RepBot(irc.IRCClient): + + def __init__(self, cfg, bot): + self.version = "0.13.0" + self.cfg = cfg + + self.users = {} + + # Instance variables for irc.IRCClient + self.nickname = cfg.nick + self.realname = cfg.realname + self.sourceURL = "http://github.com/msoucy/RepBot" + self.versionName = "RepBot" + self.versionNum = self.version + + self.rebuild_wildcards() + self.changed = False + self.saver = LoopingCall(self.save) + self.saver.start(self.cfg.savespeed) + + self.bot = bot + + def signedOn(self): + print "Signed on as {0}.".format(self.nickname) + for chan in self.cfg["channels"]: + self.join(chan) + + def irc_unknown(self, prefix, command, params): + if command == "INVITE": + self.log(u"Invite to {1} from {0}".format(prefix, params[1])) + self.join(params[1]) + + def joined(self, channel): + print "Joined {0}.".format(channel) + + def log(self, msg): + print time.asctime(), msg + + def save(self): + if not self.changed: return + self.changed = False + self.cfg.save() + self.log("Saved data") + + def rebuild_wildcards(self): + def wildcard_regex(w): + return w.replace('.','\\.').replace('?','.').replace('*','.*?') + def regex_list(l): + return [re.compile(wildcard_regex(x)) for x in l] + self.adminList = regex_list(self.cfg.admins) + self.ignoreList = regex_list(self.cfg.ignore) + + def hasadmin(self, user): + return any(u.match(user) for u in self.adminList) + + def ignores(self, user): + return any(u.match(user) for u in self.ignoreList) + + def handle(self, user, changer): + currtime = time.time() + # Filter old uses + self.users[user] = [val + for val in self.users.get(user, []) + if (currtime - val) < self.cfg.timelimit] + if len(self.users[user]) < self.cfg.replimit: + self.log("User %s caused rep change" % user) + self.bot.handle(self, user, changer) + self.users[user].append(currtime) + self.changed = True + else: + self.log("User %s triggered rep limit" % user) + self.send_to(user, "You have reached your rep limit. You can give more rep in {0} seconds" + .format(int(self.cfg.timelimit - (currtime - self.users[user][-1])))) + + def report(self, chan): + admin(self, chan, "report") + + def send_to(self, dest, *args, **kwargs): + return self.msg(dest, *[a.encode("utf-8") for a in args], **kwargs) + + def send_help(self, user): + send = lambda msg: self.send_to(user, msg) + send('Message me with "!rep " to get the reputation of ') + send('Use prefix or postfix ++/-- to change someone\'s rep.') + send('You are not able to change your own rep.') + send('Message me with "!version" to see my version number') + + def canonical_name(self, user): + return re.split(r"[\|`:]", user)[0].lower() + + def privmsg(self, ident, channel, msg): + if not ident: + return + + try: + msg = msg.decode("utf-8") + except UnicodeDecodeError as ue: + self.log("Received non-unicode message") + return + admincmd = None + if msg.startswith('!'): + # It's a command to RepBot itself + msg = msg[1:] + elif channel != self.nickname and msg.startswith(self.nickname + ":"): + # It's a command to RepBot itself + msg = msg[len(self.nickname) + 1:].strip() + elif self.hasadmin(ident) and channel == self.nickname: + # They have admin access, check for commands + admincmd = get_command(msg) + elif get_rep_change(msg) == None: + # It doesn't match a rep change + return + + user = ident_to_name(ident) + if self.ignores(ident) and not self.hasadmin(ident): + self.msg( + user, + "You have been blocked from utilizing my functionality.") + + if self.cfg.spy: + self.log(u"[{0}]\t{1}:\t{2}".format(channel, ident, msg)) + + if admincmd: + admin(self, user, admincmd) + elif channel == self.nickname or not self.cfg.privonly: + # I'm just picking up a regular chat + # And we aren't limited to private messages only + self.bot.repcmd(self, user, msg, channel if channel != self.nickname else None) + + +class RepBotFactory(protocol.ClientFactory): + + def __init__(self, cfg, bot): + self.cfg = cfg + self.bot = bot + + def buildProtocol(self, addr): + return RepBot(self.cfg, self.bot) + + def clientConnectionLost(self, connector, reason): + print "Lost connection (%s), reconnecting." % (reason,) + connector.connect() + + def clientConnectionFailed(self, connector, reason): + print "Could not connect: %s" % (reason,) + +class TwistedIRCModule(Module("irc")): + + def __init__(self, cfg, backend): + server, port = cfg.server, cfg.port + factory = RepBotFactory(cfg, backend) + print "Connecting to {0}:{1}".format(server, port) + if cfg.ssl: + print "Using SSL" + reactor.connectSSL(server, port, factory, ssl.ClientContextFactory()) + else: + print "Not using SSL" + reactor.connectTCP(server, port, factory) + + def start(self): + reactor.run() + + def term(self): + reactor.stop() diff --git a/RepBot/__init__.py b/RepBot/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/RepBot/__main__.py b/RepBot/__main__.py new file mode 100644 index 0000000..0ef9d0b --- /dev/null +++ b/RepBot/__main__.py @@ -0,0 +1,12 @@ +#!/usr/bin/python + +from .backend_yaml import ReputationSystemYAML +from .config import Config +from .ReputationBot import ReputationBot +from .TwistedIRCBot import TwistedIRCModule + +if __name__ == "__main__": + cfg = Config("data/settings.txt") + bot = ReputationBot(ReputationSystemYAML(cfg.reps)) + mod = TwistedIRCModule(cfg, bot) + mod.start() diff --git a/RepBot/admin.py b/RepBot/admin.py new file mode 100644 index 0000000..e017ad7 --- /dev/null +++ b/RepBot/admin.py @@ -0,0 +1,252 @@ +#!/usr/bin/python + +from ast import literal_eval +import json +import re +from fuf import ActionSet +from twisted.internet import reactor +from twisted.internet.task import LoopingCall + +def get_channel_arg(channel, args): + if args and args[0].startswith(('#', '&', '+', '!')): + channel = args.pop(0) + return channel + + +Action = ActionSet("Action_") + + + +@Action +def Action_help(bot, user, *cmds): + """List command help""" + if cmds: + for cmds in cmds: + a = Action[arg] + if a: + bot.send_to(user, "{0.name}:\t{0.helpmsg}".format(a)) + else: + bot.send_to(user, " ".join(a for a in Action)) + + +@Action +def Action_verify(bot, user): + """Confirm admin access""" + bot.send_to(user, "Authentication valid") + + +@Action +def Action_admin(bot, user, cmd, *args): + """Adjust user admin access""" + if cmd == "list": + bot.send_to(user, str(list(bot.cfg["admins"]))) + elif not args: + bot.send_to(user, "Admin change failed: too few arguments") + elif cmd == "add": + bot.cfg["admins"] = sorted(set(bot.cfg["admins"]) | set(args)) + elif cmd in ("remove", "rm"): + bot.cfg["admins"] = sorted(set(bot.cfg["admins"]) - set(args)) + else: + bot.send_to(user, "Admin change failed: unknown action") + bot.rebuild_wildcards() + + +@Action +def Action_ignore(bot, user, cmd, *args): + """Adjust ignore list""" + if cmd == "list": + bot.send_to(user, str(list(bot.cfg["ignores"]))) + elif not args: + bot.send_to(user, "Admin change failed: too few arguments") + elif cmd == "add": + bot.cfg["ignores"] = sorted(set(bot.cfg["ignores"]) | set(args)) + elif cmd in ("remove", "rm"): + bot.cfg["ignores"] = sorted(set(bot.cfg["ignores"]) - set(args)) + else: + bot.send_to(user, "Ignore change failed: unknown action") + bot.rebuild_wildcards() + +@Action +def Action_cfg(bot, user, setting, *args): + """Control a config setting""" + if args: + bot.send_to(user, "{0} = {1}".format(setting, bot.cfg.get(setting))) + elif len(args) == 1: + newval = literal_eval(args[1]) + if type(newval) == type(bot.cfg.get(setting)): + bot.cfg[setting] = newval + # I know, a sad little hack for now. + if setting == "savespeed": + bot.saver.stop() + bot.saver.start(newval) + elif setting == "report" and len(args) == 2: + newval = literal_eval(args[1]) + if type(newval) == type(bot.cfg["report"].get(args[0])): + bot.cfg["report"][args[0]] = newval + else: + bot.send_to(user, "Invalid config setting change") + +@Action +def Action_dump(bot, user): + bot.reps.save() + bot.log("Rep file dumped") + + +@Action +def Action_save(bot, user): + """Save all bot information""" + bot.save() + + +@Action +def Action_load(bot, user): + """Load database from a file""" + bot.reps.load() + bot.log("Rep file loaded") + + +@Action +def Action_filter(bot, user): + """Remove unused entries""" + bot.reps.filter() + bot.log("Filtered zeroed entries") + + +@Action +def Action_clear(bot, user, *args): + """Remove the given names from the system""" + if args == ["all"]: + bot.reps.reps = {} + else: + for name in args: + bot.reps.set(name, 0) + + +@Action +def Action_tell(bot, user, *args): + """Tell a channel rep information for users""" + user = get_channel_arg(user, args) + for name in args: + bot.send_to(user, bot.reps.tell(name)) + + +@Action +def Action_all(bot, user, dest=None): + """Get all reputations""" + dest = dest or user + bot.send_to(user, bot.reps.all()) + + +@Action +def Action_limit(bot, user, cmd, *args): + """Adjust limits""" + if len(args) < 2: + bot.send_to(user, "Limit change failed: too few arguments") + return + if cmd == "rep": + if args: + bot.cfg["replimit"] = int(args[0]) + else: + bot.send_to(user, "Rep limit: {0}".format(bot.cfg["replimit"])) + elif cmd == "time": + if args: + bot.cfg["timelimit"] = int(args[0]) + else: + bot.send_to(user, "Time limit: {0}".format(bot.cfg["timelimit"])) + else: + bot.send_to(user, "Limit change failed: unknown limit") + + +@Action +def Action_set(bot, user, nick, value): + """Manually set a user's rep value""" + bot.bot.repsys.set(nick, int(value)) + + +@Action +def Action_allow(bot, user, *args): + """Clear rep timeout restrictions for all given users""" + for name in args: + bot.users[name] = [] + + +@Action +def Action_term(bot, user, *msg): + """Safely terminate""" + bot.save() + for chan in bot.cfg["channels"]: + bot.leave(chan, " ".join(msg)) + bot.quit(" ".join(msg)) + reactor.stop() + + +@Action +def Action_join(bot, user, *chans): + """Join a channel""" + for chan in chans: + bot.join(chan) + bot.cfg["channels"].append(chan) + bot.cfg["channels"] = sorted(set(bot.cfg["channels"])) + + +@Action +def Action_part(bot, user, *chars): + """Leave a channel""" + for chan in chars: + bot.leave(chan) + bot.cfg["channels"].remove(chan) + +@Action +def Action_autoreport(bot, user, args): + """Automatically report to a channel""" + channels = bot.cfg["report"]["channels"] + for chan in args: + if chan in bot.loops: + bot.loops.pop(chan).stop() + channels.remove(chan) + else: + bot.loops[chan] = LoopingCall(lambda:bot.report(chan)) + bot.loops[chan].start(bot.cfg["report"]["delay"]) + channels.append(chan) + +@Action +def Action_report(bot, user, dest=None): + """Generate a report""" + bot.send_to(dest or user, bot.reps.report()) + +@Action +def Action_as(bot, user, fakeuser, *cmd): + """Spoof a message as a user""" + if not cmd: + bot.send_to(user, "as failed: Not enough information") + else: + bot.privmsg(fakeuser,fakeuser," ".join(cmd)) + +@Action +def Action_say(bot, user, dest, *msg): + """Say a message""" + if not msg: + bot.send_to(user, "Not enough arguments") + bot.send_to(dest, " ".join(msg)) + +class get_command(object): + def __init__(self): + self.reg = re.compile(r'^(@|(?:admin\s+))(?:!(?P[a-zA-Z_]\w*))?\s*(?P\S+)\s*(?P.*)$') + def __call__(self, msg): + mat = self.reg.match(msg) + if mat: + return mat.groupdict() + return None +get_command = get_command() + +def admin(bot, user, command): + cmd = command["cmd"] + args = command["args"] + if cmd in Action: + try: Action[cmd](bot, user, *(args.split())) + except: + bot.send_to(user, "Can't run that admin command with arguments: {}".format(args.split())) + raise + else: + print "Invalid command {0}".format(command) + diff --git a/RepBot/backend_yaml.py b/RepBot/backend_yaml.py new file mode 100644 index 0000000..995e72b --- /dev/null +++ b/RepBot/backend_yaml.py @@ -0,0 +1,68 @@ +import json +import operator +import os.path + +from .interfaces import ReputationInterface + +REPFILE = "data/reps.txt" + +class ReputationSystemYAML(ReputationInterface): + __slots__ = ('reps', 'ignorelist', 'cached', 'repfile') + + def __init__(self, repfile=REPFILE): + self.reps = {} + self.ignorelist = set() + self.repfile = os.path.normpath(repfile) + self.load() + self.filter() + + ####################################################################################### + # ReputationInterface + + def save(self): + self.filter() + with open(self.repfile, "w") as fi: + json.dump(self.reps, fi, sort_keys=True, indent=4, separators=(',', ': ')) + + def load(self): + if not os.path.exists(self.repfile): + self.reps = {} + else: + with open(self.repfile) as fi: + self.reps = json.load(fi) + + def get(self, name): + return self.reps.get(name, 0) + + def apply(self, changer): + self.reps[changer.getUser()] = changer.perform(self.get(changer.getUser())) + + def set(self, name, val): + self.reps[name] = int(val) + + def top(self, N=5): + sorted_reps = sorted(self.reps.iteritems(), + key=operator.itemgetter(1), + reverse=True) + highest = sorted_reps[:N] + lowest = sorted_reps[-N:] + return (highest, lowest) + + ####################################################################################### + # Extra systems + + def filter(self): + self.reps = {key: val for key, val in self.reps.items() if val != 0} + + def report(self): + self.filter() + highest, lowest = self.top() + val = lambda name, score: "{0}: {1}".format(name.encode('unicode-escape'), score) + return "Top reps: {0}\nBottom reps: {1}".format( + ", ".join(val(name, score) for name, score in highest), + ", ".join(val(name, score) for name, score in lowest)) + + def tell(self, name): + self.filter() + return "Rep for {0}: {1}".format(name.encode('unicode-escape'), self.get(name)) + diff --git a/RepBot/config.py b/RepBot/config.py new file mode 100644 index 0000000..ef73886 --- /dev/null +++ b/RepBot/config.py @@ -0,0 +1,81 @@ +#!/usr/bin/python + +import yaml +import os.path + +class Config(object): + + def __init__(self, filename): + self._filename = filename + self._data = {} + self.load() + + def __getitem__(self, name): + return self._data[name] + + def __getattr__(self, name): + if name.startswith('_'): + return super(Config, self).__getattr__(name, value) + else: return self._data[name] + + def __setitem__(self, name, value): + self._data[name] = value + return self._data[name] + + def __setattr__(self, name, value): + if name.startswith('_'): + super(Config, self).__setattr__(name, value) + return + self._data[name] = value + return self._data[name] + + def save(self): + with open(self._filename, "w") as fi: + yaml.dump(self._data, fi, default_flow_style=False) + + def load(self): + # Default settings + ret = { + "reps": "data/reps.txt", + "ignore": [], + "admins": [], + "replimit": 5, + "timelimit": 5.0 * 60.0, + "privonly": False, + "autorespond": False, + "nick": "RepBot", + "realname": "Reputation Bot", + "servname": "Reputation Bot", + "channels": [], + "server": "", + "port": 6667, + "ssl": False, + "spy": False, + "report": { + "channels": [], + "delay": 60*60 + }, + "savespeed": 3*60*60, + "topprivate": True + } + # Add the new stuff + if os.path.exists(self._filename): + ret.update(yaml.safe_load(open(self._filename))) + # Fix set information + ret["ignore"] = sorted(set(ret["ignore"])) + ret["admins"] = sorted(set(ret["admins"])) + ret["report"]["channels"] = sorted(set(ret["report"]["channels"])) + ret["nick"] = ret["nick"].decode('ascii') + + def cleanup(item): + if isinstance(item, dict): + return {name:cleanup(val) for name, val in item.items()} + elif isinstance(item, list): + return [cleanup(x) for x in item] + elif isinstance(item, basestring): + return str(item) + else: + return item + self._data = cleanup(ret) + # Write the full config file, so they have a full listing + self.save() diff --git a/RepBot/interfaces.py b/RepBot/interfaces.py new file mode 100644 index 0000000..bf9575b --- /dev/null +++ b/RepBot/interfaces.py @@ -0,0 +1,41 @@ +import abc + +class Frontend(object): + 'Abstract Frontend implementation' + def send_to(self, target, msg): + raise NotImplementedError + def send_help(self): + raise NotImplementedError + def send_rep(self, target, name, rep): + raise NotImplementedError + def send_report(self, target, reps): + raise NotImplementedError + +class ReputationInterface(object): + + __metaclass__ = abc.ABCMeta + + @abc.abstractmethod + def save(self): + 'Force a save to the backend' + + @abc.abstractmethod + def load(self): + 'Force a reload from the backend' + + @abc.abstractmethod + def get(self, name): + "Get the reputation for a name" + + @abc.abstractmethod + def apply(self, changer): + "Applies the given changer to the given name" + + @abc.abstractmethod + def set(self, name, value): + "Force sets a name's reputation" + + @abc.abstractmethod + def top(self, N=5): + 'Get the top (and bottom) N reputations' + diff --git a/RepBot/modules.py b/RepBot/modules.py new file mode 100644 index 0000000..1c5cf8c --- /dev/null +++ b/RepBot/modules.py @@ -0,0 +1,54 @@ +# Module system +# Components can register with the module system +# Admin commands go through this +# Also provides the mapping of frontends to backends + +from .interfaces import Frontend +from fuf import ActionSet + +class Modules(object): + def __new__(cls, *args, **kwargs): + if not hasattr(cls, "_instance"): + cls._instance = super(Modules, cls).__new__(cls) + return cls._instance + + def __init__(self): + self._types = {} + self._modules = {} + self._backends = {} + + def register(self, tname, t): + if tname in self._types: + raise KeyError("{} already in module type registry".format(tname)) + self._types[tname] = t + + def create(self, name, tname, cfg): + if tname not in self._types: + raise KeyError("{} not in module type registry".format(tname)) + modtype = self._types[tname] + if issubclass(modtype, Frontend): + mod = modtype(cfg, self.get(cfg.backend)) + else: + mod = modtype(cfg) + self._modules[name] = mod + + def get(self, name): + if name in self._modules: + return self._modules[name] + elif name in self._backends: + return self._backends[name] + raise KeyError("{} not in module registry".format(name)) + + __getitem__ = get + +def Module(modname=None): + class _ModuleMetaClass(type): + def __new__(cls, name, bases, attrs): + cls = type.__new__(cls, name, bases, dict(attrs, action=ActionSet())) + Modules().register(modname or name, cls) + return cls + return _ModuleMetaClass('Module', (object, ), {}) + +def Frontend(modname=None): + class _Module(Module(modname)): pass + diff --git a/repcmds.py b/RepBot/repcmds.py old mode 100755 new mode 100644 similarity index 100% rename from repcmds.py rename to RepBot/repcmds.py diff --git a/admin.py b/admin.py deleted file mode 100644 index d0465d4..0000000 --- a/admin.py +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/bin/python - -import ast -import json -from twisted.internet import reactor -from twisted.internet.task import LoopingCall - -def get_channel_arg(channel, args): - if args and args[0].startswith(('#', '&', '+', '!')): - channel = args[0] - args.pop(0) - return channel - - -adminActions = {} - - -def Action(name, helpmsg): - class ActionClass(object): - __slots__ = ('name', 'helpmsg', 'cmd') - - def __init__(self, f): - self.name = name - self.helpmsg = helpmsg - self.cmd = f - adminActions[name] = self; - - def __call__(self, *args, **kwargs): - return self.cmd(*args, **kwargs) - return ActionClass - - -@Action("help", "List command help") -def Action_help(bot, user, args): - if args: - for arg in args: - a = adminActions.get(arg) - if a: - bot.msg(user, "{0}:\t{1}".format(a.name, a.helpmsg)) - else: - bot.msg( - user, - " ".join(a for a in adminActions)) - - -@Action("verify", "Confirm admin access") -def Action_verify(bot, user, args): - bot.msg(user, "Authentication valid") - - -@Action("admin", "Adjust user admin access") -def Action_admin(bot, user, args): - if len(args) < 2 and args[0] != "list": - bot.msg(user, "Admin change failed: too few arguments") - return - cmd = args[0] - args = args[1:] - if cmd == "add": - bot.cfg["admins"] = sorted(set(bot.cfg["admins"]) | set(args)) - elif cmd in ("remove", "rm"): - bot.cfg["admins"] = sorted(set(bot.cfg["admins"]) - set(args)) - elif cmd == "list": - bot.msg(user, str(list(bot.cfg["admins"]))) - else: - bot.msg(user, "Admin change failed: unknown action") - bot.rebuild_wildcards() - - -@Action("ignore", "Adjust ignore list") -def Action_ignore(bot, user, args): - if len(args) < 1: - bot.msg(user, "Ignore change failed: too few arguments") - return - cmd = args[0] - args = args[1:] - if cmd == "add": - bot.cfg["ignore"] = sorted(set(bot.cfg["ignore"]) | set(args)) - elif cmd in ("remove", "rm"): - bot.cfg["ignore"] = sorted(set(bot.cfg["ignore"]) - set(args)) - elif cmd == "list": - bot.msg(user, str(list(bot.cfg["ignore"]))) - else: - bot.msg(user, "Ignore change failed: unknown action") - bot.rebuild_wildcards() - -@Action("cfg", "Control a config setting") -def Action_cfg(bot, user, args): - if len(args) == 1: - bot.msg(user, "{0} = {1}".format(args[0], bot.cfg.get(args[0]))) - elif len(args) == 2: - newval = ast.literal_eval(args[1]) - if type(newval) == type(bot.cfg.get(args[0])): - bot.cfg[args[0]] = newval - # I know, a sad little hack for now. - if args[0] == "savespeed": - bot.saver.stop() - bot.saver.start(newval) - elif args[0] == "report" and len(args) == 3: - newval = ast.literal_eval(args[2]) - if type(newval) == type(bot.cfg["report"].get(args[1])): - bot.cfg["report"][args[1]] = newval - else: - bot.msg(user, "Invalid config setting change") - -@Action("dump", "Dump database to a file") -def Action_dump(bot, user, args): - bot.reps.dump() - bot.log("Rep file dumped") - - -@Action("save", "Save all bot information") -def Action_save(bot, user, args): - bot.save() - - -@Action("load", "Load database from a file") -def Action_load(bot, user, args): - bot.reps.load() - bot.log("Rep file loaded") - - -@Action("filter", "Remove unused entries") -def Action_filter(bot, user, args): - bot.reps.filter() - bot.log("Filtered zeroed entries") - - -@Action("clear", "Remove the given names from the system") -def Action_clear(bot, user, args): - if len(args) == 1 and args[0] == "all": - bot.reps.reps = {} - else: - for name in args: - bot.reps.clear(name) - - -@Action("tell", "Tell a channel rep information for users") -def Action_tell(bot, user, args): - user = get_channel_arg(user, args) - for name in args: - bot.msg(user, bot.reps.tell(name)) - - -@Action("all", "Get all reputations") -def Action_all(bot, user, args): - user = get_channel_arg(user, args) - bot.msg(user, bot.reps.all()) - - -@Action("limit", "Adjust limits") -def Action_limit(bot, user, args): - if len(args) < 2: - bot.msg(user, "Limit change failed: too few arguments") - return - cmd = args[0] - args = args[1:] - if cmd == "rep": - if args: - bot.cfg["replimit"] = int(args[0]) - else: - bot.msg(user, "Rep limit: {0}".format(bot.cfg["replimit"])) - elif cmd == "time": - if args: - bot.cfg["timelimit"] = int(args[0]) - else: - bot.msg(user, "Time limit: {0}".format(bot.cfg["timelimit"])) - else: - bot.msg(user, "Limit change failed: unknown limit") - - -@Action("set", "Manually set a user's rep value") -def Action_set(bot, user, args): - if len(args) != 2: - bot.msg(user, "Set failed: incorrect number of arguments") - else: - bot.reps.set(args[0], args[1]) - - -@Action("allow", "Clear rep timeout restrictions for all given users") -def Action_allow(bot, user, args): - for name in args: - bot.users[name] = [] - - -@Action("apply", "Apply the Python dictionary provided to the rep database") -def Action_apply(bot, user, args): - bot.reps.update(json.loads(" ".join(args))) - - -@Action("term", "Safely terminate RepBot") -def Action_term(bot, user, args): - bot.save() - for chan in bot.cfg["channels"]: - bot.leave(chan, " ".join(args)) - bot.quit(" ".join(args)) - reactor.stop() - - -@Action("join", "Join a channel") -def Action_join(bot, user, args): - for chan in args: - bot.join(chan) - bot.cfg["channels"].append(chan) - bot.cfg["channels"] = sorted(set(bot.cfg["channels"])) - - -@Action("part", "Leave a channel") -def Action_part(bot, user, args): - for chan in args: - bot.leave(chan) - bot.cfg["channels"].remove(chan) - -@Action("autoreport", "Automatically report to a channel") -def Action_autoreport(bot, user, args): - channels = bot.cfg["report"]["channels"] - for chan in args: - if chan in bot.loops: - bot.loops.pop(chan).stop() - channels.remove(chan) - else: - bot.loops[chan] = LoopingCall(lambda:bot.report(chan)) - bot.loops[chan].start(bot.cfg["report"]["delay"]) - channels.append(chan) - -@Action("report", "Generate a report") -def Action_report(bot, user, args): - user = get_channel_arg(user, args) - forceFlag = False - if args == ["force"]: - forceFlag = True - elif args: - bot.msg(user, "Report failed: Too many arguments") - return - bot.msg(user, bot.reps.report(forceFlag)) - -@Action("as", "Spoof a message as a user") -def Action_as(bot, user, args): - if len(args)<2: - bot.msg(user, "as failed: Not enough information") - return - bot.privmsg(args[0],args[0]," ".join(args[1:])) - -@Action("say", "Say a message") -def Action_say(bot, user, args): - if len(args) < 2: - bot.msg(user, "Not enough arguments") - bot.msg(args[0], " ".join(args[1:])) - -def admin(bot, user, msg): - if not msg.strip(): - return - command = msg.split()[0].lower() - args = msg.split()[1:] - action = adminActions.get(command) - if action: - action(bot, user, args) - else: - print "Invalid command {0}".format(command) - diff --git a/distribute_setup.py b/distribute_setup.py new file mode 100644 index 0000000..c8bd18c --- /dev/null +++ b/distribute_setup.py @@ -0,0 +1,546 @@ +#!python +"""Bootstrap distribute installation + +If you want to use setuptools in your package's setup.py, just include this +file in the same directory with it, and add this to the top of your setup.py:: + + from distribute_setup import use_setuptools + use_setuptools() + +If you want to require a specific version of setuptools, set a download +mirror, or use an alternate download directory, you can do so by supplying +the appropriate options to ``use_setuptools()``. + +This file can also be run as a script to install or upgrade setuptools. +""" +import os +import shutil +import sys +import time +import fnmatch +import tempfile +import tarfile +import optparse + +from distutils import log + +try: + from site import USER_SITE +except ImportError: + USER_SITE = None + +try: + import subprocess + + def _python_cmd(*args): + args = (sys.executable,) + args + return subprocess.call(args) == 0 + +except ImportError: + # will be used for python 2.3 + def _python_cmd(*args): + args = (sys.executable,) + args + # quoting arguments if windows + if sys.platform == 'win32': + def quote(arg): + if ' ' in arg: + return '"%s"' % arg + return arg + args = [quote(arg) for arg in args] + return os.spawnl(os.P_WAIT, sys.executable, *args) == 0 + +DEFAULT_VERSION = "0.6.35" +DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/" +SETUPTOOLS_FAKED_VERSION = "0.6c11" + +SETUPTOOLS_PKG_INFO = """\ +Metadata-Version: 1.0 +Name: setuptools +Version: %s +Summary: xxxx +Home-page: xxx +Author: xxx +Author-email: xxx +License: xxx +Description: xxx +""" % SETUPTOOLS_FAKED_VERSION + + +def _install(tarball, install_args=()): + # extracting the tarball + tmpdir = tempfile.mkdtemp() + log.warn('Extracting in %s', tmpdir) + old_wd = os.getcwd() + try: + os.chdir(tmpdir) + tar = tarfile.open(tarball) + _extractall(tar) + tar.close() + + # going in the directory + subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) + os.chdir(subdir) + log.warn('Now working in %s', subdir) + + # installing + log.warn('Installing Distribute') + if not _python_cmd('setup.py', 'install', *install_args): + log.warn('Something went wrong during the installation.') + log.warn('See the error message above.') + # exitcode will be 2 + return 2 + finally: + os.chdir(old_wd) + shutil.rmtree(tmpdir) + + +def _build_egg(egg, tarball, to_dir): + # extracting the tarball + tmpdir = tempfile.mkdtemp() + log.warn('Extracting in %s', tmpdir) + old_wd = os.getcwd() + try: + os.chdir(tmpdir) + tar = tarfile.open(tarball) + _extractall(tar) + tar.close() + + # going in the directory + subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) + os.chdir(subdir) + log.warn('Now working in %s', subdir) + + # building an egg + log.warn('Building a Distribute egg in %s', to_dir) + _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) + + finally: + os.chdir(old_wd) + shutil.rmtree(tmpdir) + # returning the result + log.warn(egg) + if not os.path.exists(egg): + raise IOError('Could not build the egg.') + + +def _do_download(version, download_base, to_dir, download_delay): + egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg' + % (version, sys.version_info[0], sys.version_info[1])) + if not os.path.exists(egg): + tarball = download_setuptools(version, download_base, + to_dir, download_delay) + _build_egg(egg, tarball, to_dir) + sys.path.insert(0, egg) + import setuptools + setuptools.bootstrap_install_from = egg + + +def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, + to_dir=os.curdir, download_delay=15, no_fake=True): + # making sure we use the absolute path + to_dir = os.path.abspath(to_dir) + was_imported = 'pkg_resources' in sys.modules or \ + 'setuptools' in sys.modules + try: + try: + import pkg_resources + if not hasattr(pkg_resources, '_distribute'): + if not no_fake: + _fake_setuptools() + raise ImportError + except ImportError: + return _do_download(version, download_base, to_dir, download_delay) + try: + pkg_resources.require("distribute>=" + version) + return + except pkg_resources.VersionConflict: + e = sys.exc_info()[1] + if was_imported: + sys.stderr.write( + "The required version of distribute (>=%s) is not available,\n" + "and can't be installed while this script is running. Please\n" + "install a more recent version first, using\n" + "'easy_install -U distribute'." + "\n\n(Currently using %r)\n" % (version, e.args[0])) + sys.exit(2) + else: + del pkg_resources, sys.modules['pkg_resources'] # reload ok + return _do_download(version, download_base, to_dir, + download_delay) + except pkg_resources.DistributionNotFound: + return _do_download(version, download_base, to_dir, + download_delay) + finally: + if not no_fake: + _create_fake_setuptools_pkg_info(to_dir) + + +def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, + to_dir=os.curdir, delay=15): + """Download distribute from a specified location and return its filename + + `version` should be a valid distribute version number that is available + as an egg for download under the `download_base` URL (which should end + with a '/'). `to_dir` is the directory where the egg will be downloaded. + `delay` is the number of seconds to pause before an actual download + attempt. + """ + # making sure we use the absolute path + to_dir = os.path.abspath(to_dir) + try: + from urllib.request import urlopen + except ImportError: + from urllib2 import urlopen + tgz_name = "distribute-%s.tar.gz" % version + url = download_base + tgz_name + saveto = os.path.join(to_dir, tgz_name) + src = dst = None + if not os.path.exists(saveto): # Avoid repeated downloads + try: + log.warn("Downloading %s", url) + src = urlopen(url) + # Read/write all in one block, so we don't create a corrupt file + # if the download is interrupted. + data = src.read() + dst = open(saveto, "wb") + dst.write(data) + finally: + if src: + src.close() + if dst: + dst.close() + return os.path.realpath(saveto) + + +def _no_sandbox(function): + def __no_sandbox(*args, **kw): + try: + from setuptools.sandbox import DirectorySandbox + if not hasattr(DirectorySandbox, '_old'): + def violation(*args): + pass + DirectorySandbox._old = DirectorySandbox._violation + DirectorySandbox._violation = violation + patched = True + else: + patched = False + except ImportError: + patched = False + + try: + return function(*args, **kw) + finally: + if patched: + DirectorySandbox._violation = DirectorySandbox._old + del DirectorySandbox._old + + return __no_sandbox + + +def _patch_file(path, content): + """Will backup the file then patch it""" + f = open(path) + existing_content = f.read() + f.close() + if existing_content == content: + # already patched + log.warn('Already patched.') + return False + log.warn('Patching...') + _rename_path(path) + f = open(path, 'w') + try: + f.write(content) + finally: + f.close() + return True + +_patch_file = _no_sandbox(_patch_file) + + +def _same_content(path, content): + f = open(path) + existing_content = f.read() + f.close() + return existing_content == content + + +def _rename_path(path): + new_name = path + '.OLD.%s' % time.time() + log.warn('Renaming %s to %s', path, new_name) + os.rename(path, new_name) + return new_name + + +def _remove_flat_installation(placeholder): + if not os.path.isdir(placeholder): + log.warn('Unkown installation at %s', placeholder) + return False + found = False + for file in os.listdir(placeholder): + if fnmatch.fnmatch(file, 'setuptools*.egg-info'): + found = True + break + if not found: + log.warn('Could not locate setuptools*.egg-info') + return + + log.warn('Moving elements out of the way...') + pkg_info = os.path.join(placeholder, file) + if os.path.isdir(pkg_info): + patched = _patch_egg_dir(pkg_info) + else: + patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO) + + if not patched: + log.warn('%s already patched.', pkg_info) + return False + # now let's move the files out of the way + for element in ('setuptools', 'pkg_resources.py', 'site.py'): + element = os.path.join(placeholder, element) + if os.path.exists(element): + _rename_path(element) + else: + log.warn('Could not find the %s element of the ' + 'Setuptools distribution', element) + return True + +_remove_flat_installation = _no_sandbox(_remove_flat_installation) + + +def _after_install(dist): + log.warn('After install bootstrap.') + placeholder = dist.get_command_obj('install').install_purelib + _create_fake_setuptools_pkg_info(placeholder) + + +def _create_fake_setuptools_pkg_info(placeholder): + if not placeholder or not os.path.exists(placeholder): + log.warn('Could not find the install location') + return + pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1]) + setuptools_file = 'setuptools-%s-py%s.egg-info' % \ + (SETUPTOOLS_FAKED_VERSION, pyver) + pkg_info = os.path.join(placeholder, setuptools_file) + if os.path.exists(pkg_info): + log.warn('%s already exists', pkg_info) + return + + log.warn('Creating %s', pkg_info) + try: + f = open(pkg_info, 'w') + except EnvironmentError: + log.warn("Don't have permissions to write %s, skipping", pkg_info) + return + try: + f.write(SETUPTOOLS_PKG_INFO) + finally: + f.close() + + pth_file = os.path.join(placeholder, 'setuptools.pth') + log.warn('Creating %s', pth_file) + f = open(pth_file, 'w') + try: + f.write(os.path.join(os.curdir, setuptools_file)) + finally: + f.close() + +_create_fake_setuptools_pkg_info = _no_sandbox( + _create_fake_setuptools_pkg_info +) + + +def _patch_egg_dir(path): + # let's check if it's already patched + pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') + if os.path.exists(pkg_info): + if _same_content(pkg_info, SETUPTOOLS_PKG_INFO): + log.warn('%s already patched.', pkg_info) + return False + _rename_path(path) + os.mkdir(path) + os.mkdir(os.path.join(path, 'EGG-INFO')) + pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') + f = open(pkg_info, 'w') + try: + f.write(SETUPTOOLS_PKG_INFO) + finally: + f.close() + return True + +_patch_egg_dir = _no_sandbox(_patch_egg_dir) + + +def _before_install(): + log.warn('Before install bootstrap.') + _fake_setuptools() + + +def _under_prefix(location): + if 'install' not in sys.argv: + return True + args = sys.argv[sys.argv.index('install') + 1:] + for index, arg in enumerate(args): + for option in ('--root', '--prefix'): + if arg.startswith('%s=' % option): + top_dir = arg.split('root=')[-1] + return location.startswith(top_dir) + elif arg == option: + if len(args) > index: + top_dir = args[index + 1] + return location.startswith(top_dir) + if arg == '--user' and USER_SITE is not None: + return location.startswith(USER_SITE) + return True + + +def _fake_setuptools(): + log.warn('Scanning installed packages') + try: + import pkg_resources + except ImportError: + # we're cool + log.warn('Setuptools or Distribute does not seem to be installed.') + return + ws = pkg_resources.working_set + try: + setuptools_dist = ws.find( + pkg_resources.Requirement.parse('setuptools', replacement=False) + ) + except TypeError: + # old distribute API + setuptools_dist = ws.find( + pkg_resources.Requirement.parse('setuptools') + ) + + if setuptools_dist is None: + log.warn('No setuptools distribution found') + return + # detecting if it was already faked + setuptools_location = setuptools_dist.location + log.warn('Setuptools installation detected at %s', setuptools_location) + + # if --root or --preix was provided, and if + # setuptools is not located in them, we don't patch it + if not _under_prefix(setuptools_location): + log.warn('Not patching, --root or --prefix is installing Distribute' + ' in another location') + return + + # let's see if its an egg + if not setuptools_location.endswith('.egg'): + log.warn('Non-egg installation') + res = _remove_flat_installation(setuptools_location) + if not res: + return + else: + log.warn('Egg installation') + pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO') + if (os.path.exists(pkg_info) and + _same_content(pkg_info, SETUPTOOLS_PKG_INFO)): + log.warn('Already patched.') + return + log.warn('Patching...') + # let's create a fake egg replacing setuptools one + res = _patch_egg_dir(setuptools_location) + if not res: + return + log.warn('Patching complete.') + _relaunch() + + +def _relaunch(): + log.warn('Relaunching...') + # we have to relaunch the process + # pip marker to avoid a relaunch bug + _cmd1 = ['-c', 'install', '--single-version-externally-managed'] + _cmd2 = ['-c', 'install', '--record'] + if sys.argv[:3] == _cmd1 or sys.argv[:3] == _cmd2: + sys.argv[0] = 'setup.py' + args = [sys.executable] + sys.argv + sys.exit(subprocess.call(args)) + + +def _extractall(self, path=".", members=None): + """Extract all members from the archive to the current working + directory and set owner, modification time and permissions on + directories afterwards. `path' specifies a different directory + to extract to. `members' is optional and must be a subset of the + list returned by getmembers(). + """ + import copy + import operator + from tarfile import ExtractError + directories = [] + + if members is None: + members = self + + for tarinfo in members: + if tarinfo.isdir(): + # Extract directories with a safe mode. + directories.append(tarinfo) + tarinfo = copy.copy(tarinfo) + tarinfo.mode = 448 # decimal for oct 0700 + self.extract(tarinfo, path) + + # Reverse sort directories. + if sys.version_info < (2, 4): + def sorter(dir1, dir2): + return cmp(dir1.name, dir2.name) + directories.sort(sorter) + directories.reverse() + else: + directories.sort(key=operator.attrgetter('name'), reverse=True) + + # Set correct owner, mtime and filemode on directories. + for tarinfo in directories: + dirpath = os.path.join(path, tarinfo.name) + try: + self.chown(tarinfo, dirpath) + self.utime(tarinfo, dirpath) + self.chmod(tarinfo, dirpath) + except ExtractError: + e = sys.exc_info()[1] + if self.errorlevel > 1: + raise + else: + self._dbg(1, "tarfile: %s" % e) + + +def _build_install_args(options): + """ + Build the arguments to 'python setup.py install' on the distribute package + """ + install_args = [] + if options.user_install: + if sys.version_info < (2, 6): + log.warn("--user requires Python 2.6 or later") + raise SystemExit(1) + install_args.append('--user') + return install_args + +def _parse_args(): + """ + Parse the command line for options + """ + parser = optparse.OptionParser() + parser.add_option( + '--user', dest='user_install', action='store_true', default=False, + help='install in user site package (requires Python 2.6 or later)') + parser.add_option( + '--download-base', dest='download_base', metavar="URL", + default=DEFAULT_URL, + help='alternative URL from where to download the distribute package') + options, args = parser.parse_args() + # positional arguments are ignored + return options + +def main(version=DEFAULT_VERSION): + """Install or upgrade setuptools and EasyInstall""" + options = _parse_args() + tarball = download_setuptools(download_base=options.download_base) + return _install(tarball, _build_install_args(options)) + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/repsys.py b/repsys.py deleted file mode 100644 index 33fffaf..0000000 --- a/repsys.py +++ /dev/null @@ -1,65 +0,0 @@ -import json -import operator -import os.path - -REPFILE = "data/reps.txt" - -class ReputationSystem(object): - __slots__ = ('reps', 'ignorelist', 'cached', 'repfile') - - def __init__(self, repfile=REPFILE): - self.reps = {} - self.ignorelist = set() - self.repfile = os.path.normpath(repfile) - self.load(repfile) - self.filter() - - def dump(self): - self.filter() - fi = open(self.repfile, "w") - json.dump(self.reps, fi, sort_keys=True, indent=4, separators=(',', ': ')) - fi.close() - - def load(self, repfile=REPFILE): - if not os.path.exists(repfile): - self.reps = {} - self.dump() - return - fi = open(self.repfile) - self.reps = json.load(fi) - fi.close() - - def get(self, name): - return self.reps.get(name, 0) - - def set(self, name, val): - self.reps[name] = int(val) - - def apply(self, changer): - self.reps[changer.getUser()] = changer.perform(self.reps.get(changer.getUser(),0)) - - def clear(self, name): - self.reps.pop(name.strip(), None) - - def filter(self): - self.reps = {key: val for key, val in self.reps.items() if val != 0} - - def report(self, force=False): - self.filter() - sorted_reps = sorted(self.reps.iteritems(), - key=operator.itemgetter(1), - reverse=True) - highest = sorted_reps[:5] - lowest = sorted_reps[-5:] - return "Top reps: {0}\nBottom reps: {1}".format( - ", ".join("{0}: {1}".format(name.encode('unicode-escape'), score) for name, score in sorted_reps[:5]), - ", ".join("{0}: {1}".format(name.encode('unicode-escape'), score) for name, score in sorted_reps[-5:])) - - def tell(self, name): - self.filter() - return "Rep for {0}: {1}".format(name.encode('unicode-escape'), self.get(name)) - - def all(self): - self.filter() - return "All reps: {0}".format(self.reps) - diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..419c421 --- /dev/null +++ b/setup.py @@ -0,0 +1,41 @@ +#!/bin/env python +# -*- coding: utf8 -*- + +from distribute_setup import use_setuptools +use_setuptools() + +from setuptools import setup, find_packages + +version = "0.12.0" + +setup( + name="RepBot", + version=version, + description="IRC Reputation bot", + classifiers=[ + "Development Status :: 3 - Alpha", + "Framework :: Twisted", + "License :: OSI Approved :: MIT License", + "Natural Language :: English", + ], + keywords="irc reputation bot", + author="Matt Soucy", + author_email="msoucy@csh.rit.edu", + url="http://github.com/msoucy/RepBot", + license="MIT License", + packages=find_packages( + ), + scripts=[ + "distribute_setup.py", + ], + include_package_data=True, + zip_safe=False, + install_requires=[ + "twisted", + ], + #TODO: Deal with entry_points + #entry_points=""" + #[console_scripts] + #pythong = pythong.util:parse_args + #""" +) \ No newline at end of file