diff --git a/plugins/MessageParser/README.txt b/plugins/MessageParser/README.txt new file mode 100644 index 000000000..25159d3cf --- /dev/null +++ b/plugins/MessageParser/README.txt @@ -0,0 +1,3 @@ +The MessageParser plugin allows you to set custom regexp triggers, which will trigger the bot to respond if they match anywhere in the message. This is useful for those cases when you want a bot response even when the bot was not explicitly addressed by name or prefix character. + +An updated page of this plugin's documentation is located here: http://sourceforge.net/apps/mediawiki/gribble/index.php?title=MessageParser_Plugin diff --git a/plugins/MessageParser/__init__.py b/plugins/MessageParser/__init__.py new file mode 100644 index 000000000..c2d0efb5a --- /dev/null +++ b/plugins/MessageParser/__init__.py @@ -0,0 +1,66 @@ +### +# Copyright (c) 2010, Daniel Folkinshteyn +# 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. + +### + +""" +Add a description of the plugin (to be presented to the user inside the wizard) +here. This should describe *what* the plugin does. +""" + +import supybot +import supybot.world as world + +# Use this for the version of this plugin. You may wish to put a CVS keyword +# in here if you're keeping the plugin in CVS or some similar system. +__version__ = "" + +# XXX Replace this with an appropriate author or supybot.Author instance. +__author__ = supybot.authors.unknown + +# This is a dictionary mapping supybot.Author instances to lists of +# contributions. +__contributors__ = {} + +# This is a url where the most recent plugin package can be downloaded. +__url__ = '' # 'http://supybot.com/Members/yourname/MessageParser/download' + +import config +import plugin +reload(plugin) # In case we're being reloaded. +# Add more reloads here if you add third-party modules and want them to be +# reloaded when this plugin is reloaded. Don't forget to import them as well! + +if world.testing: + import test + +Class = plugin.Class +configure = config.configure + + +# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: diff --git a/plugins/MessageParser/config.py b/plugins/MessageParser/config.py new file mode 100644 index 000000000..f70dbdb24 --- /dev/null +++ b/plugins/MessageParser/config.py @@ -0,0 +1,71 @@ +### +# Copyright (c) 2010, Daniel Folkinshteyn +# 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 supybot.conf as conf +import supybot.registry as registry + +def configure(advanced): + # This will be called by supybot to configure this module. advanced is + # a bool that specifies whether the user identified himself as an advanced + # user or not. You should effect your configuration by manipulating the + # registry as appropriate. + from supybot.questions import expect, anything, something, yn + conf.registerPlugin('MessageParser', True) + +MessageParser = conf.registerPlugin('MessageParser') +# This is where your configuration variables (if any) should go. For example: +# conf.registerGlobalValue(MessageParser, 'someConfigVariableName', +# registry.Boolean(False, """Help for someConfigVariableName.""")) +conf.registerChannelValue(MessageParser, 'enable', + registry.Boolean(True, """Determines whether the + message parser is enabled. If enabled, will trigger on regexps + added to the regexp db.""")) +conf.registerChannelValue(MessageParser, 'keepRankInfo', + registry.Boolean(True, """Determines whether we keep updating the usage + count for each regexp, for popularity ranking.""")) +conf.registerChannelValue(MessageParser, 'rankListLength', + registry.Integer(20, """Determines the number of regexps returned + by the triggerrank command.""")) +conf.registerChannelValue(MessageParser, 'requireVacuumCapability', + registry.String('admin', """Determines the capability required (if any) to + vacuum the database.""")) +conf.registerChannelValue(MessageParser, 'requireManageCapability', + registry.String('admin; channel,op', + """Determines the + capabilities required (if any) to manage the regexp database, + including add, remove, lock, unlock. Use 'channel,capab' for + channel-level capabilities. + Note that absence of an explicit anticapability means user has + capability.""")) +conf.registerChannelValue(MessageParser, 'listSeparator', + registry.String(', ', """Determines the separator used between rexeps when + shown by the list command.""")) + +# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: diff --git a/plugins/MessageParser/local/__init__.py b/plugins/MessageParser/local/__init__.py new file mode 100644 index 000000000..e86e97b86 --- /dev/null +++ b/plugins/MessageParser/local/__init__.py @@ -0,0 +1 @@ +# Stub so local is a module, used for third-party modules diff --git a/plugins/MessageParser/plugin.py b/plugins/MessageParser/plugin.py new file mode 100644 index 000000000..62d8e9dad --- /dev/null +++ b/plugins/MessageParser/plugin.py @@ -0,0 +1,422 @@ +### +# Copyright (c) 2010, Daniel Folkinshteyn +# 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 supybot.utils as utils +from supybot.commands import * +import supybot.plugins as plugins +import supybot.ircutils as ircutils +import supybot.callbacks as callbacks + +import supybot.conf as conf +import supybot.ircdb as ircdb + +import re +import os +import time + +#try: + #import sqlite +#except ImportError: + #raise callbacks.Error, 'You need to have PySQLite installed to use this ' \ + #'plugin. Download it at ' \ + #'' + +try: + import sqlite3 +except ImportError: + from pysqlite2 import dbapi2 as sqlite3 # for python2.4 + +# these are needed cuz we are overriding getdb +import threading +import supybot.world as world + + +import supybot.log as log + + +class MessageParser(callbacks.Plugin, plugins.ChannelDBHandler): + """This plugin can set regexp triggers to activate the bot. + Use 'add' command to add regexp trigger, 'remove' to remove.""" + threaded = True + def __init__(self, irc): + callbacks.Plugin.__init__(self, irc) + plugins.ChannelDBHandler.__init__(self) + + def makeDb(self, filename): + """Create the database and connect to it.""" + if os.path.exists(filename): + db = sqlite3.connect(filename) + db.text_factory = str + return db + db = sqlite3.connect(filename) + db.text_factory = str + cursor = db.cursor() + cursor.execute("""CREATE TABLE triggers ( + id INTEGER PRIMARY KEY, + regexp TEXT UNIQUE ON CONFLICT REPLACE, + added_by TEXT, + added_at TIMESTAMP, + usage_count INTEGER, + action TEXT, + locked BOOLEAN + )""") + db.commit() + return db + + # override this because sqlite3 doesn't have autocommit + # use isolation_level instead. + def getDb(self, channel): + """Use this to get a database for a specific channel.""" + currentThread = threading.currentThread() + if channel not in self.dbCache and currentThread == world.mainThread: + self.dbCache[channel] = self.makeDb(self.makeFilename(channel)) + if currentThread != world.mainThread: + db = self.makeDb(self.makeFilename(channel)) + else: + db = self.dbCache[channel] + db.isolation_level = None + return db + + def _updateRank(self, channel, regexp): + if self.registryValue('keepRankInfo', channel): + db = self.getDb(channel) + cursor = db.cursor() + cursor.execute("""SELECT usage_count + FROM triggers + WHERE regexp=?""", (regexp,)) + old_count = cursor.fetchall()[0][0] + cursor.execute("UPDATE triggers SET usage_count=? WHERE regexp=?", (old_count + 1, regexp,)) + db.commit() + + def _runCommandFunction(self, irc, msg, command): + """Run a command from message, as if command was sent over IRC.""" + tokens = callbacks.tokenize(command) + try: + self.Proxy(irc.irc, msg, tokens) + except Exception, e: + log.exception('Uncaught exception in function called by MessageParser:') + + def _checkManageCapabilities(self, irc, msg, channel): + """Check if the user has any of the required capabilities to manage + the regexp database.""" + capabilities = self.registryValue('requireManageCapability') + if capabilities: + for capability in re.split(r'\s*;\s*', capabilities): + if capability.startswith('channel,'): + capability = ircdb.makeChannelCapability(channel, capability[8:]) + if capability and ircdb.checkCapability(msg.prefix, capability): + #print "has capability:", capability + return True + return False + else: + return True + + def doPrivmsg(self, irc, msg): + channel = msg.args[0] + if not irc.isChannel(channel): + return + if self.registryValue('enable', channel): + if callbacks.addressed(irc.nick, msg): #message is direct command + return + actions = [] + db = self.getDb(channel) + cursor = db.cursor() + cursor.execute("SELECT regexp, action FROM triggers") + results = cursor.fetchall() + if len(results) == 0: + return + for (regexp, action) in results: + for match in re.finditer(regexp, msg.args[1]): + if match is not None: + thisaction = action + self._updateRank(channel, regexp) + for (i, j) in enumerate(match.groups()): + thisaction = re.sub(r'\$' + str(i+1), match.group(i+1), thisaction) + actions.append(thisaction) + + for action in actions: + self._runCommandFunction(irc, msg, action) + + def add(self, irc, msg, args, channel, regexp, action): + """[] + + Associates with . is only + necessary if the message isn't sent on the channel + itself. Action is echoed upon regexp match, with variables $1, $2, + etc. being interpolated from the regexp match groups.""" + if not self._checkManageCapabilities(irc, msg, channel): + capabilities = self.registryValue('requireManageCapability') + irc.errorNoCapability(capabilities, Raise=True) + db = self.getDb(channel) + cursor = db.cursor() + cursor.execute("SELECT id, usage_count, locked FROM triggers WHERE regexp=?", (regexp,)) + results = cursor.fetchall() + if len(results) != 0: + (id, usage_count, locked) = map(int, results[0]) + else: + locked = 0 + usage_count = 0 + if not locked: + try: + re.compile(regexp) + except Exception, e: + irc.error('Invalid python regexp: %s' % (e,)) + return + if ircdb.users.hasUser(msg.prefix): + name = ircdb.users.getUser(msg.prefix).name + else: + name = msg.nick + cursor.execute("""INSERT INTO triggers VALUES + (NULL, ?, ?, ?, ?, ?, ?)""", + (regexp, name, int(time.time()), usage_count, action, locked,)) + db.commit() + irc.replySuccess() + else: + irc.error('That trigger is locked.') + return + add = wrap(add, ['channel', 'something', 'something']) + + def remove(self, irc, msg, args, channel, optlist, regexp): + """[] [--id] ] + + Removes the trigger for from the triggers database. + is only necessary if + the message isn't sent in the channel itself. + If option --id specified, will retrieve by regexp id, not content. + """ + if not self._checkManageCapabilities(irc, msg, channel): + capabilities = self.registryValue('requireManageCapability') + irc.errorNoCapability(capabilities, Raise=True) + db = self.getDb(channel) + cursor = db.cursor() + target = 'regexp' + for (option, arg) in optlist: + if option == 'id': + target = 'id' + sql = "SELECT id, locked FROM triggers WHERE %s=?" % (target,) + cursor.execute(sql, (regexp,)) + results = cursor.fetchall() + if len(results) != 0: + (id, locked) = map(int, results[0]) + else: + irc.error('There is no such regexp trigger.') + return + + if locked: + irc.error('This regexp trigger is locked.') + return + + cursor.execute("""DELETE FROM triggers WHERE id=?""", (id,)) + db.commit() + irc.replySuccess() + remove = wrap(remove, ['channel', + getopts({'id': '',}), + 'something']) + + def lock(self, irc, msg, args, channel, regexp): + """[] + + Locks the so that it cannot be + removed or overwritten to. is only necessary if the message isn't + sent in the channel itself. + """ + if not self._checkManageCapabilities(irc, msg, channel): + capabilities = self.registryValue('requireManageCapability') + irc.errorNoCapability(capabilities, Raise=True) + db = self.getDb(channel) + cursor = db.cursor() + cursor.execute("SELECT id FROM triggers WHERE regexp=?", (regexp,)) + results = cursor.fetchall() + if len(results) == 0: + irc.error('There is no such regexp trigger.') + return + cursor.execute("UPDATE triggers SET locked=1 WHERE regexp=?", (regexp,)) + db.commit() + irc.replySuccess() + lock = wrap(lock, ['channel', 'text']) + + def unlock(self, irc, msg, args, channel, regexp): + """[] + + Unlocks the entry associated with so that it can be + removed or overwritten. is only necessary if the message isn't + sent in the channel itself. + """ + if not self._checkManageCapabilities(irc, msg, channel): + capabilities = self.registryValue('requireManageCapability') + irc.errorNoCapability(capabilities, Raise=True) + db = self.getDb(channel) + cursor = db.cursor() + cursor.execute("SELECT id FROM triggers WHERE regexp=?", (regexp,)) + results = cursor.fetchall() + if len(results) == 0: + irc.error('There is no such regexp trigger.') + return + cursor.execute("UPDATE triggers SET locked=0 WHERE regexp=?", (regexp,)) + db.commit() + irc.replySuccess() + unlock = wrap(unlock, ['channel', 'text']) + + def show(self, irc, msg, args, channel, optlist, regexp): + """[] [--id] + + Looks up the value of in the triggers database. + is only necessary if the message isn't sent in the channel + itself. + If option --id specified, will retrieve by regexp id, not content. + """ + db = self.getDb(channel) + cursor = db.cursor() + target = 'regexp' + for (option, arg) in optlist: + if option == 'id': + target = 'id' + sql = "SELECT regexp, action FROM triggers WHERE %s=?" % (target,) + cursor.execute(sql, (regexp,)) + results = cursor.fetchall() + if len(results) != 0: + (regexp, action) = results[0] + else: + irc.error('There is no such regexp trigger.') + return + + irc.reply("The action for regexp trigger \"%s\" is \"%s\"" % (regexp, action)) + show = wrap(show, ['channel', + getopts({'id': '',}), + 'something']) + + def info(self, irc, msg, args, channel, optlist, regexp): + """[] [--id] + + Display information about in the triggers database. + is only necessary if the message isn't sent in the channel + itself. + If option --id specified, will retrieve by regexp id, not content. + """ + db = self.getDb(channel) + cursor = db.cursor() + target = 'regexp' + for (option, arg) in optlist: + if option == 'id': + target = 'id' + sql = "SELECT * FROM triggers WHERE %s=?" % (target,) + cursor.execute(sql, (regexp,)) + results = cursor.fetchall() + if len(results) != 0: + (id, regexp, added_by, added_at, usage_count, + action, locked) = results[0] + else: + irc.error('There is no such regexp trigger.') + return + + irc.reply("The regexp id is %d, regexp is \"%s\", and action is" + " \"%s\". It was added by user %s on %s, has been " + "triggered %d times, and is %s." % (id, + regexp, + action, + added_by, + time.strftime(conf.supybot.reply.format.time(), + time.localtime(int(added_at))), + usage_count, + locked and "locked" or "not locked",)) + info = wrap(info, ['channel', + getopts({'id': '',}), + 'something']) + + def list(self, irc, msg, args, channel): + """[] + + Lists regexps present in the triggers database. + is only necessary if the message isn't sent in the channel + itself. Regexp ID listed in paretheses. + """ + db = self.getDb(channel) + cursor = db.cursor() + cursor.execute("SELECT regexp, id FROM triggers") + results = cursor.fetchall() + if len(results) != 0: + regexps = results + else: + irc.reply('There are no regexp triggers in the database.') + return + + s = [ "\"%s\" (%d)" % (regexp[0], regexp[1]) for regexp in regexps ] + separator = self.registryValue('listSeparator', channel) + irc.reply(separator.join(s)) + list = wrap(list, ['channel']) + + def rank(self, irc, msg, args, channel): + """[] + + Returns a list of top-ranked regexps, sorted by usage count + (rank). The number of regexps returned is set by the + rankListLength registry value. is only necessary if the + message isn't sent in the channel itself. + """ + numregexps = self.registryValue('rankListLength', channel) + db = self.getDb(channel) + cursor = db.cursor() + cursor.execute("""SELECT regexp, usage_count + FROM triggers + ORDER BY usage_count DESC + LIMIT ?""", (numregexps,)) + regexps = cursor.fetchall() + if len(regexps) == 0: + irc.reply('There are no regexp triggers in the database.') + return + s = [ "#%d \"%s\" (%d)" % (i+1, regexp[0], regexp[1]) for i, regexp in enumerate(regexps) ] + irc.reply(", ".join(s)) + rank = wrap(rank, ['channel']) + + def vacuum(self, irc, msg, args, channel): + """[] + + Vacuums the database for . + See SQLite vacuum doc here: http://www.sqlite.org/lang_vacuum.html + is only necessary if the message isn't sent in + the channel itself. + First check if user has the required capability specified in plugin + config requireVacuumCapability. + """ + capability = self.registryValue('requireVacuumCapability') + if capability: + if not ircdb.checkCapability(msg.prefix, capability): + irc.errorNoCapability(capability, Raise=True) + db = self.getDb(channel) + cursor = db.cursor() + cursor.execute("""VACUUM""") + db.commit() + irc.replySuccess() + vacuum = wrap(vacuum, ['channel']) + +Class = MessageParser + + +# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: diff --git a/plugins/MessageParser/test.py b/plugins/MessageParser/test.py new file mode 100644 index 000000000..870f83ebd --- /dev/null +++ b/plugins/MessageParser/test.py @@ -0,0 +1,174 @@ +### +# Copyright (c) 2010, Daniel Folkinshteyn +# 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. + +### + +from supybot.test import * + +try: + import sqlite3 +except ImportError: + from pysqlite2 import dbapi2 as sqlite3 # for python2.4 + + +class MessageParserTestCase(ChannelPluginTestCase): + plugins = ('MessageParser','Utilities','User') + #utilities for the 'echo' + #user for register for testVacuum + + def testAdd(self): + self.assertError('messageparser add') #no args + self.assertError('messageparser add "stuff"') #no action arg + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.assertRegexp('messageparser show "stuff"', '.*i saw some stuff.*') + + self.assertError('messageparser add "[a" "echo stuff"') #invalid regexp + self.assertError('messageparser add "(a" "echo stuff"') #invalid regexp + self.assertNotError('messageparser add "stuff" "echo i saw no stuff"') #overwrite existing regexp + self.assertRegexp('messageparser show "stuff"', '.*i saw no stuff.*') + + + try: + world.testing = False + origuser = self.prefix + self.prefix = 'stuff!stuff@stuff' + self.assertNotError('register nottester stuff', private=True) + + self.assertError('messageparser add "aoeu" "echo vowels are nice"') + origconf = conf.supybot.plugins.MessageParser.requireManageCapability() + conf.supybot.plugins.MessageParser.requireManageCapability.setValue('') + self.assertNotError('messageparser add "aoeu" "echo vowels are nice"') + finally: + world.testing = True + self.prefix = origuser + conf.supybot.plugins.MessageParser.requireManageCapability.setValue(origconf) + + def testShow(self): + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.assertRegexp('messageparser show "nostuff"', 'there is no such regexp trigger') + self.assertRegexp('messageparser show "stuff"', '.*i saw some stuff.*') + self.assertRegexp('messageparser show --id 1', '.*i saw some stuff.*') + + def testInfo(self): + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.assertRegexp('messageparser info "nostuff"', 'there is no such regexp trigger') + self.assertRegexp('messageparser info "stuff"', '.*i saw some stuff.*') + self.assertRegexp('messageparser info --id 1', '.*i saw some stuff.*') + self.assertRegexp('messageparser info "stuff"', 'has been triggered 0 times') + self.feedMsg('this message has some stuff in it') + self.getMsg(' ') + self.assertRegexp('messageparser info "stuff"', 'has been triggered 1 times') + + def testTrigger(self): + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.feedMsg('this message has some stuff in it') + m = self.getMsg(' ') + self.failUnless(str(m).startswith('PRIVMSG #test :i saw some stuff')) + + def testLock(self): + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.assertNotError('messageparser lock "stuff"') + self.assertError('messageparser add "stuff" "echo some other stuff"') + self.assertError('messageparser remove "stuff"') + self.assertRegexp('messageparser info "stuff"', 'is locked') + + def testUnlock(self): + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.assertNotError('messageparser lock "stuff"') + self.assertError('messageparser remove "stuff"') + self.assertNotError('messageparser unlock "stuff"') + self.assertRegexp('messageparser info "stuff"', 'is not locked') + self.assertNotError('messageparser remove "stuff"') + + def testRank(self): + self.assertRegexp('messageparser rank', + 'There are no regexp triggers in the database\.') + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.assertRegexp('messageparser rank', '#1 "stuff" \(0\)') + self.assertNotError('messageparser add "aoeu" "echo vowels are nice!"') + self.assertRegexp('messageparser rank', '#1 "stuff" \(0\), #2 "aoeu" \(0\)') + self.feedMsg('instead of asdf, dvorak has aoeu') + self.getMsg(' ') + self.assertRegexp('messageparser rank', '#1 "aoeu" \(1\), #2 "stuff" \(0\)') + + def testList(self): + self.assertRegexp('messageparser list', + 'There are no regexp triggers in the database\.') + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.assertRegexp('messageparser list', '"stuff" \(1\)') + self.assertNotError('messageparser add "aoeu" "echo vowels are nice!"') + self.assertRegexp('messageparser list', '"stuff" \(1\), "aoeu" \(2\)') + + def testRemove(self): + self.assertError('messageparser remove "stuff"') + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.assertNotError('messageparser lock "stuff"') + self.assertError('messageparser remove "stuff"') + self.assertNotError('messageparser unlock "stuff"') + self.assertNotError('messageparser remove "stuff"') + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.assertNotError('messageparser remove --id 1') + + def testVacuum(self): + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.assertNotError('messageparser remove "stuff"') + self.assertNotError('messageparser vacuum') + # disable world.testing since we want new users to not + # magically be endowed with the admin capability + try: + world.testing = False + original = self.prefix + self.prefix = 'stuff!stuff@stuff' + self.assertNotError('register nottester stuff', private=True) + self.assertError('messageparser vacuum') + + orig = conf.supybot.plugins.MessageParser.requireVacuumCapability() + conf.supybot.plugins.MessageParser.requireVacuumCapability.setValue('') + self.assertNotError('messageparser vacuum') + finally: + world.testing = True + self.prefix = original + conf.supybot.plugins.MessageParser.requireVacuumCapability.setValue(orig) + + def testKeepRankInfo(self): + orig = conf.supybot.plugins.MessageParser.keepRankInfo() + + try: + conf.supybot.plugins.MessageParser.keepRankInfo.setValue(False) + self.assertNotError('messageparser add "stuff" "echo i saw some stuff"') + self.feedMsg('instead of asdf, dvorak has aoeu') + self.getMsg(' ') + self.assertRegexp('messageparser info "stuff"', 'has been triggered 0 times') + finally: + conf.supybot.plugins.MessageParser.keepRankInfo.setValue(orig) + + self.feedMsg('this message has some stuff in it') + self.getMsg(' ') + self.assertRegexp('messageparser info "stuff"', 'has been triggered 1 times') + +# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: