Commits

Jason R. Coombs  committed 15cd604

Moved all karma functionality (including commands) into the karma module

  • Participants
  • Parent commits 6bd3844

Comments (0)

Files changed (6)

+1110
+====
+
+With version 1110, much of the backward compatibility around quotes and karma
+has been removed::
+
+ - The Karma store must now be referenced as `pmxbot.karma:Karma.store` (a
+   class attribute). It is no longer available as `pmxbot.pmxbot:karma` nor
+   `pmxbot.util:karma` nor `pmxbot.karma.karma`.

File pmxbot/botbase.py

 import irc.bot
 
 import pmxbot.itertools
-from . import karma
 from . import quotes
 from .logging import init_logger
 
 			db_uri = os.path.join(db_uri, "pmxbot.sqlite")
 		self.db_uri = db_uri
 		globals().update(logger=init_logger(db_uri))
-		karma.init_karma(db_uri)
 		quotes.init_quotes(db_uri)
 		self._nickname = nickname
 		self.__use_ssl = use_ssl

File pmxbot/karma.py

 import itertools
 import re
 import importlib
+import random
 
 from . import storage
+from .botbase import command
 
 class SameName(ValueError): pass
 class AlreadyLinked(ValueError): pass
 
 class Karma(storage.SelectableStorage):
 	@classmethod
+	def initialize(cls):
+		pmxbot = importlib.import_module('pmxbot.pmxbot')
+		cls.store = cls.from_URI(pmxbot.config.database)
+		pmxbot._finalizers.append(cls.finalize)
+
+	@classmethod
 	def finalize(cls):
 		del cls.store
 		del globals()['karma']
 				self.db.update(query, update, safe=True)
 				self.db.remove(duplicate)
 
-def init_karma(uri):
-	Karma.store = Karma.from_URI(uri)
-	# for backward compatibility
-	globals().update(karma=Karma.store)
-	importlib.import_module('pmxbot.util').karma = Karma.store
+@command("karma", aliases=("k",), doc="Return or change the karma value for "
+	"some(one|thing)")
+def karma(client, event, channel, nick, rest):
+	karmee = rest.strip('++').strip('--').strip('~~')
+	if '++' in rest:
+		Karma.store.change(karmee, 1)
+	elif '--' in rest:
+		Karma.store.change(karmee, -1)
+	elif '~~' in rest:
+		change = random.choice([-1, 0, 1])
+		Karma.store.change(karmee, change)
+		if change == 1:
+			return "%s karma++" % karmee
+		elif change == 0:
+			return "%s karma shall remain the same" % karmee
+		elif change == -1:
+			return "%s karma--" % karmee
+	elif '==' in rest:
+		t1, t2 = rest.split('==')
+		try:
+			Karma.store.link(t1, t2)
+		except SameName:
+			Karma.store.change(nick, -1)
+			return "Don't try to link a name to itself!"
+		except AlreadyLinked:
+			return "Those names were previously linked."
+		score = Karma.store.lookup(t1)
+		return "%s and %s are now linked and have a score of %s" % (t1, t2, score)
+	else:
+		karmee = rest or nick
+		score = Karma.store.lookup(karmee)
+		return "%s has %s karmas" % (karmee, score)
 
+@command("top10", aliases=("top",), doc="Return the top n (default 10) "
+	"highest entities by Karmic value. Use negative numbers for the bottom "
+	"N.")
+def top10(client, event, channel, nick, rest):
+	if rest:
+		topn = int(rest)
+	else:
+		topn = 10
+	selection = Karma.store.list(topn)
+	res = ' '.join('(%s: %s)' % (', '.join(n), k) for n, k in selection)
+	return res
 
