Limnoria/plugins/Quotes.py

260 lines
9.8 KiB
Python
Raw Normal View History

2003-03-12 07:26:59 +01:00
#!/usr/bin/env python
###
# Copyright (c) 2002, Jeremiah Fincher
# 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.
###
"""
Maintains a Quotes database for each channel.
"""
2003-03-12 07:26:59 +01:00
from baseplugin import *
import re
import time
2003-08-26 19:07:37 +02:00
import getopt
2003-03-12 07:26:59 +01:00
import os.path
import sqlite
2003-08-26 19:07:37 +02:00
import utils
2003-03-12 07:26:59 +01:00
import ircdb
import privmsgs
import callbacks
2003-03-28 06:15:08 +01:00
class Quotes(ChannelDBHandler, callbacks.Privmsg):
2003-03-12 07:26:59 +01:00
def __init__(self):
2003-03-28 06:15:08 +01:00
ChannelDBHandler.__init__(self)
2003-03-12 07:26:59 +01:00
callbacks.Privmsg.__init__(self)
def makeDb(self, filename):
if os.path.exists(filename):
return sqlite.connect(db=filename, mode=0755,
converters={'bool': bool})
#else:
db = sqlite.connect(db=filename, mode=0755, coverters={'bool': bool})
cursor = db.cursor()
cursor.execute("""CREATE TABLE quotes (
id INTEGER PRIMARY KEY,
2003-08-26 19:07:37 +02:00
added_by TEXT,
2003-03-12 07:26:59 +01:00
added_at TIMESTAMP,
quote TEXT
);""")
2003-08-26 19:07:37 +02:00
cursor.execute("""CREATE TABLE quotegrabs (
id INTEGER PRIMARY KEY,
nick TEXT,
added_by TEXT,
quote TEXT
);""")
2003-03-12 07:26:59 +01:00
db.commit()
return db
def addquote(self, irc, msg, args):
2003-08-26 19:07:37 +02:00
"""[<channel>] <quote>
Adds <quote> to the quotes database for <channel>. <channel> is only
necessary if the message isn't sent in the channel itself.
"""
2003-03-12 07:26:59 +01:00
channel = privmsgs.getChannel(msg, args)
quote = privmsgs.getArgs(args)
db = self.getDb(channel)
cursor = db.cursor()
quotetime = int(time.time())
2003-03-12 07:26:59 +01:00
cursor.execute("""INSERT INTO quotes
VALUES(NULL, %s, %s, %s)""",
msg.nick, quotetime, quote)
2003-03-12 07:26:59 +01:00
db.commit()
criteria = ['added_by="%s"' % msg.nick]
criteria.append('added_at=%s' % quotetime)
criteria.append('quote="%s"' % quote)
sql = """SELECT id FROM quotes WHERE %s""" % ' AND '.join(criteria)
cursor.execute(sql)
quoteid = cursor.fetchone()[0]
irc.reply(msg, '%s (Quote #%s added)' % (conf.replySuccess, quoteid))
2003-03-12 07:26:59 +01:00
2003-08-26 19:07:37 +02:00
def numquotes(self, irc, msg, args):
"""[<channel>]
Returns the numbers of quotes in the quote database for <channel>.
<channel> is only necessary if the message isn't sent in the channel
itself.
"""
2003-03-12 07:26:59 +01:00
channel = privmsgs.getChannel(msg, args)
db = self.getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT COUNT(*) FROM quotes""")
2003-08-26 19:07:37 +02:00
maxid = int(cursor.fetchone()[0])
2003-03-12 07:26:59 +01:00
if maxid is None:
maxid = 0
2003-08-26 19:07:37 +02:00
if maxid == 1:
IS = 'is'
QUOTE = 'quote'
else:
IS = 'are'
QUOTE = 'quotes'
s = 'There %s %s %s in my database.' % (IS, maxid, QUOTE)
2003-03-12 07:26:59 +01:00
irc.reply(msg, s)
def quote(self, irc, msg, args):
2003-09-23 00:11:05 +02:00
"""[<channel>] --{id,regexp,from,with}=<value> ]
2003-08-26 19:07:37 +02:00
Returns quote(s) matching the given criteria. --from is who added the
quote; --id is the id number of the quote; --regexp is a regular
expression to search for.
"""
2003-03-12 07:26:59 +01:00
channel = privmsgs.getChannel(msg, args)
2003-09-23 00:11:05 +02:00
(optlist, rest) = getopt.getopt(args, '', ['id=', 'regexp=',
'from=', 'with='])
2003-08-26 19:07:37 +02:00
if not optlist and not rest:
raise callbacks.ArgumentError
criteria = []
formats = []
predicateName = ''
2003-03-12 07:26:59 +01:00
db = self.getDb(channel)
2003-08-26 19:07:37 +02:00
for (option, argument) in optlist:
option = option.lstrip('-')
if option == 'id':
try:
argument = int(argument)
criteria.append('id=%s' % argument)
except ValueError:
irc.error(msg, '--id value must be an integer.')
return
2003-09-23 00:11:05 +02:00
elif option == 'with':
criteria.append('quote LIKE %s')
formats.append('%%%s%%' % argument)
2003-08-26 19:07:37 +02:00
elif option == 'from':
criteria.append('added_by=%s')
formats.append(argument)
elif option == 'regexp':
try:
r = utils.perlReToPythonRe(argument)
except ValueError:
try:
r = re.compile(argument, re.I)
except re.error, e:
irc.error(msg, str(e))
return
2003-08-26 19:07:37 +02:00
def p(s):
return int(bool(r.search(s)))
2003-08-26 19:07:37 +02:00
predicateName += 'p'
db.create_function(predicateName, 1, p)
criteria.append('%s(quote)' % predicateName)
for s in rest:
try:
i = int(s)
criteria.append('id=%s' % i)
except ValueError:
s = '%%%s%%' % s
criteria.append('quote LIKE %s')
formats.append(s)
2003-08-26 19:07:37 +02:00
sql = """SELECT id, quote FROM quotes
WHERE %s""" % ' AND '.join(criteria)
#debug.printf(sql)
2003-03-12 07:26:59 +01:00
cursor = db.cursor()
2003-08-26 19:07:37 +02:00
cursor.execute(sql, *formats)
if cursor.rowcount == 0:
irc.reply(msg, 'No quotes matched that criteria.')
elif cursor.rowcount == 1:
(id, quote) = cursor.fetchone()
irc.reply(msg, '#%s: %s' % (id, quote))
elif cursor.rowcount > 10:
irc.reply(msg, 'More than 10 quotes matched your criteria. '
'Please narrow your query.')
else:
results = cursor.fetchall()
idsWithSnippets = []
for (id, quote) in results:
s = '#%s: "%s..."' % (id, quote[:30])
idsWithSnippets.append(s)
irc.reply(msg, utils.commaAndify(idsWithSnippets))
### FIXME: we need to remove those predicates from the database.
2003-03-12 07:26:59 +01:00
def randomquote(self, irc, msg, args):
2003-08-26 19:07:37 +02:00
"""[<channel>]
Returns a random quote from <channel>. <channel> is only necessary if
the message isn't sent in the channel itself.
"""
2003-03-12 07:26:59 +01:00
channel = privmsgs.getChannel(msg, args)
db = self.getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT id FROM quotes
2003-03-12 07:26:59 +01:00
ORDER BY random()
LIMIT 1""")
if cursor.rowcount != 1:
irc.error(msg, 'It seems that quote database is empty.')
return
(id,) = cursor.fetchone()
self.quote(irc, msg, [channel, '--id', str(id)])
2003-03-12 07:26:59 +01:00
def quoteinfo(self, irc, msg, args):
2003-08-26 19:07:37 +02:00
"""[<channel>] <id>
Returns the metadata about the quote <id> in the quotes
database for <channel>. <channel> is only necessary if the message
isn't sent in the channel itself.
"""
2003-03-12 07:26:59 +01:00
channel = privmsgs.getChannel(msg, args)
id = privmsgs.getArgs(args)
db = self.getDb(channel)
cursor = db.cursor()
cursor.execute("""SELECT * FROM quotes WHERE id=%s""", id)
if cursor.rowcount == 1:
(id, added_by, added_at, quote) = cursor.fetchone()
timestamp = time.strftime(conf.humanTimestampFormat,
time.localtime(int(added_at)))
2003-03-12 07:26:59 +01:00
irc.reply(msg, 'Quote %r added by %s at %s.' % \
(quote, added_by, timestamp))
2003-03-12 07:26:59 +01:00
else:
irc.error(msg, 'There isn\'t a quote with that id.')
2003-03-12 07:26:59 +01:00
def removequote(self, irc, msg, args):
2003-08-26 19:07:37 +02:00
"""[<channel>] <id>
Removes quote <id> from the quotes database for <channel>. <channel>
is only necessary if the message isn't sent in the channel itself.
"""
2003-03-12 07:26:59 +01:00
channel = privmsgs.getChannel(msg, args)
id = privmsgs.getArgs(args)
db = self.getDb(channel)
cursor = db.cursor()
capability = ircdb.makeChannelCapability(channel, 'op')
if ircdb.checkCapability(msg.prefix, capability):
cursor.execute("""DELETE FROM quotes WHERE id=%s""", id)
if cursor.rowcount == 0:
irc.error(msg, 'There was no such quote.')
else:
irc.reply(msg, conf.replySuccess)
2003-03-12 07:26:59 +01:00
else:
irc.error(msg, conf.replyNoCapability % capability)
2003-08-20 18:26:23 +02:00
2003-03-12 07:26:59 +01:00
Class = Quotes
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: