Newer
Older
# Copyright © 2016, 2018 Bruce Cowan <bruce@bcowan.eu>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from errbot import BotPlugin, botcmd, re_botcmd
class Karma(BotPlugin):
"""Karma service"""
def activate(self):
super().activate()
def deactivate(self):
self['karma'] = self.karma
def _change_karma(self, target, value, message):
self.karma[target] += value
return "Karma for '{}' is now {}".format(target, self.karma[target])
@re_botcmd(pattern=r'(.+)\+\+', prefixed=False, flags=re.IGNORECASE)
def on_karma_inc(self, message, match):
if message.frm == self.bot_identifier:
return
return self._change_karma(match.group(1), 1, message)
@re_botcmd(pattern=r'(.+)--', prefixed=False, flags=re.IGNORECASE)
def on_karma_dec(self, message, match):
if message.frm == self.bot_identifier:
return
return self._change_karma(match.group(1), -1, message)
@botcmd
def karma(self, message, args):
"""Gets karma"""
if not args:
return "**Usage**: !karma <target>"
return "Karma for '{}' is {}".format(args, self.karma[args])
def _get_num_from_args(self, args):
try:
num = int(args[0])
return num
except ValueError:
return None
except IndexError:
return 5
@botcmd
def karma_top(self, message, args):
"""Gets the top 5 karmaed items"""
if not self.karma:
return "There are no karmaed items"
num = self._get_num_from_args(args)
if not num:
return "**Error**: Couldn't convert to an integer"
keys = sorted(self.karma, key=self.karma.get, reverse=True)[:num]
values = sorted(self.karma.values(), reverse=True)[:num]
return ", ".join(["{}: {}".format(k, v) for k, v in zip(keys, values)])
@botcmd
def karma_bottom(self, message, args):
"""Gets the bottom 5 karmaed items"""
if not self.karma:
return "There are no karmaed items"
num = self._get_num_from_args(args)
if not num:
return "**Error**: Couldn't convert to an integer"
keys = sorted(self.karma, key=self.karma.get)[:num]
values = sorted(self.karma.values())[:num]
return ", ".join(["{}: {}".format(k, v) for k, v in zip(keys, values)])