-# for backward compatibility:
-def karmaChange(db, *args, **kwargs):
-	return Karma.store.change(*args, **kwargs)
+@command("bottom10", aliases=("bottom",), doc="Return the bottom n (default "
+	"10) lowest entities by Karmic value. Use negative numbers for the "
+	"bottom N.")
+def bottom10(client, event, channel, nick, rest):
+	if rest:
+		topn = -int(rest)
+	else:
+		topn = -10
+	selection = Karma.store.list(topn)
+	res = ' '.join('(%s: %s)' % (', '.join(n), k) for n, k in selection)
+	return res

File pmxbot/pmxbot.py

 from .botbase import (command, contains, _handler_registry, NoLog)
 from . import dictlib
 from . import botbase
-from . import karma as karma_mod
+from . import karma
 from . import quotes
 from . import phrases
 from . import util
 	except ValueError:
 		# google returns invalid JSON
 		# !dm google
-		karma_mod.karma.change(u'google', -1)
+		karma.Karma.store.change(u'google', -1)
 		json_fixed = re.sub(r'(\w+):', r'"\1":', json_raw)
 		res = json.loads(json_fixed)
 	if res[u'error']:
 @command("boo", doc="Boo someone")
 def boo(client, event, channel, nick, rest):
 	slapee = rest
-	karma_mod.karma.change(slapee, -1)
+	karma.Karma.store.change(slapee, -1)
 	return "/me BOOO %s!!! BOOO!!!" % slapee
 
 @command("troutslap", aliases=("slap", "ts"), doc="Slap some(one|thing) with a fish")
 def troutslap(client, event, channel, nick, rest):
 	slapee = rest
-	karma_mod.karma.change(slapee, -1)
+	karma.Karma.store.change(slapee, -1)
 	return "/me slaps %s around a bit with a large trout" % slapee
 
 @command("keelhaul", aliases=("kh",), doc="Inflict great pain and embarassment on some(one|thing)")
 def keelhaul(client, event, channel, nick, rest):
 	keelee = rest
-	karma_mod.karma.change(keelee, -1)
+	karma.Karma.store.change(keelee, -1)
 	return "/me straps %s to a dirty rope, tosses 'em overboard and pulls with great speed. Yarrr!" % keelee
 
 @command("annoy", aliases=("a", "bother",), doc="Annoy everyone with meaningless banter")
 	rest = rest.strip()
 	if rest:
 		parts.append("%s is" % rest)
-		karma_mod.karma.change(rest, 1)
+		karma.Karma.store.change(rest, 1)
 	parts.append("APPROVED!")
 	return " ".join(parts)
 
 @command("cheer", aliases=("c",), doc="Cheer for something")
 def cheer(client, event, channel, nick, rest):
 	if rest:
-		karma_mod.karma.change(rest, 1)
+		karma.Karma.store.change(rest, 1)
 		return "/me cheers for %s!" % rest
-	karma_mod.karma.change('the day', 1)
+	karma.Karma.store.change('the day', 1)
 	return "/me cheers!"
 
 @command("golfclap", aliases=("clap",), doc="Clap for something")
 	adj = random.choice(phrases.adjl)
 	if rest:
 		clapee = rest.strip()
-		karma_mod.karma.change(clapee, 1)
+		karma.Karma.store.change(clapee, 1)
 		return "/me claps %s for %s, %s %s." % (clapv, rest, adv, adj)
 	return "/me claps %s, %s %s." % (clapv, adv, adj)
 
 	name = 'you'
 	if rest:
 		name = rest.strip()
-		karma_mod.karma.change(name, -1)
+		karma.Karma.store.change(name, -1)
 	return "OH MAN!!! %s TOTALLY GOT ZING'D!" % (name.upper())
 
 @command("motivate", aliases=("m", "appreciate", "thanks", "thank"), doc="Motivate someone")
 		r = rest.strip()
 	else:
 		r = channel
-	karma_mod.karma.change(r, 1)
+	karma.Karma.store.change(r, 1)
 	return "you're doing good work, %s!" % r
 
 @command("imotivate", aliases=("im", 'ironicmotivate',), doc='''Ironically "Motivate" someone''')
 def imotivate(client, event, channel, nick, rest):
 	if rest:
 		r = rest.strip()
