| 1 |
### |
| 2 |
# Copyright (c) 2005, Jeremiah Fincher |
| 3 |
# Copyright (c) 2010, James McCoy |
| 4 |
# Copyright (c) 2010-2021, Valentin Lorentz |
| 5 |
# All rights reserved. |
| 6 |
# |
| 7 |
# Redistribution and use in source and binary forms, with or without |
| 8 |
# modification, are permitted provided that the following conditions are met: |
| 9 |
# |
| 10 |
# * Redistributions of source code must retain the above copyright notice, |
| 11 |
# this list of conditions, and the following disclaimer. |
| 12 |
# * Redistributions in binary form must reproduce the above copyright notice, |
| 13 |
# this list of conditions, and the following disclaimer in the |
| 14 |
# documentation and/or other materials provided with the distribution. |
| 15 |
# * Neither the name of the author of this software nor the name of |
| 16 |
# contributors to this software may be used to endorse or promote products |
| 17 |
# derived from this software without specific prior written consent. |
| 18 |
# |
| 19 |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 20 |
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 21 |
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 22 |
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE |
| 23 |
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 24 |
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 25 |
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 26 |
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 27 |
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 28 |
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 29 |
# POSSIBILITY OF SUCH DAMAGE. |
| 30 |
### |
| 31 |
|
| 32 |
import os |
| 33 |
import re |
| 34 |
import sys |
| 35 |
import csv |
| 36 |
import time |
| 37 |
import random |
| 38 |
|
| 39 |
import supybot.conf as conf |
| 40 |
import supybot.utils as utils |
| 41 |
from supybot.commands import * |
| 42 |
import supybot.utils.minisix as minisix |
| 43 |
import supybot.plugins as plugins |
| 44 |
import supybot.ircmsgs as ircmsgs |
| 45 |
import supybot.ircutils as ircutils |
| 46 |
import supybot.callbacks as callbacks |
| 47 |
import supybot.schedule as schedule |
| 48 |
from supybot.i18n import PluginInternationalization, internationalizeDocstring |
| 49 |
_ = PluginInternationalization('Karma') |
| 50 |
|
| 51 |
import sqlite3 |
| 52 |
|
| 53 |
def checkAllowShell(irc): |
| 54 |
if not conf.supybot.commands.allowShell(): |
| 55 |
irc.error('This command is not available, because ' |
| 56 |
'supybot.commands.allowShell is False.', Raise=True) |
| 57 |
|
| 58 |
class SqliteKarmaDB(object): |
| 59 |
def __init__(self, filename): |
| 60 |
self.dbs = ircutils.IrcDict() |
| 61 |
self.filename = filename |
| 62 |
|
| 63 |
def close(self): |
| 64 |
for db in self.dbs.values(): |
| 65 |
db.close() |
| 66 |
|
| 67 |
def _getDb(self, channel): |
| 68 |
filename = plugins.makeChannelFilename(self.filename, channel) |
| 69 |
if filename in self.dbs: |
| 70 |
return self.dbs[filename] |
| 71 |
if os.path.exists(filename): |
| 72 |
db = sqlite3.connect(filename, check_same_thread=False) |
| 73 |
if minisix.PY2: |
| 74 |
db.text_factory = str |
| 75 |
self.dbs[filename] = db |
| 76 |
return db |
| 77 |
db = sqlite3.connect(filename, check_same_thread=False) |
| 78 |
if minisix.PY2: |
| 79 |
db.text_factory = str |
| 80 |
self.dbs[filename] = db |
| 81 |
cursor = db.cursor() |
| 82 |
cursor.execute("""CREATE TABLE karma ( |
| 83 |
id INTEGER PRIMARY KEY, |
| 84 |
name TEXT, |
| 85 |
normalized TEXT UNIQUE ON CONFLICT IGNORE, |
| 86 |
added INTEGER, |
| 87 |
subtracted INTEGER |
| 88 |
)""") |
| 89 |
db.commit() |
| 90 |
def p(s1, s2): |
| 91 |
return int(ircutils.nickEqual(s1, s2)) |
| 92 |
db.create_function('nickeq', 2, p) |
| 93 |
return db |
| 94 |
|
| 95 |
def get(self, channel, thing): |
| 96 |
db = self._getDb(channel) |
| 97 |
thing = thing.lower() |
| 98 |
cursor = db.cursor() |
| 99 |
cursor.execute("""SELECT added, subtracted FROM karma |
| 100 |
WHERE normalized=?""", (thing,)) |
| 101 |
results = cursor.fetchall() |
| 102 |
if len(results) == 0: |
| 103 |
return None |
| 104 |
else: |
| 105 |
return list(map(int, results[0])) |
| 106 |
|
| 107 |
def gets(self, channel, things): |
| 108 |
db = self._getDb(channel) |
| 109 |
cursor = db.cursor() |
| 110 |
normalizedThings = dict(list(zip([s.lower() for s in things], things))) |
| 111 |
criteria = ' OR '.join(['normalized=?'] * len(normalizedThings)) |
| 112 |
sql = """SELECT name, added-subtracted FROM karma |
| 113 |
WHERE %s ORDER BY added-subtracted DESC""" % criteria |
| 114 |
cursor.execute(sql, list(normalizedThings.keys())) |
| 115 |
L = [(name, int(karma)) for (name, karma) in cursor.fetchall()] |
| 116 |
for (name, _) in L: |
| 117 |
del normalizedThings[name.lower()] |
| 118 |
neutrals = list(normalizedThings.values()) |
| 119 |
neutrals.sort() |
| 120 |
return (L, neutrals) |
| 121 |
|
| 122 |
def top(self, channel, limit): |
| 123 |
db = self._getDb(channel) |
| 124 |
cursor = db.cursor() |
| 125 |
cursor.execute("""SELECT name, added-subtracted FROM karma |
| 126 |
ORDER BY added-subtracted DESC LIMIT ?""", (limit,)) |
| 127 |
return [(t[0], int(t[1])) for t in cursor.fetchall()] |
| 128 |
|
| 129 |
def bottom(self, channel, limit): |
| 130 |
db = self._getDb(channel) |
| 131 |
cursor = db.cursor() |
| 132 |
cursor.execute("""SELECT name, added-subtracted FROM karma |
| 133 |
ORDER BY added-subtracted ASC LIMIT ?""", (limit,)) |
| 134 |
return [(t[0], int(t[1])) for t in cursor.fetchall()] |
| 135 |
|
| 136 |
def rank(self, channel, thing): |
| 137 |
db = self._getDb(channel) |
| 138 |
cursor = db.cursor() |
| 139 |
cursor.execute("""SELECT added-subtracted FROM karma |
| 140 |
WHERE name=?""", (thing,)) |
| 141 |
results = cursor.fetchall() |
| 142 |
if len(results) == 0: |
| 143 |
return None |
| 144 |
karma = int(results[0][0]) |
| 145 |
cursor.execute("""SELECT COUNT(*) FROM karma |
| 146 |
WHERE added-subtracted > ?""", (karma,)) |
| 147 |
rank = int(cursor.fetchone()[0]) |
| 148 |
return rank+1 |
| 149 |
|
| 150 |
def size(self, channel): |
| 151 |
db = self._getDb(channel) |
| 152 |
cursor = db.cursor() |
| 153 |
cursor.execute("""SELECT COUNT(*) FROM karma""") |
| 154 |
return int(cursor.fetchone()[0]) |
| 155 |
|
| 156 |
def increment(self, channel, name): |
| 157 |
db = self._getDb(channel) |
| 158 |
cursor = db.cursor() |
| 159 |
normalized = name.lower() |
| 160 |
cursor.execute("""INSERT INTO karma VALUES (NULL, ?, ?, 0, 0)""", |
| 161 |
(name, normalized,)) |
| 162 |
cursor.execute("""UPDATE karma SET added=added+1 |
| 163 |
WHERE normalized=?""", (normalized,)) |
| 164 |
db.commit() |
| 165 |
|
| 166 |
def decrement(self, channel, name): |
| 167 |
db = self._getDb(channel) |
| 168 |
cursor = db.cursor() |
| 169 |
normalized = name.lower() |
| 170 |
cursor.execute("""INSERT INTO karma VALUES (NULL, ?, ?, 0, 0)""", |
| 171 |
(name, normalized,)) |
| 172 |
cursor.execute("""UPDATE karma SET subtracted=subtracted+1 |
| 173 |
WHERE normalized=?""", (normalized,)) |
| 174 |
db.commit() |
| 175 |
|
| 176 |
def most(self, channel, kind, limit): |
| 177 |
if kind == 'increased': |
| 178 |
orderby = 'added' |
| 179 |
elif kind == 'decreased': |
| 180 |
orderby = 'subtracted' |
| 181 |
elif kind == 'active': |
| 182 |
orderby = 'added+subtracted' |
| 183 |
else: |
| 184 |
raise ValueError('invalid kind') |
| 185 |
sql = """SELECT name, %s FROM karma ORDER BY %s DESC LIMIT %s""" % \ |
| 186 |
(orderby, orderby, limit) |
| 187 |
db = self._getDb(channel) |
| 188 |
cursor = db.cursor() |
| 189 |
cursor.execute(sql) |
| 190 |
return [(name, int(i)) for (name, i) in cursor.fetchall()] |
| 191 |
|
| 192 |
def clear(self, channel, name=None): |
| 193 |
db = self._getDb(channel) |
| 194 |
cursor = db.cursor() |
| 195 |
if name: |
| 196 |
normalized = name.lower() |
| 197 |
cursor.execute("""DELETE FROM karma |
| 198 |
WHERE normalized=?""", (normalized,)) |
| 199 |
else: |
| 200 |
cursor.execute("""DELETE FROM karma""") |
| 201 |
db.commit() |
| 202 |
|
| 203 |
def dump(self, channel, filename): |
| 204 |
filename = conf.supybot.directories.data.dirize(filename) |
| 205 |
fd = utils.file.AtomicFile(filename) |
| 206 |
out = csv.writer(fd) |
| 207 |
db = self._getDb(channel) |
| 208 |
cursor = db.cursor() |
| 209 |
cursor.execute("""SELECT name, added, subtracted FROM karma""") |
| 210 |
for (name, added, subtracted) in cursor.fetchall(): |
| 211 |
out.writerow([name, added, subtracted]) |
| 212 |
fd.close() |
| 213 |
|
| 214 |
def load(self, channel, filename): |
| 215 |
filename = conf.supybot.directories.data.dirize(filename) |
| 216 |
fd = open(filename, encoding='utf8') |
| 217 |
reader = csv.reader(fd) |
| 218 |
db = self._getDb(channel) |
| 219 |
cursor = db.cursor() |
| 220 |
cursor.execute("""DELETE FROM karma""") |
| 221 |
for (name, added, subtracted) in reader: |
| 222 |
normalized = name.lower() |
| 223 |
cursor.execute("""INSERT INTO karma |
| 224 |
VALUES (NULL, ?, ?, ?, ?)""", |
| 225 |
(name, normalized, added, subtracted,)) |
| 226 |
db.commit() |
| 227 |
fd.close() |
| 228 |
|
| 229 |
KarmaDB = plugins.DB('Karma', |
| 230 |
{'sqlite3': SqliteKarmaDB}) |
| 231 |
|
| 232 |
class Karma(callbacks.Plugin): |
| 233 |
""" |
| 234 |
Provides a simple tracker for setting Karma (thing++, thing--). |
| 235 |
If ``config plugins.karma.allowUnaddressedKarma`` is set to ``True`` |
| 236 |
(default since 2014.05.07), saying `boats++` will give 1 karma |
| 237 |
to ``boats``, and ``ships--`` will subtract 1 karma from ``ships``. |
| 238 |
|
| 239 |
However, if you use this in a sentence, like |
| 240 |
``That deserves a ++. Kevin++``, 1 karma will be added to |
| 241 |
``That deserves a ++. Kevin``, so you should only add or subtract karma |
| 242 |
in a line that doesn't have anything else in it. |
| 243 |
Alternatively, you can restrict karma tracking to nicks in the current |
| 244 |
channel by setting `config plugins.Karma.onlyNicks` to ``True``. |
| 245 |
|
| 246 |
If ``config plugins.karma.allowUnaddressedKarma` is set to `False``, |
| 247 |
you must address the bot with nick or prefix to add or subtract karma. |
| 248 |
""" |
| 249 |
callBefore = ('Factoids', 'MoobotFactoids', 'Infobot') |
| 250 |
def __init__(self, irc): |
| 251 |
self.__parent = super(Karma, self) |
| 252 |
self.__parent.__init__(irc) |
| 253 |
self.db = KarmaDB() |
| 254 |
|
| 255 |
def die(self): |
| 256 |
self.__parent.die() |
| 257 |
self.db.close() |
| 258 |
|
| 259 |
def _normalizeThing(self, thing): |
| 260 |
assert thing |
| 261 |
if thing[0] == '(' and thing[-1] == ')': |
| 262 |
thing = thing[1:-1] |
| 263 |
return thing |
| 264 |
|
| 265 |
def _respond(self, irc, channel, thing, karma): |
| 266 |
if self.registryValue('response', channel, irc.network): |
| 267 |
irc.reply(_('%(thing)s\'s karma is now %(karma)i') % |
| 268 |
{'thing': thing, 'karma': karma}) |
| 269 |
else: |
| 270 |
irc.noReply() |
| 271 |
|
| 272 |
IRC_NICK = r'\w[\w\\`\[\]\{\}\^-]*' |
| 273 |
TABLE_FLIP = re.compile(r'\s*[(\(]╯...[\))]╯\s*︵\s*.*', re.U) |
| 274 |
|
| 275 |
def _doKarma(self, irc, msg, channel, line): |
| 276 |
match = self.TABLE_FLIP.match(line) |
| 277 |
if match: |
| 278 |
event_name = f'unflip {msg.nic}' |
| 279 |
try: |
| 280 |
schedule.removeEvent(event_name) |
| 281 |
except KeyError: |
| 282 |
pass |
| 283 |
schedule.addEvent( |
| 284 |
irc.reply, |
| 285 |
time.time() + random.lognormvariate(0.5, 0.5), |
| 286 |
name=event_name, |
| 287 |
args=['┳━┳ノ(°_°ノ)'], |
| 288 |
) |
| 289 |
return |
| 290 |
|
| 291 |
inc = self.registryValue('incrementChars', channel, irc.network) |
| 292 |
dec = self.registryValue('decrementChars', channel, irc.network) |
| 293 |
onlynicks = self.registryValue('onlyNicks', channel, irc.network) |
| 294 |
karma = {} |
| 295 |
for s in inc: |
| 296 |
regex = re.compile(rf'\b({self.IRC_NICK})\b{re.escape(s)}') |
| 297 |
for match in regex.finditer(line): |
| 298 |
thing = match.group(1) |
| 299 |
# Don't reply if the target isn't a nick |
| 300 |
if onlynicks and thing.lower() not in map(ircutils.toLower, |
| 301 |
irc.state.channels[channel].users): |
| 302 |
return |
| 303 |
if ircutils.strEqual(thing, msg.nick) and \ |
| 304 |
not self.registryValue('allowSelfRating', |
| 305 |
channel, irc.network): |
| 306 |
irc.error(_('You\'re not allowed to adjust your own karma.')) |
| 307 |
return |
| 308 |
self.db.increment(channel, self._normalizeThing(thing)) |
| 309 |
scores = self.db.get(channel, self._normalizeThing(thing)) |
| 310 |
if scores: |
| 311 |
karma[thing] = scores[0] - scores[1] |
| 312 |
for s in dec: |
| 313 |
regex = re.compile(rf'\b({self.IRC_NICK})\b{re.escape(s)}') |
| 314 |
for match in regex.finditer(line): |
| 315 |
thing = match.group(1) |
| 316 |
if onlynicks and thing.lower() not in map(ircutils.toLower, |
| 317 |
irc.state.channels[channel].users): |
| 318 |
return |
| 319 |
if ircutils.strEqual(thing, msg.nick) and \ |
| 320 |
not self.registryValue('allowSelfRating', |
| 321 |
channel, irc.network): |
| 322 |
irc.error(_('You\'re not allowed to adjust your own karma.')) |
| 323 |
return |
| 324 |
self.db.decrement(channel, self._normalizeThing(thing)) |
| 325 |
scores = self.db.get(channel, self._normalizeThing(thing)) |
| 326 |
if scores: |
| 327 |
karma[thing] = scores[0] - scores[1] |
| 328 |
for thing, score in karma.items(): |
| 329 |
self._respond(irc, channel, thing, score) |
| 330 |
|
| 331 |
def invalidCommand(self, irc, msg, tokens): |
| 332 |
if msg.channel and tokens: |
| 333 |
line = msg.args[1].rstrip() |
| 334 |
self._doKarma(irc, msg, msg.channel, line) |
| 335 |
|
| 336 |
def doPrivmsg(self, irc, msg): |
| 337 |
# We don't handle this if we've been addressed because invalidCommand |
| 338 |
# will handle it for us. This prevents us from accessing the db twice |
| 339 |
# and therefore crashing. |
| 340 |
if not (msg.addressed or msg.repliedTo): |
| 341 |
if msg.channel and \ |
| 342 |
not ircmsgs.isCtcp(msg) and \ |
| 343 |
self.registryValue('allowUnaddressedKarma', |
| 344 |
msg.channel, irc.network): |
| 345 |
irc = callbacks.SimpleProxy(irc, msg) |
| 346 |
line = msg.args[1].rstrip() |
| 347 |
self._doKarma(irc, msg, msg.channel, line) |
| 348 |
|
| 349 |
@internationalizeDocstring |
| 350 |
def karma(self, irc, msg, args, channel, things): |
| 351 |
"""[<channel>] [<thing> ...] |
| 352 |
|
| 353 |
Returns the karma of <thing>. If <thing> is not given, returns the top |
| 354 |
N karmas, where N is determined by the config variable |
| 355 |
supybot.plugins.Karma.rankingDisplay. If one <thing> is given, returns |
| 356 |
the details of its karma; if more than one <thing> is given, returns |
| 357 |
the total karma of each of the things. <channel> is only necessary |
| 358 |
if the message isn't sent on the channel itself. |
| 359 |
""" |
| 360 |
if len(things) == 1: |
| 361 |
name = things[0] |
| 362 |
t = self.db.get(channel, name) |
| 363 |
if t is None: |
| 364 |
irc.reply(format(_('%s has neutral karma.'), name)) |
| 365 |
else: |
| 366 |
(added, subtracted) = t |
| 367 |
total = added - subtracted |
| 368 |
if self.registryValue('simpleOutput', channel, irc.network): |
| 369 |
s = format('%s: %i', name, total) |
| 370 |
else: |
| 371 |
s = format(_('Karma for %q has been increased %n and ' |
| 372 |
'decreased %n for a total karma of %s.'), |
| 373 |
name, (added, _('time')), |
| 374 |
(subtracted, _('time')), |
| 375 |
total) |
| 376 |
irc.reply(s) |
| 377 |
elif len(things) > 1: |
| 378 |
(L, neutrals) = self.db.gets(channel, things) |
| 379 |
if L: |
| 380 |
s = format('%L', [format('%s: %i', *t) for t in L]) |
| 381 |
if neutrals: |
| 382 |
neutral = format('. %L %h neutral karma', |
| 383 |
neutrals, len(neutrals)) |
| 384 |
s += neutral |
| 385 |
irc.reply(s + '.') |
| 386 |
else: |
| 387 |
irc.reply(_('I didn\'t know the karma for any of those ' |
| 388 |
'things.')) |
| 389 |
else: # No name was given. Return the top/bottom N karmas. |
| 390 |
limit = self.registryValue('rankingDisplay', channel, irc.network) |
| 391 |
highest = [format('%q (%s)', s, t) |
| 392 |
for (s, t) in self.db.top(channel, limit)] |
| 393 |
lowest = [format('%q (%s)', s, t) |
| 394 |
for (s, t) in self.db.bottom(channel, limit)] |
| 395 |
if not (highest and lowest): |
| 396 |
irc.error(_('I have no karma for this channel.')) |
| 397 |
return |
| 398 |
rank = self.db.rank(channel, msg.nick) |
| 399 |
if rank is not None: |
| 400 |
total = self.db.size(channel) |
| 401 |
rankS = format(_(' You (%s) are ranked %i out of %i.'), |
| 402 |
msg.nick, rank, total) |
| 403 |
else: |
| 404 |
rankS = '' |
| 405 |
s = format(_('Highest karma: %L. Lowest karma: %L.%s'), |
| 406 |
highest, lowest, rankS) |
| 407 |
irc.reply(s) |
| 408 |
karma = wrap(karma, ['channel', any('something')]) |
| 409 |
|
| 410 |
_mostAbbrev = utils.abbrev(['increased', 'decreased', 'active']) |
| 411 |
@internationalizeDocstring |
| 412 |
def most(self, irc, msg, args, channel, kind): |
| 413 |
"""[<channel>] {increased,decreased,active} |
| 414 |
|
| 415 |
Returns the most increased, the most decreased, or the most active |
| 416 |
(the sum of increased and decreased) karma things. <channel> is only |
| 417 |
necessary if the message isn't sent in the channel itself. |
| 418 |
""" |
| 419 |
L = self.db.most(channel, kind, |
| 420 |
self.registryValue('mostDisplay', |
| 421 |
channel, irc.network)) |
| 422 |
if L: |
| 423 |
L = [format('%q: %i', name, i) for (name, i) in L] |
| 424 |
irc.reply(format('%L', L)) |
| 425 |
else: |
| 426 |
irc.error(_('I have no karma for this channel.')) |
| 427 |
most = wrap(most, ['channel', |
| 428 |
('literal', ['increased', 'decreased', 'active'])]) |
| 429 |
|
| 430 |
@internationalizeDocstring |
| 431 |
def clear(self, irc, msg, args, channel, name): |
| 432 |
"""[<channel>] [<name>] |
| 433 |
|
| 434 |
Resets the karma of <name> to 0. If <name> is not given, resets |
| 435 |
everything. |
| 436 |
""" |
| 437 |
self.db.clear(channel, name or None) |
| 438 |
irc.replySuccess() |
| 439 |
clear = wrap(clear, [('checkChannelCapability', 'op'), optional('text')]) |
| 440 |
|
| 441 |
@internationalizeDocstring |
| 442 |
def dump(self, irc, msg, args, channel, filename): |
| 443 |
"""[<channel>] <filename> |
| 444 |
|
| 445 |
Dumps the Karma database for <channel> to <filename> in the bot's |
| 446 |
data directory. <channel> is only necessary if the message isn't sent |
| 447 |
in the channel itself. |
| 448 |
""" |
| 449 |
checkAllowShell(irc) |
| 450 |
self.db.dump(channel, filename) |
| 451 |
irc.replySuccess() |
| 452 |
dump = wrap(dump, [('checkCapability', 'owner'), 'channeldb', 'filename']) |
| 453 |
|
| 454 |
@internationalizeDocstring |
| 455 |
def load(self, irc, msg, args, channel, filename): |
| 456 |
"""[<channel>] <filename> |
| 457 |
|
| 458 |
Loads the Karma database for <channel> from <filename> in the bot's |
| 459 |
data directory. <channel> is only necessary if the message isn't sent |
| 460 |
in the channel itself. |
| 461 |
""" |
| 462 |
checkAllowShell(irc) |
| 463 |
self.db.load(channel, filename) |
| 464 |
irc.replySuccess() |
| 465 |
load = wrap(load, [('checkCapability', 'owner'), 'channeldb', 'filename']) |
| 466 |
|
| 467 |
Class = Karma |
| 468 |
|
| 469 |
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: |