2005-04-17 21:43:09 +02:00
|
|
|
###
|
|
|
|
# Copyright (c) 2002-2005, Jeremiah Fincher
|
2010-02-06 00:50:03 +01:00
|
|
|
# Copyright (c) 2009-2010, James Vega
|
2005-04-17 21:43:09 +02:00
|
|
|
# All rights reserved.
|
|
|
|
#
|
|
|
|
# Redistribution and use in source and binary forms, with or without
|
|
|
|
# modification, are permitted provided that the following conditions are met:
|
|
|
|
#
|
|
|
|
# * Redistributions of source code must retain the above copyright notice,
|
|
|
|
# this list of conditions, and the following disclaimer.
|
|
|
|
# * Redistributions in binary form must reproduce the above copyright notice,
|
|
|
|
# this list of conditions, and the following disclaimer in the
|
|
|
|
# documentation and/or other materials provided with the distribution.
|
|
|
|
# * Neither the name of the author of this software nor the name of
|
|
|
|
# contributors to this software may be used to endorse or promote products
|
|
|
|
# derived from this software without specific prior written consent.
|
|
|
|
#
|
|
|
|
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
|
|
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
|
|
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
|
|
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
|
|
|
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
|
|
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
|
|
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
|
|
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
|
|
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
|
|
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
|
|
# POSSIBILITY OF SUCH DAMAGE.
|
|
|
|
###
|
|
|
|
|
|
|
|
import os
|
|
|
|
import time
|
|
|
|
import string
|
|
|
|
|
|
|
|
import supybot.conf as conf
|
|
|
|
import supybot.ircdb as ircdb
|
|
|
|
import supybot.utils as utils
|
|
|
|
from supybot.commands import *
|
|
|
|
import supybot.plugins as plugins
|
|
|
|
import supybot.ircutils as ircutils
|
|
|
|
import supybot.callbacks as callbacks
|
2010-10-17 11:22:07 +02:00
|
|
|
from supybot.i18n import PluginInternationalization, internationalizeDocstring
|
|
|
|
_ = PluginInternationalization('Factoids')
|
2005-04-17 21:43:09 +02:00
|
|
|
|
|
|
|
try:
|
2010-03-21 07:25:11 +01:00
|
|
|
import sqlite3
|
2005-04-17 21:43:09 +02:00
|
|
|
except ImportError:
|
2010-03-21 07:25:11 +01:00
|
|
|
from pysqlite2 import dbapi2 as sqlite3 # for python2.4
|
|
|
|
|
2010-04-07 18:33:28 +02:00
|
|
|
import re
|
|
|
|
from supybot.utils.seq import dameraulevenshtein
|
|
|
|
|
2005-04-17 21:43:09 +02:00
|
|
|
def getFactoid(irc, msg, args, state):
|
|
|
|
assert not state.channel
|
|
|
|
callConverter('channel', irc, msg, args, state)
|
|
|
|
separator = state.cb.registryValue('learnSeparator', state.channel)
|
|
|
|
try:
|
|
|
|
i = args.index(separator)
|
|
|
|
except ValueError:
|
|
|
|
raise callbacks.ArgumentError
|
|
|
|
args.pop(i)
|
|
|
|
key = []
|
|
|
|
value = []
|
|
|
|
for (j, s) in enumerate(args[:]):
|
|
|
|
if j < i:
|
|
|
|
key.append(args.pop(0))
|
|
|
|
else:
|
|
|
|
value.append(args.pop(0))
|
2010-02-06 00:50:03 +01:00
|
|
|
if not key or not value:
|
|
|
|
raise callbacks.ArgumentError
|
2005-04-17 21:43:09 +02:00
|
|
|
state.args.append(' '.join(key))
|
|
|
|
state.args.append(' '.join(value))
|
|
|
|
|
2005-04-17 23:38:17 +02:00
|
|
|
def getFactoidId(irc, msg, args, state):
|
|
|
|
Type = 'key id'
|
|
|
|
p = lambda i: i > 0
|
|
|
|
callConverter('int', irc, msg, args, state, Type, p)
|
|
|
|
|
2005-04-17 21:43:09 +02:00
|
|
|
addConverter('factoid', getFactoid)
|
2005-04-17 23:38:17 +02:00
|
|
|
addConverter('factoidId', getFactoidId)
|
2005-04-17 21:43:09 +02:00
|
|
|
|
|
|
|
class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
|
2009-04-06 23:30:53 +02:00
|
|
|
def __init__(self, irc):
|
|
|
|
callbacks.Plugin.__init__(self, irc)
|
|
|
|
plugins.ChannelDBHandler.__init__(self)
|
|
|
|
|
2005-04-17 21:43:09 +02:00
|
|
|
def makeDb(self, filename):
|
|
|
|
if os.path.exists(filename):
|
2010-03-21 07:25:11 +01:00
|
|
|
db = sqlite3.connect(filename)
|
|
|
|
db.text_factory = str
|
|
|
|
return db
|
|
|
|
db = sqlite3.connect(filename)
|
|
|
|
db.text_factory = str
|
2005-04-17 21:43:09 +02:00
|
|
|
cursor = db.cursor()
|
|
|
|
cursor.execute("""CREATE TABLE keys (
|
|
|
|
id INTEGER PRIMARY KEY,
|
2010-04-02 06:03:01 +02:00
|
|
|
key TEXT UNIQUE ON CONFLICT REPLACE
|
2005-04-17 21:43:09 +02:00
|
|
|
)""")
|
|
|
|
cursor.execute("""CREATE TABLE factoids (
|
|
|
|
id INTEGER PRIMARY KEY,
|
|
|
|
added_by TEXT,
|
|
|
|
added_at TIMESTAMP,
|
2010-04-02 06:03:01 +02:00
|
|
|
fact TEXT UNIQUE ON CONFLICT REPLACE,
|
|
|
|
locked BOOLEAN
|
|
|
|
)""")
|
|
|
|
cursor.execute("""CREATE TABLE relations (
|
|
|
|
id INTEGER PRIMARY KEY,
|
|
|
|
key_id INTEGER,
|
|
|
|
fact_id INTEGER,
|
|
|
|
usage_count INTEGER
|
2005-04-17 21:43:09 +02:00
|
|
|
)""")
|
|
|
|
db.commit()
|
|
|
|
return db
|
|
|
|
|
2009-05-18 17:09:18 +02:00
|
|
|
def getCommandHelp(self, command, simpleSyntax=None):
|
2006-08-28 15:14:21 +02:00
|
|
|
method = self.getCommandMethod(command)
|
|
|
|
if method.im_func.func_name == 'learn':
|
2009-04-28 14:03:21 +02:00
|
|
|
chan = None
|
|
|
|
if dynamic.msg is not None:
|
|
|
|
chan = dynamic.msg.args[0]
|
|
|
|
s = self.registryValue('learnSeparator', chan)
|
2008-12-22 03:21:07 +01:00
|
|
|
help = callbacks.getHelp
|
2009-05-18 17:09:18 +02:00
|
|
|
if simpleSyntax is None:
|
|
|
|
simpleSyntax = conf.get(conf.supybot.reply.showSimpleSyntax,
|
|
|
|
chan)
|
|
|
|
if simpleSyntax:
|
2008-12-22 03:21:07 +01:00
|
|
|
help = callbacks.getSyntax
|
|
|
|
return help(method,
|
|
|
|
doc=method._fake__doc__ % (s, s),
|
|
|
|
name=callbacks.formatCommand(command))
|
2009-05-18 17:09:18 +02:00
|
|
|
return super(Factoids, self).getCommandHelp(command, simpleSyntax)
|
2011-06-28 19:43:21 +02:00
|
|
|
|
2010-04-02 06:03:01 +02:00
|
|
|
def _getKeyAndFactId(self, channel, key, factoid):
|
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
|
|
|
cursor.execute("SELECT id FROM keys WHERE key=?", (key,))
|
|
|
|
keyresults = cursor.fetchall()
|
|
|
|
cursor.execute("SELECT id FROM factoids WHERE fact=?", (factoid,))
|
|
|
|
factresults = cursor.fetchall()
|
|
|
|
return (keyresults, factresults,)
|
|
|
|
|
2006-08-28 15:14:21 +02:00
|
|
|
def learn(self, irc, msg, args, channel, key, factoid):
|
2010-04-02 06:03:01 +02:00
|
|
|
|
|
|
|
# if neither key nor factoid exist, add them.
|
|
|
|
# if key exists but factoid doesn't, add factoid, link it to existing key
|
|
|
|
# if factoid exists but key doesn't, add key, link it to existing factoid
|
|
|
|
# if both key and factoid already exist, and are linked, do nothing, print nice message
|
2005-04-17 21:43:09 +02:00
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
2010-04-02 06:03:01 +02:00
|
|
|
(keyid, factid) = self._getKeyAndFactId(channel, key, factoid)
|
|
|
|
|
|
|
|
if len(keyid) == 0:
|
|
|
|
cursor.execute("""INSERT INTO keys VALUES (NULL, ?)""", (key,))
|
2005-04-17 21:43:09 +02:00
|
|
|
db.commit()
|
2010-04-02 06:03:01 +02:00
|
|
|
if len(factid) == 0:
|
2005-04-17 21:43:09 +02:00
|
|
|
if ircdb.users.hasUser(msg.prefix):
|
|
|
|
name = ircdb.users.getUser(msg.prefix).name
|
|
|
|
else:
|
|
|
|
name = msg.nick
|
|
|
|
cursor.execute("""INSERT INTO factoids VALUES
|
2010-04-02 06:03:01 +02:00
|
|
|
(NULL, ?, ?, ?, ?)""",
|
|
|
|
(name, int(time.time()), factoid, 0))
|
|
|
|
db.commit()
|
|
|
|
(keyid, factid) = self._getKeyAndFactId(channel, key, factoid)
|
|
|
|
|
|
|
|
cursor.execute("""SELECT id, key_id, fact_id from relations
|
|
|
|
WHERE key_id=? AND fact_id=?""",
|
|
|
|
(keyid[0][0], factid[0][0],))
|
|
|
|
existingrelation = cursor.fetchall()
|
|
|
|
if len(existingrelation) == 0:
|
|
|
|
cursor.execute("""INSERT INTO relations VALUES (NULL, ?, ?, ?)""",
|
|
|
|
(keyid[0][0],factid[0][0],0,))
|
2005-04-17 21:43:09 +02:00
|
|
|
db.commit()
|
|
|
|
irc.replySuccess()
|
|
|
|
else:
|
2010-04-02 06:03:01 +02:00
|
|
|
irc.error("This key-factoid relationship already exists.")
|
|
|
|
|
2005-04-17 21:43:09 +02:00
|
|
|
learn = wrap(learn, ['factoid'])
|
2010-10-17 11:22:07 +02:00
|
|
|
learn._fake__doc__ = _("""[<channel>] <key> %s <value>
|
2006-08-28 15:14:21 +02:00
|
|
|
|
|
|
|
Associates <key> with <value>. <channel> is only
|
|
|
|
necessary if the message isn't sent on the channel
|
|
|
|
itself. The word '%s' is necessary to separate the
|
|
|
|
key from the value. It can be changed to another word
|
|
|
|
via the learnSeparator registry value.
|
2010-10-17 11:22:07 +02:00
|
|
|
""")
|
2006-08-28 15:14:21 +02:00
|
|
|
|
2005-04-17 21:43:09 +02:00
|
|
|
|
|
|
|
def _lookupFactoid(self, channel, key):
|
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
2010-04-02 06:03:01 +02:00
|
|
|
cursor.execute("""SELECT factoids.fact, factoids.id, relations.id FROM factoids, keys, relations
|
|
|
|
WHERE keys.key LIKE ? AND relations.key_id=keys.id AND relations.fact_id=factoids.id
|
2005-04-17 21:43:09 +02:00
|
|
|
ORDER BY factoids.id
|
2010-03-21 07:25:11 +01:00
|
|
|
LIMIT 20""", (key,))
|
2010-03-05 19:03:08 +01:00
|
|
|
return cursor.fetchall()
|
|
|
|
|
2010-03-23 20:46:22 +01:00
|
|
|
def _searchFactoid(self, channel, key):
|
2010-04-07 18:33:28 +02:00
|
|
|
"""Try to typo-match input to possible factoids.
|
|
|
|
|
|
|
|
Assume first letter is correct, to reduce processing time.
|
|
|
|
First, try a simple wildcard search.
|
|
|
|
If that fails, use the Damerau-Levenshtein edit-distance metric.
|
|
|
|
"""
|
|
|
|
# if you made a typo in a two-character key, boo on you.
|
|
|
|
if len(key) < 3:
|
|
|
|
return []
|
|
|
|
|
2010-03-23 20:46:22 +01:00
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
2010-04-07 18:33:28 +02:00
|
|
|
cursor.execute("""SELECT key FROM keys WHERE key LIKE ?""", ('%' + key + '%',))
|
|
|
|
wildcardkeys = cursor.fetchall()
|
|
|
|
if len(wildcardkeys) > 0:
|
|
|
|
return [line[0] for line in wildcardkeys]
|
|
|
|
|
|
|
|
cursor.execute("""SELECT key FROM keys WHERE key LIKE ?""", (key[0] + '%',))
|
|
|
|
flkeys = cursor.fetchall()
|
|
|
|
if len(flkeys) == 0:
|
|
|
|
return []
|
|
|
|
flkeys = [line[0] for line in flkeys]
|
|
|
|
dl_metrics = [dameraulevenshtein(key, sourcekey) for sourcekey in flkeys]
|
|
|
|
dict_metrics = dict(zip(flkeys, dl_metrics))
|
|
|
|
if min(dl_metrics) <= 2:
|
|
|
|
return [key for key,item in dict_metrics.iteritems() if item <= 2]
|
|
|
|
if min(dl_metrics) <= 3:
|
|
|
|
return [key for key,item in dict_metrics.iteritems() if item <= 3]
|
|
|
|
|
|
|
|
return []
|
|
|
|
|
2010-03-05 19:03:08 +01:00
|
|
|
def _updateRank(self, channel, factoids):
|
|
|
|
if self.registryValue('keepRankInfo', channel):
|
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
2010-04-02 06:03:01 +02:00
|
|
|
for (fact,factid,relationid) in factoids:
|
|
|
|
cursor.execute("""SELECT relations.usage_count
|
|
|
|
FROM relations
|
|
|
|
WHERE relations.id=?""", (relationid,))
|
2010-03-05 19:03:08 +01:00
|
|
|
old_count = cursor.fetchall()[0][0]
|
2010-04-02 06:03:01 +02:00
|
|
|
cursor.execute("UPDATE relations SET usage_count=? WHERE id=?",
|
|
|
|
(old_count + 1, relationid,))
|
2010-03-05 19:03:08 +01:00
|
|
|
db.commit()
|
|
|
|
|
|
|
|
def _replyFactoids(self, irc, msg, key, channel, factoids,
|
2010-04-28 21:27:08 +02:00
|
|
|
number=0, error=True, raw=False):
|
|
|
|
def format_fact(text):
|
|
|
|
if raw:
|
|
|
|
return text
|
|
|
|
else:
|
|
|
|
return ircutils.standardSubstitute(irc, msg, text)
|
|
|
|
|
2005-04-17 21:43:09 +02:00
|
|
|
if factoids:
|
|
|
|
if number:
|
|
|
|
try:
|
2010-04-28 21:27:08 +02:00
|
|
|
irc.reply(format_fact(factoids[number-1][0]))
|
2010-03-05 19:03:08 +01:00
|
|
|
self._updateRank(channel, [factoids[number-1]])
|
2005-04-17 21:43:09 +02:00
|
|
|
except IndexError:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.error(_('That\'s not a valid number for that key.'))
|
2005-04-17 21:43:09 +02:00
|
|
|
return
|
|
|
|
else:
|
2009-10-16 04:37:59 +02:00
|
|
|
env = {'key': key}
|
|
|
|
def prefixer(v):
|
|
|
|
env['value'] = v
|
|
|
|
formatter = self.registryValue('format', msg.args[0])
|
|
|
|
return ircutils.standardSubstitute(irc, msg,
|
|
|
|
formatter, env)
|
2005-04-17 21:43:09 +02:00
|
|
|
if len(factoids) == 1:
|
2010-04-28 21:27:08 +02:00
|
|
|
irc.reply(format_fact(prefixer(factoids[0][0])))
|
2005-04-17 21:43:09 +02:00
|
|
|
else:
|
|
|
|
factoidsS = []
|
|
|
|
counter = 1
|
|
|
|
for factoid in factoids:
|
2010-04-28 06:10:48 +02:00
|
|
|
factoidsS.append(format('(#%i) %s', counter,
|
2010-04-28 21:27:08 +02:00
|
|
|
format_fact(factoid[0])))
|
2005-04-17 21:43:09 +02:00
|
|
|
counter += 1
|
2009-10-16 04:37:59 +02:00
|
|
|
irc.replies(factoidsS, prefixer=prefixer,
|
2005-04-17 21:43:09 +02:00
|
|
|
joiner=', or ', onlyPrefixFirst=True)
|
2010-03-05 19:03:08 +01:00
|
|
|
self._updateRank(channel, factoids)
|
2005-04-17 21:43:09 +02:00
|
|
|
elif error:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.error(_('No factoid matches that key.'))
|
2005-04-17 21:43:09 +02:00
|
|
|
|
2010-04-18 09:33:10 +02:00
|
|
|
def _replyApproximateFactoids(self, irc, msg, channel, key, error=True):
|
|
|
|
if self.registryValue('replyApproximateSearchKeys'):
|
|
|
|
factoids = self._searchFactoid(channel, key)
|
|
|
|
if factoids:
|
|
|
|
keylist = ["'%s'" % (fact,) for fact in factoids]
|
|
|
|
keylist = ', '.join(keylist)
|
|
|
|
irc.reply("I do not know about '%s', but I do know about these similar topics: %s" % (key, keylist))
|
|
|
|
elif error:
|
|
|
|
irc.error('No factoid matches that key.')
|
|
|
|
|
2005-04-17 23:38:17 +02:00
|
|
|
def invalidCommand(self, irc, msg, tokens):
|
2005-04-17 21:43:09 +02:00
|
|
|
if irc.isChannel(msg.args[0]):
|
|
|
|
channel = msg.args[0]
|
|
|
|
if self.registryValue('replyWhenInvalidCommand', channel):
|
|
|
|
key = ' '.join(tokens)
|
|
|
|
factoids = self._lookupFactoid(channel, key)
|
2010-03-23 20:46:22 +01:00
|
|
|
if factoids:
|
|
|
|
self._replyFactoids(irc, msg, key, channel, factoids, error=False)
|
|
|
|
else:
|
2010-04-18 09:33:10 +02:00
|
|
|
self._replyApproximateFactoids(irc, msg, channel, key, error=False)
|
2005-04-17 21:43:09 +02:00
|
|
|
|
2010-10-17 11:22:07 +02:00
|
|
|
@internationalizeDocstring
|
2010-04-28 21:27:08 +02:00
|
|
|
def whatis(self, irc, msg, args, channel, optlist, words):
|
|
|
|
"""[<channel>] [--raw] <key> [<number>]
|
2005-04-17 21:43:09 +02:00
|
|
|
|
|
|
|
Looks up the value of <key> in the factoid database. If given a
|
2010-04-28 21:27:08 +02:00
|
|
|
number, will return only that exact factoid. If '--raw' option is
|
|
|
|
given, no variable substitution will take place on the factoid.
|
|
|
|
<channel> is only necessary if the message isn't sent in the channel
|
|
|
|
itself.
|
2005-04-17 21:43:09 +02:00
|
|
|
"""
|
2010-04-28 21:27:08 +02:00
|
|
|
raw = False
|
|
|
|
for (option, arg) in optlist:
|
|
|
|
if option == 'raw':
|
|
|
|
raw = True
|
2005-04-18 03:58:57 +02:00
|
|
|
number = None
|
|
|
|
if len(words) > 1:
|
|
|
|
if words[-1].isdigit():
|
|
|
|
number = int(words.pop())
|
|
|
|
if number <= 0:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.errorInvalid(_('key id'))
|
2005-04-18 03:58:57 +02:00
|
|
|
key = ' '.join(words)
|
2005-04-17 21:43:09 +02:00
|
|
|
factoids = self._lookupFactoid(channel, key)
|
2010-04-18 09:33:10 +02:00
|
|
|
if factoids:
|
2010-04-28 21:27:08 +02:00
|
|
|
self._replyFactoids(irc, msg, key, channel, factoids, number, raw=raw)
|
2010-04-18 09:33:10 +02:00
|
|
|
else:
|
|
|
|
self._replyApproximateFactoids(irc, msg, channel, key)
|
2011-02-26 10:45:29 +01:00
|
|
|
whatis = wrap(whatis, ['channel',
|
2010-04-28 21:27:08 +02:00
|
|
|
getopts({'raw': '',}),
|
|
|
|
many('something')])
|
2011-02-26 10:45:29 +01:00
|
|
|
|
|
|
|
@internationalizeDocstring
|
2010-04-02 06:49:43 +02:00
|
|
|
def alias(self, irc, msg, args, channel, oldkey, newkey, number):
|
|
|
|
"""[<channel>] <oldkey> <newkey> [<number>]
|
|
|
|
|
|
|
|
Adds a new key <newkey> for factoid associated with <oldkey>.
|
|
|
|
<number> is only necessary if there's more than one factoid associated
|
|
|
|
with <oldkey>.
|
|
|
|
|
|
|
|
The same action can be accomplished by using the 'learn' function with
|
|
|
|
a new key but an existing (verbatim) factoid content.
|
|
|
|
"""
|
|
|
|
def _getNewKey(channel, newkey, arelation):
|
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
|
|
|
cursor.execute("""SELECT id FROM keys WHERE key=?""", (newkey,))
|
|
|
|
newkey_info = cursor.fetchall()
|
|
|
|
if len(newkey_info) == 1:
|
|
|
|
# check if we already have the requested relation
|
|
|
|
cursor.execute("""SELECT id FROM relations WHERE
|
|
|
|
key_id=? and fact_id=?""",
|
|
|
|
(arelation[1], arelation[2]))
|
|
|
|
existentrelation = cursor.fetchall()
|
|
|
|
if len(existentrelation) != 0:
|
|
|
|
newkey_info = False
|
|
|
|
if len(newkey_info) == 0:
|
|
|
|
cursor.execute("""INSERT INTO keys VALUES (NULL, ?)""",
|
|
|
|
(newkey,))
|
|
|
|
db.commit()
|
|
|
|
cursor.execute("""SELECT id FROM keys WHERE key=?""", (newkey,))
|
|
|
|
newkey_info = cursor.fetchall()
|
|
|
|
return newkey_info
|
|
|
|
|
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
|
|
|
cursor.execute("""SELECT relations.id, relations.key_id, relations.fact_id
|
|
|
|
FROM keys, relations
|
|
|
|
WHERE keys.key=? AND
|
|
|
|
relations.key_id=keys.id""", (oldkey,))
|
|
|
|
results = cursor.fetchall()
|
|
|
|
if len(results) == 0:
|
|
|
|
irc.error(_('No factoid matches that key.'))
|
|
|
|
return
|
|
|
|
elif len(results) == 1:
|
|
|
|
newkey_info = _getNewKey(channel, newkey, results[0])
|
|
|
|
if newkey_info is not False:
|
|
|
|
cursor.execute("""INSERT INTO relations VALUES(NULL, ?, ?, ?)""",
|
|
|
|
(newkey_info[0][0], results[0][2], 0,))
|
|
|
|
irc.replySuccess()
|
|
|
|
else:
|
|
|
|
irc.error(_('This key-factoid relationship already exists.'))
|
|
|
|
elif len(results) > 1:
|
|
|
|
try:
|
|
|
|
arelation = results[number-1]
|
|
|
|
except IndexError:
|
|
|
|
irc.error(_("That's not a valid number for that key."))
|
|
|
|
return
|
|
|
|
except TypeError:
|
|
|
|
irc.error(_("This key has more than one factoid associated "
|
|
|
|
"with it, but you have not provided a number."))
|
|
|
|
return
|
|
|
|
newkey_info = _getNewKey(channel, newkey, arelation)
|
|
|
|
if newkey_info is not False:
|
|
|
|
cursor.execute("""INSERT INTO relations VALUES(NULL, ?, ?, ?)""",
|
|
|
|
(newkey_info[0][0], arelation[2], 0,))
|
|
|
|
irc.replySuccess()
|
|
|
|
else:
|
|
|
|
irc.error(_('This key-factoid relationship already exists.'))
|
|
|
|
alias = wrap(alias, ['channel', 'something', 'something', optional('int')])
|
|
|
|
|
2010-03-05 19:03:08 +01:00
|
|
|
@internationalizeDocstring
|
2010-04-25 08:58:43 +02:00
|
|
|
def rank(self, irc, msg, args, channel, optlist, number):
|
|
|
|
"""[<channel>] [--plain] [--alpha] [<number>]
|
2010-03-05 19:03:08 +01:00
|
|
|
|
|
|
|
Returns a list of top-ranked factoid keys, sorted by usage count
|
2010-04-25 08:58:43 +02:00
|
|
|
(rank). If <number> is not provided, the default number of factoid keys
|
|
|
|
returned is set by the rankListLength registry value.
|
|
|
|
|
|
|
|
If --plain option is given, rank numbers and usage counts are not
|
|
|
|
included in output.
|
|
|
|
|
|
|
|
If --alpha option is given in addition to --plain, keys are sorted
|
|
|
|
alphabetically, instead of by rank.
|
|
|
|
|
|
|
|
<channel> is only necessary if the message isn't sent in the channel
|
|
|
|
itself.
|
2010-03-05 19:03:08 +01:00
|
|
|
"""
|
2010-04-25 08:58:43 +02:00
|
|
|
if not number:
|
|
|
|
number = self.registryValue('rankListLength', channel)
|
2010-03-05 19:03:08 +01:00
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
2010-04-02 06:03:01 +02:00
|
|
|
cursor.execute("""SELECT keys.key, relations.usage_count
|
|
|
|
FROM keys, relations
|
|
|
|
WHERE relations.key_id=keys.id
|
|
|
|
ORDER BY relations.usage_count DESC
|
2010-04-25 08:58:43 +02:00
|
|
|
LIMIT ?""", (number,))
|
2010-03-05 19:03:08 +01:00
|
|
|
factkeys = cursor.fetchall()
|
2010-04-25 08:58:43 +02:00
|
|
|
plain=False
|
|
|
|
alpha=False
|
|
|
|
for (option, arg) in optlist:
|
|
|
|
if option == 'plain':
|
|
|
|
plain = True
|
|
|
|
elif option =='alpha':
|
|
|
|
alpha = True
|
|
|
|
if plain:
|
|
|
|
s = [ "%s" % (key[0],) for i, key in enumerate(factkeys) ]
|
|
|
|
if alpha:
|
|
|
|
s.sort()
|
|
|
|
else:
|
|
|
|
s = [ "#%d %s (%d)" % (i+1, key[0], key[1]) for i, key in enumerate(factkeys) ]
|
2010-03-05 19:03:08 +01:00
|
|
|
irc.reply(", ".join(s))
|
2010-04-25 08:58:43 +02:00
|
|
|
rank = wrap(rank, ['channel',
|
|
|
|
getopts({'plain': '', 'alpha': '',}),
|
|
|
|
optional('int')])
|
2010-04-28 21:27:08 +02:00
|
|
|
|
|
|
|
@internationalizeDocstring
|
2005-04-17 21:43:09 +02:00
|
|
|
def lock(self, irc, msg, args, channel, key):
|
|
|
|
"""[<channel>] <key>
|
|
|
|
|
|
|
|
Locks the factoid(s) associated with <key> so that they cannot be
|
|
|
|
removed or added to. <channel> is only necessary if the message isn't
|
|
|
|
sent in the channel itself.
|
|
|
|
"""
|
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
2010-04-02 06:03:01 +02:00
|
|
|
cursor.execute("UPDATE factoids, keys, relations "
|
|
|
|
"SET factoids.locked=1 WHERE key LIKE ? AND "
|
|
|
|
"factoids.id=relations.fact_id AND "
|
|
|
|
"keys.id=relations.key_id", (key,))
|
2005-04-17 21:43:09 +02:00
|
|
|
db.commit()
|
|
|
|
irc.replySuccess()
|
|
|
|
lock = wrap(lock, ['channel', 'text'])
|
|
|
|
|
2010-10-17 11:22:07 +02:00
|
|
|
@internationalizeDocstring
|
2005-04-17 21:43:09 +02:00
|
|
|
def unlock(self, irc, msg, args, channel, key):
|
|
|
|
"""[<channel>] <key>
|
|
|
|
|
|
|
|
Unlocks the factoid(s) associated with <key> so that they can be
|
|
|
|
removed or added to. <channel> is only necessary if the message isn't
|
|
|
|
sent in the channel itself.
|
|
|
|
"""
|
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
2010-04-02 06:03:01 +02:00
|
|
|
cursor.execute("""UPDATE factoids, keys, relations
|
|
|
|
SET factoids.locked=1 WHERE key LIKE ? AND
|
|
|
|
factoids.id=relations.fact_id AND
|
|
|
|
keys.id=relations.key_id""", (key,))
|
2005-04-17 21:43:09 +02:00
|
|
|
db.commit()
|
|
|
|
irc.replySuccess()
|
|
|
|
unlock = wrap(unlock, ['channel', 'text'])
|
|
|
|
|
2010-04-02 06:03:01 +02:00
|
|
|
def _deleteRelation(self, channel, relationlist):
|
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
|
|
|
for (keyid, factid, relationid) in relationlist:
|
|
|
|
cursor.execute("""DELETE FROM relations where relations.id=?""",
|
|
|
|
(relationid,))
|
|
|
|
db.commit()
|
|
|
|
|
|
|
|
cursor.execute("""SELECT id FROM relations
|
|
|
|
WHERE relations.key_id=?""", (keyid,))
|
|
|
|
remaining_key_relations = cursor.fetchall()
|
|
|
|
if len(remaining_key_relations) == 0:
|
|
|
|
cursor.execute("""DELETE FROM keys where id=?""", (keyid,))
|
|
|
|
|
|
|
|
cursor.execute("""SELECT id FROM relations
|
|
|
|
WHERE relations.fact_id=?""", (factid,))
|
|
|
|
remaining_fact_relations = cursor.fetchall()
|
|
|
|
if len(remaining_fact_relations) == 0:
|
|
|
|
cursor.execute("""DELETE FROM factoids where id=?""", (factid,))
|
|
|
|
db.commit()
|
|
|
|
|
2010-10-17 11:22:07 +02:00
|
|
|
@internationalizeDocstring
|
2005-04-18 03:58:57 +02:00
|
|
|
def forget(self, irc, msg, args, channel, words):
|
2005-04-17 21:43:09 +02:00
|
|
|
"""[<channel>] <key> [<number>|*]
|
|
|
|
|
2010-04-02 06:03:01 +02:00
|
|
|
Removes a key-fact relationship for key <key> from the factoids
|
|
|
|
database. If there is more than one such relationship for this key,
|
|
|
|
a number is necessary to determine which one should be removed.
|
|
|
|
A * can be used to remove all relationships for <key>.
|
|
|
|
|
|
|
|
If as a result, the key (factoid) remains without any relationships to
|
|
|
|
a factoid (key), it shall be removed from the database.
|
|
|
|
|
|
|
|
<channel> is only necessary if
|
2005-04-17 21:43:09 +02:00
|
|
|
the message isn't sent in the channel itself.
|
|
|
|
"""
|
2005-04-18 03:58:57 +02:00
|
|
|
number = None
|
|
|
|
if len(words) > 1:
|
|
|
|
if words[-1].isdigit():
|
|
|
|
number = int(words.pop())
|
|
|
|
if number <= 0:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.errorInvalid(_('key id'))
|
2005-04-18 03:58:57 +02:00
|
|
|
elif words[-1] == '*':
|
|
|
|
words.pop()
|
|
|
|
number = True
|
|
|
|
key = ' '.join(words)
|
2005-04-17 21:43:09 +02:00
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
2010-04-02 06:03:01 +02:00
|
|
|
cursor.execute("""SELECT keys.id, factoids.id, relations.id
|
|
|
|
FROM keys, factoids, relations
|
|
|
|
WHERE key LIKE ? AND
|
|
|
|
relations.key_id=keys.id AND
|
|
|
|
relations.fact_id=factoids.id""", (key,))
|
2010-03-21 07:25:11 +01:00
|
|
|
results = cursor.fetchall()
|
|
|
|
if len(results) == 0:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.error(_('There is no such factoid.'))
|
2010-03-21 07:25:11 +01:00
|
|
|
elif len(results) == 1 or number is True:
|
2010-04-02 06:03:01 +02:00
|
|
|
self._deleteRelation(channel, results)
|
2005-04-17 21:43:09 +02:00
|
|
|
irc.replySuccess()
|
|
|
|
else:
|
|
|
|
if number is not None:
|
2010-03-21 07:25:11 +01:00
|
|
|
#results = cursor.fetchall()
|
2005-04-17 21:43:09 +02:00
|
|
|
try:
|
2010-04-02 06:03:01 +02:00
|
|
|
arelation = results[number-1]
|
2005-04-17 21:43:09 +02:00
|
|
|
except IndexError:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.error(_('Invalid factoid number.'))
|
2005-04-17 21:43:09 +02:00
|
|
|
return
|
2010-04-02 06:03:01 +02:00
|
|
|
self._deleteRelation(channel, [arelation,])
|
2005-04-17 21:43:09 +02:00
|
|
|
irc.replySuccess()
|
|
|
|
else:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.error(_('%s factoids have that key. '
|
2005-04-17 21:43:09 +02:00
|
|
|
'Please specify which one to remove, '
|
2010-10-17 11:22:07 +02:00
|
|
|
'or use * to designate all of them.') %
|
2010-03-21 07:25:11 +01:00
|
|
|
len(results))
|
2005-04-18 03:58:57 +02:00
|
|
|
forget = wrap(forget, ['channel', many('something')])
|
2005-04-17 21:43:09 +02:00
|
|
|
|
2010-10-17 11:22:07 +02:00
|
|
|
@internationalizeDocstring
|
2005-04-17 21:43:09 +02:00
|
|
|
def random(self, irc, msg, args, channel):
|
|
|
|
"""[<channel>]
|
|
|
|
|
|
|
|
Returns a random factoid from the database for <channel>. <channel>
|
|
|
|
is only necessary if the message isn't sent in the channel itself.
|
|
|
|
"""
|
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
2010-04-02 06:03:01 +02:00
|
|
|
cursor.execute("""SELECT id, key_id, fact_id FROM relations
|
2005-04-17 21:43:09 +02:00
|
|
|
ORDER BY random()
|
|
|
|
LIMIT 3""")
|
2010-03-21 07:25:11 +01:00
|
|
|
results = cursor.fetchall()
|
|
|
|
if len(results) != 0:
|
2005-04-17 21:43:09 +02:00
|
|
|
L = []
|
2010-04-02 06:03:01 +02:00
|
|
|
for (relationid, keyid, factid) in results:
|
|
|
|
cursor.execute("""SELECT keys.key, factoids.fact
|
|
|
|
FROM keys, factoids
|
|
|
|
WHERE factoids.id=? AND
|
|
|
|
keys.id=?""", (factid,keyid,))
|
|
|
|
(key,factoid) = cursor.fetchall()[0]
|
2005-04-17 21:43:09 +02:00
|
|
|
L.append('"%s": %s' % (ircutils.bold(key), factoid))
|
|
|
|
irc.reply('; '.join(L))
|
|
|
|
else:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.error(_('I couldn\'t find a factoid.'))
|
2005-04-17 21:43:09 +02:00
|
|
|
random = wrap(random, ['channel'])
|
|
|
|
|
2010-10-17 11:22:07 +02:00
|
|
|
@internationalizeDocstring
|
2005-04-17 21:43:09 +02:00
|
|
|
def info(self, irc, msg, args, channel, key):
|
|
|
|
"""[<channel>] <key>
|
|
|
|
|
|
|
|
Gives information about the factoid(s) associated with <key>.
|
|
|
|
<channel> is only necessary if the message isn't sent in the channel
|
|
|
|
itself.
|
|
|
|
"""
|
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
2010-04-02 06:03:01 +02:00
|
|
|
cursor.execute("SELECT id FROM keys WHERE key LIKE ?", (key,))
|
2010-03-21 07:25:11 +01:00
|
|
|
results = cursor.fetchall()
|
|
|
|
if len(results) == 0:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.error(_('No factoid matches that key.'))
|
2005-04-17 21:43:09 +02:00
|
|
|
return
|
2010-04-02 06:03:01 +02:00
|
|
|
id = results[0][0]
|
|
|
|
cursor.execute("""SELECT factoids.added_by, factoids.added_at, factoids.locked, relations.usage_count
|
|
|
|
FROM factoids, relations
|
|
|
|
WHERE relations.key_id=? AND
|
|
|
|
relations.fact_id=factoids.id
|
|
|
|
ORDER BY relations.id""", (id,))
|
2005-04-17 21:43:09 +02:00
|
|
|
factoids = cursor.fetchall()
|
|
|
|
L = []
|
|
|
|
counter = 0
|
2010-04-02 06:03:01 +02:00
|
|
|
for (added_by, added_at, locked, usage_count) in factoids:
|
2005-04-17 21:43:09 +02:00
|
|
|
counter += 1
|
2009-02-27 20:17:05 +01:00
|
|
|
added_at = time.strftime(conf.supybot.reply.format.time(),
|
|
|
|
time.localtime(int(added_at)))
|
2010-04-01 06:51:25 +02:00
|
|
|
L.append(format(_('#%i was added by %s at %s, and has been '
|
|
|
|
'recalled %n'),
|
2011-02-26 10:45:29 +01:00
|
|
|
counter, added_by, added_at,
|
|
|
|
(usage_count, _('time'))))
|
2005-04-17 21:43:09 +02:00
|
|
|
factoids = '; '.join(L)
|
|
|
|
s = format('Key %q is %s and has %n associated with it: %s',
|
|
|
|
key, locked and 'locked' or 'not locked',
|
|
|
|
(counter, 'factoid'), factoids)
|
|
|
|
irc.reply(s)
|
|
|
|
info = wrap(info, ['channel', 'text'])
|
|
|
|
|
2010-10-17 11:22:07 +02:00
|
|
|
@internationalizeDocstring
|
2005-04-17 21:43:09 +02:00
|
|
|
def change(self, irc, msg, args, channel, key, number, replacer):
|
|
|
|
"""[<channel>] <key> <number> <regexp>
|
|
|
|
|
|
|
|
Changes the factoid #<number> associated with <key> according to
|
|
|
|
<regexp>.
|
|
|
|
"""
|
|
|
|
db = self.getDb(channel)
|
|
|
|
cursor = db.cursor()
|
|
|
|
cursor.execute("""SELECT factoids.id, factoids.fact
|
2010-04-02 06:03:01 +02:00
|
|
|
FROM keys, factoids, relations
|
|
|
|
WHERE keys.key LIKE ? AND
|
|
|
|
keys.id=relations.key_id AND
|
|
|
|
factoids.id=relations.fact_id""", (key,))
|
2010-03-21 07:25:11 +01:00
|
|
|
results = cursor.fetchall()
|
|
|
|
if len(results) == 0:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.error(format(_('I couldn\'t find any key %q'), key))
|
2005-04-17 21:43:09 +02:00
|
|
|
return
|
2010-03-21 07:25:11 +01:00
|
|
|
elif len(results) < number:
|
|
|
|
irc.errorInvalid('key id')
|
|
|
|
(id, fact) = results[number-1]
|
2005-04-17 21:43:09 +02:00
|
|
|
newfact = replacer(fact)
|
2010-03-21 07:25:11 +01:00
|
|
|
cursor.execute("UPDATE factoids SET fact=? WHERE id=?", (newfact, id))
|
2005-04-17 21:43:09 +02:00
|
|
|
db.commit()
|
|
|
|
irc.replySuccess()
|
|
|
|
change = wrap(change, ['channel', 'something',
|
2005-04-17 23:38:17 +02:00
|
|
|
'factoidId', 'regexpReplacer'])
|
2005-04-17 21:43:09 +02:00
|
|
|
|
|
|
|
_sqlTrans = string.maketrans('*?', '%_')
|
2010-10-17 11:22:07 +02:00
|
|
|
@internationalizeDocstring
|
2005-04-17 21:43:09 +02:00
|
|
|
def search(self, irc, msg, args, channel, optlist, globs):
|
|
|
|
"""[<channel>] [--values] [--{regexp} <value>] [<glob> ...]
|
|
|
|
|
|
|
|
Searches the keyspace for keys matching <glob>. If --regexp is given,
|
2011-07-18 15:23:06 +02:00
|
|
|
its associated value is taken as a regexp and matched against the keys.
|
2005-04-17 21:43:09 +02:00
|
|
|
If --values is given, search the value space instead of the keyspace.
|
|
|
|
"""
|
|
|
|
if not optlist and not globs:
|
|
|
|
raise callbacks.ArgumentError
|
|
|
|
tables = ['keys']
|
|
|
|
formats = []
|
|
|
|
criteria = []
|
|
|
|
target = 'keys.key'
|
|
|
|
predicateName = 'p'
|
|
|
|
db = self.getDb(channel)
|
|
|
|
for (option, arg) in optlist:
|
|
|
|
if option == 'values':
|
|
|
|
target = 'factoids.fact'
|
|
|
|
if 'factoids' not in tables:
|
|
|
|
tables.append('factoids')
|
2010-04-02 06:03:01 +02:00
|
|
|
tables.append('relations')
|
|
|
|
criteria.append('factoids.id=relations.fact_id AND keys.id=relations.key_id')
|
2005-04-17 21:43:09 +02:00
|
|
|
elif option == 'regexp':
|
|
|
|
criteria.append('%s(TARGET)' % predicateName)
|
|
|
|
def p(s, r=arg):
|
|
|
|
return int(bool(r.search(s)))
|
|
|
|
db.create_function(predicateName, 1, p)
|
|
|
|
predicateName += 'p'
|
|
|
|
for glob in globs:
|
2010-03-21 07:25:11 +01:00
|
|
|
criteria.append('TARGET LIKE ?')
|
2005-04-17 21:43:09 +02:00
|
|
|
formats.append(glob.translate(self._sqlTrans))
|
|
|
|
cursor = db.cursor()
|
|
|
|
sql = """SELECT keys.key FROM %s WHERE %s""" % \
|
|
|
|
(', '.join(tables), ' AND '.join(criteria))
|
2010-03-05 20:51:25 +01:00
|
|
|
sql = sql + " ORDER BY keys.key"
|
2005-04-17 21:43:09 +02:00
|
|
|
sql = sql.replace('TARGET', target)
|
|
|
|
cursor.execute(sql, formats)
|
|
|
|
if cursor.rowcount == 0:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.reply(_('No keys matched that query.'))
|
2005-04-17 21:43:09 +02:00
|
|
|
elif cursor.rowcount == 1 and \
|
|
|
|
self.registryValue('showFactoidIfOnlyOneMatch', channel):
|
2010-04-11 17:04:45 +02:00
|
|
|
self.whatis(irc, msg, [channel, cursor.fetchone()[0]])
|
2005-04-17 21:43:09 +02:00
|
|
|
elif cursor.rowcount > 100:
|
2010-10-17 11:22:07 +02:00
|
|
|
irc.reply(_('More than 100 keys matched that query; '
|
|
|
|
'please narrow your query.'))
|
2010-03-21 07:25:11 +01:00
|
|
|
results = cursor.fetchall()
|
|
|
|
if len(results) == 0:
|
|
|
|
irc.reply(_('No keys matched that query.'))
|
|
|
|
elif len(results) == 1 and \
|
|
|
|
self.registryValue('showFactoidIfOnlyOneMatch', channel):
|
2010-04-11 07:23:27 +02:00
|
|
|
self.whatis(irc, msg, [channel, results[0][0]])
|
2010-03-21 07:25:11 +01:00
|
|
|
elif len(results) > 100:
|
|
|
|
irc.reply(_('More than 100 keys matched that query; '
|
|
|
|
'please narrow your query.'))
|
2005-04-17 21:43:09 +02:00
|
|
|
else:
|
2010-03-21 07:25:11 +01:00
|
|
|
keys = [repr(t[0]) for t in results]
|
2005-04-17 21:43:09 +02:00
|
|
|
s = format('%L', keys)
|
|
|
|
irc.reply(s)
|
|
|
|
search = wrap(search, ['channel',
|
|
|
|
getopts({'values': '', 'regexp': 'regexpMatcher'}),
|
|
|
|
any('glob')])
|
|
|
|
|
|
|
|
|
|
|
|
Class = Factoids
|
|
|
|
|
|
|
|
|
2006-02-11 16:52:51 +01:00
|
|
|
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
|