-		karma_mod.karma.change(r, -1)
+		karma.Karma.store.change(r, -1)
 	else:
 		r = channel
 	return '''you're "doing" "good" "work", %s!''' % r
 		r = rest.strip()
 	else:
 		r = channel
-	karma_mod.karma.change(r, -1)
+	karma.Karma.store.change(r, -1)
 	return "you're doing horrible work, %s!" % r
 
 @command("8ball", aliases=("8",), doc="Ask the magic 8ball a question")
 	if insult:
 		if rest:
 			insultee = rest.strip()
-			karma_mod.karma.change(insultee, -1)
+			karma.Karma.store.change(insultee, -1)
 			if instype in (0, 2):
 				cinsre = re.compile(r'\b(your)\b', re.IGNORECASE)
 				insult = cinsre.sub("%s's" % insultee, insult)
 		compliment = re.compile(r'  ').sub('%s' % ' ', compliment)
 		if rest:
 			complimentee = rest.strip()
-			karma_mod.karma.change(complimentee, 1)
+			karma.Karma.store.change(complimentee, 1)
 			compliment = re.compile(r'\b(your)\b', re.IGNORECASE).sub('%s\'s' % complimentee, compliment)
 			compliment = re.compile(r'\b(you are)\b', re.IGNORECASE).sub('%s is' % complimentee, compliment)
 			compliment = re.compile(r'\b(you have)\b', re.IGNORECASE).sub('%s has' % complimentee, compliment)
 		return compliment
 
-
-@command("karma", aliases=("k",), doc="Return or change the karma value for some(one|thing)")
-def karma(client, event, channel, nick, rest):
-	karmee = rest.strip('++').strip('--').strip('~~')
-	if '++' in rest:
-		karma_mod.karma.change(karmee, 1)
-	elif '--' in rest:
-		karma_mod.karma.change(karmee, -1)
-	elif '~~' in rest:
-		change = random.choice([-1, 0, 1])
-		karma_mod.karma.change(karmee, change)
-		if change == 1:
-			return "%s karma++" % karmee
-		elif change == 0:
-			return "%s karma shall remain the same" % karmee
-		elif change == -1:
-			return "%s karma--" % karmee
-	elif '==' in rest:
-		t1, t2 = rest.split('==')
-		try:
-			karma_mod.karma.link(t1, t2)
-		except karma_mod.SameName:
-			karma_mod.karma.change(nick, -1)
-			return "Don't try to link a name to itself!"
-		except karma_mod.AlreadyLinked:
-			return "Those names were previously linked."
-		score = karma_mod.karma.lookup(t1)
-		return "%s and %s are now linked and have a score of %s" % (t1, t2, score)
-	else:
-		karmee = rest or nick
-		score = karma_mod.karma.lookup(karmee)
-		return "%s has %s karmas" % (karmee, score)
-
-@command("top10", aliases=("top",), doc="Return the top n (default 10) highest entities by Karmic value. Use negative numbers for the bottom N.")
-def top10(client, event, channel, nick, rest):
-	if rest:
-		topn = int(rest)
-	else:
-		topn = 10
-	selection = karma_mod.karma.list(topn)
-	res = ' '.join('(%s: %s)' % (', '.join(n), k) for n, k in selection)
-	return res
-
-@command("bottom10", aliases=("bottom",), doc="Return the bottom n (default 10) lowest entities by Karmic value. Use negative numbers for the bottom N.")
-def bottom10(client, event, channel, nick, rest):
-	if rest:
-		topn = -int(rest)
-	else:
-		topn = -10
-	selection = karma_mod.karma.list(topn)
-	res = ' '.join('(%s: %s)' % (', '.join(n), k) for n, k in selection)
-	return res
-
 @command("gettowork", aliases=("gtw",), doc="You really ought to, ya know...")
 def gettowork(client, event, channel, nick, rest):
 	suggestions = [u"Um, might I suggest working now",
 	suggestion = random.choice(suggestions)
 	rest = rest.strip()
 	if rest:
-		karma_mod.karma.change(rest, -1)
+		karma.Karma.store.change(rest, -1)
 		suggestion = suggestion + ', %s' % rest
 	else:
-		karma_mod.karma.change(channel, -1)
-	karma_mod.karma.change(nick, -1)
+		karma.Karma.store.change(channel, -1)
+	karma.Karma.store.change(nick, -1)
 	return suggestion
 
 @command("bitchingisuseless", aliases=("qbiu",), doc="It really is, ya know...")
 def bitchingisuseless(client, event, channel, nick, rest):
 	rest = rest.strip()
 	if rest:
-		karma_mod.karma.change(rest, -1)
+		karma.Karma.store.change(rest, -1)
 	else:
-		karma_mod.karma.change(channel, -1)
+		karma.Karma.store.change(channel, -1)
 		rest = "foo'"
 	advice = 'Quiet bitching is useless, %s. Do something about it.' % rest
 	return advice
 		cursee = rest
 	else:
 		cursee = 'the day'
-	karma_mod.karma.change(cursee, -1)
+	karma.Karma.store.change(cursee, -1)
 	return "/me curses %s!" % cursee
 
 @command("tinytear", aliases=('tt', 'tear', 'cry'), doc="I cry a tiny tear for you.")
 	else:
 		stabee = 'wildly at anything'
 	if random.random() < 0.9:
-		karma_mod.karma.change(stabee, -1)
+		karma.Karma.store.change(stabee, -1)
 		weapon = random.choice(phrases.weapon_opts)
 		weaponadj = random.choice(phrases.weapon_adjs)
 		violentact = random.choice(phrases.violent_acts)
 		return "/me grabs a %s %s and %s %s!" % (weaponadj, weapon, violentact, stabee)
 	elif random.random() < 0.6:
-		karma_mod.karma.change(stabee, -1)
+		karma.Karma.store.change(stabee, -1)
 		return "/me is going to become rich and famous after i invent a device that allows you to stab people in the face over the internet"
 	else:
-		karma_mod.karma.change(nick, -1)
+		karma.Karma.store.change(nick, -1)
 		return "/me turns on its master and shivs %s. This is reality man, and you never know what you're going to get!" % nick
 
 @command("disembowel", aliases=("dis", "eviscerate"),doc="Disembowel some(one|thing)!")
 def disembowel(client, event, channel, nick, rest):
 	if rest:
 		stabee = rest
-		karma_mod.karma.change(stabee, -1)
+		karma.Karma.store.change(stabee, -1)
 	else:
 		stabee = "someone nearby"
 	return "/me takes %s, brings them down to the basement, ties them to a leaky pipe, and once bored of playing with them mercifully ritually disembowels them..." % stabee
 def embowel(client, event, channel, nick, rest):
 	if rest:
 		stabee = rest
-		karma_mod.karma.change(stabee, 1)
+		karma.Karma.store.change(stabee, 1)
 	else:
 		stabee = "someone nearby"
 	return "/me (wearing a bright pink cape and yellow tights) swoops in through an open window, snatches %s, races out of the basement, takes them to the hospital with entrails on ice, and mercifully embowels them, saving the day..." % stabee
 	elif random.randint(1,10) != 1:
 		return "/me chains %s to the nearest desk.  you ain't going home, buddy." % chainee
 	else:
-		karma_mod.karma.change(nick, -1)
+		karma.Karma.store.change(nick, -1)
 		return "/me spins violently around and chains %s to the nearest desk.  your days of chaining people down and stomping on their dreams are over!  get a life, you miserable beast." % nick
 
 @command("bless", doc="Bless the day!")
 		blesse = rest
 	else:
 		blesse = 'the day'
-	karma_mod.karma.change(blesse, 1)
+	karma.Karma.store.change(blesse, 1)
 	return "/me blesses %s!" % blesse
 
 @command("blame", doc="Pass the buck!")
 		blamee = rest
 	else:
 		blamee = channel
-	karma_mod.karma.change(nick, -1)
+	karma.Karma.store.change(nick, -1)
 	if random.randint(1,10) == 1:
 		yield "/me jumps atop the chair and points back at %s." % nick
 		yield "stop blaming the world for your problems, you bitter, two-faced sissified monkey!"
 
 @contains("sqlonrails")
 def yay_sor(client, event, channel, nick, rest):
-	karma_mod.karma.change('sql on rails', 1)
+	karma.Karma.store.change('sql on rails', 1)
 	return "Only 76,417 lines..."
 
 @contains("sql on rails")
 		if len(contenders) > 2:
 			bad_protocol = True
 		if bad_protocol:
-			karma_mod.karma.change(nick.lower(), -1)
+			karma.Karma.store.change(nick.lower(), -1)
 			args = (vtype, nick, fdesc)
 			return "/me %s %s in %s for bad protocol." % args
 		random.shuffle(contenders)
 		winner,loser = contenders
-		karma_mod.karma.change(winner, 1)
-		karma_mod.karma.change(loser, -1)
+		karma.Karma.store.change(winner, 1)
+		karma.Karma.store.change(loser, -1)
 		return "%s %s %s in %s." % (winner, vtype, loser, fdesc)
 
 @command("progress", doc="Display the progress of something: start|end|percent")
 	recipient = ""
 	if rest:
 		recipient = rest.strip()
-		karma_mod.karma.change(recipient, -1)
+		karma.Karma.store.change(recipient, -1)
 	return util.passagg(recipient, nick.lower())
 
 @command("therethere", aliases=('poor', 'comfort'), doc="Sympathy for you.")
 def therethere(client, event, channel, nick, rest):
 	if rest:
-		karma_mod.karma.change(rest, 1)
+		karma.Karma.store.change(rest, 1)
 		return "There there %s... There there." % rest
 	else:
 		return "/me shares its sympathy."
 
 _finalizers = [
 	botbase.LoggingCommandBot._finalize_logger,
-	karma_mod.Karma.finalize,
 	quotes.Quotes.finalize,
 ]
 
 			'pmxbotweb=pmxbotweb.pmxbotweb:run',
 		],
 		pmxbot_handlers = [
+			'pmxbot karma = pmxbot.karma:Karma.initialize',
 			'pmxbot notifier = pmxbot.notify:Notify.init',
 			'pmxbot feedparser = pmxbot.rss:RSSFeeds',
 		],

File tests/unit/test_commands.py

 		Determine your own, blank, karma.
 		"""
 		id = str(uuid.uuid4())[:15]
-		res = pmxbot.karma(c, e, "#test", id, "")
+		res = karma.karma(c, e, "#test", id, "")
 		assert re.match(r"^%s has 0 karmas$" % id, res)
 
 	def test_karma_check_other_blank(self):
 		Determine some else's blank/new karma.
 		"""
 		id = str(uuid.uuid4())
-		res = pmxbot.karma(c, e, "#test", "testrunner", id)
+		res = karma.karma(c, e, "#test", "testrunner", id)
 		assert re.match("^%s has 0 karmas$" % id, res)
 
 	def test_karma_set_and_check(self):
 		Take a new entity, give it some karma, check that it has more
 		"""
 		id = str(uuid.uuid4())
-		res = pmxbot.karma(c, e, "#test", "testrunner", id)
+		res = karma.karma(c, e, "#test", "testrunner", id)
 		assert re.match("^%s has 0 karmas$" % id, res)
-		res = pmxbot.karma(c, e, "#test", "testrunner", "%s++" %id)
-		res = pmxbot.karma(c, e, "#test", "testrunner", "%s++" %id)
-		res = pmxbot.karma(c, e, "#test", "testrunner", "%s++" %id)
-		res = pmxbot.karma(c, e, "#test", "testrunner", "%s--" %id)
-		res = pmxbot.karma(c, e, "#test", "testrunner", id)
+		res = karma.karma(c, e, "#test", "testrunner", "%s++" %id)
+		res = karma.karma(c, e, "#test", "testrunner", "%s++" %id)
+		res = karma.karma(c, e, "#test", "testrunner", "%s++" %id)
+		res = karma.karma(c, e, "#test", "testrunner", "%s--" %id)
+		res = karma.karma(c, e, "#test", "testrunner", id)
 		assert re.match(r"^%s has 2 karmas$" % id, res)
 
 	def test_karma_set_and_check_with_space(self):
 		Take a new entity that has a space in it's name, give it some karma, check that it has more
 		"""
 		id = str(uuid.uuid4()).replace("-", " ")
-		res = pmxbot.karma(c, e, "#test", "testrunner", id)
+		res = karma.karma(c, e, "#test", "testrunner", id)
 		assert re.match("^%s has 0 karmas$" % id, res)
-		res = pmxbot.karma(c, e, "#test", "testrunner", "%s++" %id)
-		res = pmxbot.karma(c, e, "#test", "testrunner", "%s++" %id)
-		res = pmxbot.karma(c, e, "#test", "testrunner", "%s++" %id)
-		res = pmxbot.karma(c, e, "#test", "testrunner", "%s--" %id)
-		res = pmxbot.karma(c, e, "#test", "testrunner", id)
+		res = karma.karma(c, e, "#test", "testrunner", "%s++" %id)
+		res = karma.karma(c, e, "#test", "testrunner", "%s++" %id)
+		res = karma.karma(c, e, "#test", "testrunner", "%s++" %id)
+		res = karma.karma(c, e, "#test", "testrunner", "%s--" %id)
+		res = karma.karma(c, e, "#test", "testrunner", id)
 		assert re.match(r"^%s has 2 karmas$" % id, res)
 
 	def test_karma_randomchange(self):
 		i = 0
 		karmafetch = re.compile(r"^%s has (\-?\d+) karmas$" % id)
 		while len(flags) < 3 and i <= 30:
-			res = pmxbot.karma(c, e, "#test", "testrunner", id)
+			res = karma.karma(c, e, "#test", "testrunner", id)
 			prekarma = int(karmafetch.findall(res)[0])
-			change = pmxbot.karma(c, e, "#test", "testrunner", "%s~~" % id)
+			change = karma.karma(c, e, "#test", "testrunner", "%s~~" % id)
 			assert change in ["%s karma++" % id, "%s karma--" % id, "%s karma shall remain the same" % id]
 			if change.endswith('karma++'):
 				flags['++'] = True
-				res = pmxbot.karma(c, e, "#test", "testrunner", id)
+				res = karma.karma(c, e, "#test", "testrunner", id)
 				postkarma = int(karmafetch.findall(res)[0])
 				assert postkarma == prekarma + 1
 			elif change.endswith('karma--'):
 				flags['--'] = True
-				res = pmxbot.karma(c, e, "#test", "testrunner", id)
+				res = karma.karma(c, e, "#test", "testrunner", id)
 				postkarma = int(karmafetch.findall(res)[0])
 				assert postkarma == prekarma - 1
 			elif change.endswith('karma shall remain the same'):
 				flags['same'] = True
-				res = pmxbot.karma(c, e, "#test", "testrunner", id)
+				res = karma.karma(c, e, "#test", "testrunner", id)
 				postkarma = int(karmafetch.findall(res)[0])
 				assert postkarma == prekarma
 			i+=1