Updated the reply infrastructure. No more msg, it's just not necessary.

This commit is contained in:
Jeremy Fincher 2004-01-08 03:12:14 +00:00
parent 1863c8b6ad
commit 530aec2be0
59 changed files with 1010 additions and 1010 deletions

View File

@ -186,9 +186,9 @@ class Alias(callbacks.Privmsg):
name = callbacks.canonicalName(name) name = callbacks.canonicalName(name)
if hasattr(self, name) and self.isCommand(name): if hasattr(self, name) and self.isCommand(name):
self.aliases[name][1] = True self.aliases[name][1] = True
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, 'There is no such alias.') irc.error('There is no such alias.')
lock = privmsgs.checkCapability(lock, 'admin') lock = privmsgs.checkCapability(lock, 'admin')
def unlock(self, irc, msg, args): def unlock(self, irc, msg, args):
@ -200,9 +200,9 @@ class Alias(callbacks.Privmsg):
name = callbacks.canonicalName(name) name = callbacks.canonicalName(name)
if hasattr(self, name) and self.isCommand(name): if hasattr(self, name) and self.isCommand(name):
self.aliases[name][1] = False self.aliases[name][1] = False
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, 'There is no such alias.') irc.error('There is no such alias.')
unlock = privmsgs.checkCapability(unlock, 'admin') unlock = privmsgs.checkCapability(unlock, 'admin')
_invalidCharsRe = re.compile(r'[\[\]\s]') _invalidCharsRe = re.compile(r'[\[\]\s]')
@ -259,9 +259,9 @@ class Alias(callbacks.Privmsg):
self.addAlias(irc, name, alias) self.addAlias(irc, name, alias)
self.log.info('Adding alias %r for %r (from %s)' % self.log.info('Adding alias %r for %r (from %s)' %
(name, alias, msg.prefix)) (name, alias, msg.prefix))
irc.replySuccess(msg) irc.replySuccess()
except AliasError, e: except AliasError, e:
irc.error(msg, str(e)) irc.error(str(e))
def remove(self, irc, msg, args): def remove(self, irc, msg, args):
"""<name> """<name>
@ -272,9 +272,9 @@ class Alias(callbacks.Privmsg):
try: try:
self.removeAlias(name) self.removeAlias(name)
self.log.info('Removing alias %r (from %s)' % (name, msg.prefix)) self.log.info('Removing alias %r (from %s)' % (name, msg.prefix))
irc.replySuccess(msg) irc.replySuccess()
except AliasError, e: except AliasError, e:
irc.error(msg, str(e)) irc.error(str(e))
Class = Alias Class = Alias

View File

@ -112,7 +112,7 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
""" """
key = privmsgs.getArgs(args) key = privmsgs.getArgs(args)
amazon.setLicense(key) amazon.setLicense(key)
irc.replySuccess(msg) irc.replySuccess()
licensekey = privmsgs.checkCapability(licensekey, 'admin') licensekey = privmsgs.checkCapability(licensekey, 'admin')
def isbn(self, irc, msg, args): def isbn(self, irc, msg, args):
@ -143,11 +143,11 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
bold = self.configurables.get('bold', msg.args[0]) bold = self.configurables.get('bold', msg.args[0])
res = self._genResults(s, attribs, book, url, bold, 'title') res = self._genResults(s, attribs, book, url, bold, 'title')
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
return return
except amazon.AmazonError, e: except amazon.AmazonError, e:
pass pass
irc.error(msg, 'No book was found with that ISBN.') irc.error('No book was found with that ISBN.')
def books(self, irc, msg, args): def books(self, irc, msg, args):
"""[--url] <keywords> """[--url] <keywords>
@ -176,11 +176,11 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
bold = self.configurables.get('bold', msg.args[0]) bold = self.configurables.get('bold', msg.args[0])
res = self._genResults(s, attribs, books, url, bold, 'title') res = self._genResults(s, attribs, books, url, bold, 'title')
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
return return
except amazon.AmazonError, e: except amazon.AmazonError, e:
pass pass
irc.error(msg, 'No books were found with that keyword search.') irc.error('No books were found with that keyword search.')
def videos(self, irc, msg, args): def videos(self, irc, msg, args):
"""[--url] [--{dvd,vhs}] <keywords> """[--url] [--{dvd,vhs}] <keywords>
@ -215,11 +215,11 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
bold = self.configurables.get('bold', msg.args[0]) bold = self.configurables.get('bold', msg.args[0])
res = self._genResults(s, attribs, videos, url, bold, 'title') res = self._genResults(s, attribs, videos, url, bold, 'title')
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
return return
except amazon.AmazonError, e: except amazon.AmazonError, e:
pass pass
irc.error(msg, 'No videos were found with that keyword search.') irc.error('No videos were found with that keyword search.')
def asin(self, irc, msg, args): def asin(self, irc, msg, args):
"""[--url] <asin> """[--url] <asin>
@ -246,11 +246,11 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
bold = self.configurables.get('bold', msg.args[0]) bold = self.configurables.get('bold', msg.args[0])
res = self._genResults(s, attribs, item, url, bold, 'title') res = self._genResults(s, attribs, item, url, bold, 'title')
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
return return
except amazon.AmazonError, e: except amazon.AmazonError, e:
pass pass
irc.error(msg, 'No item was found with that ASIN.') irc.error('No item was found with that ASIN.')
def upc(self, irc, msg, args): def upc(self, irc, msg, args):
"""[--url] <upc> """[--url] <upc>
@ -280,11 +280,11 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
bold = self.configurables.get('bold', msg.args[0]) bold = self.configurables.get('bold', msg.args[0])
res = self._genResults(s, attribs, item, url, bold, 'title') res = self._genResults(s, attribs, item, url, bold, 'title')
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
return return
except amazon.AmazonError, e: except amazon.AmazonError, e:
pass pass
irc.error(msg, 'No item was found with that UPC.') irc.error('No item was found with that UPC.')
def author(self, irc, msg, args): def author(self, irc, msg, args):
"""[--url] <author> """[--url] <author>
@ -313,11 +313,11 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
bold = self.configurables.get('bold', msg.args[0]) bold = self.configurables.get('bold', msg.args[0])
res = self._genResults(s, attribs, books, url, bold, 'title') res = self._genResults(s, attribs, books, url, bold, 'title')
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
return return
except amazon.AmazonError, e: except amazon.AmazonError, e:
pass pass
irc.error(msg, 'No books were found by that author.') irc.error('No books were found by that author.')
# FIXME: Until I get a *good* list of categories (ones that actually work), # FIXME: Until I get a *good* list of categories (ones that actually work),
# these commands will remain unavailable # these commands will remain unavailable
@ -336,7 +336,7 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
""" """
cats = self._textToNode.keys() cats = self._textToNode.keys()
cats.sort() cats.sort()
irc.reply(msg, utils.commaAndify(cats)) irc.reply(utils.commaAndify(cats))
def bestsellers(self, irc, msg, args): def bestsellers(self, irc, msg, args):
"""[--url] <category> """[--url] <category>
@ -355,7 +355,7 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
url = True url = True
category = privmsgs.getArgs(rest).lower() category = privmsgs.getArgs(rest).lower()
if category not in self._textToNode: if category not in self._textToNode:
irc.error(msg, 'An invalid category was specified. The categories' irc.error('An invalid category was specified. The categories'
' command will return a list of valid categories') ' command will return a list of valid categories')
return return
category = self._textToNode[category] category = self._textToNode[category]
@ -370,11 +370,11 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
#self.log.warning(items) #self.log.warning(items)
res = self._genResults(s, attribs, items, url) res = self._genResults(s, attribs, items, url)
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
return return
except amazon.AmazonError, e: except amazon.AmazonError, e:
pass pass
irc.error(msg, 'No items were found on that best seller list.') irc.error('No items were found on that best seller list.')
''' '''
@ -411,11 +411,11 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
bold = self.configurables.get('bold', msg.args[0]) bold = self.configurables.get('bold', msg.args[0])
res = self._genResults(s, attribs, items, url, bold, 'title') res = self._genResults(s, attribs, items, url, bold, 'title')
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
return return
except amazon.AmazonError, e: except amazon.AmazonError, e:
pass pass
irc.error(msg, 'No items were found by that artist.') irc.error('No items were found by that artist.')
def actor(self, irc, msg, args): def actor(self, irc, msg, args):
"""[--url] [--{dvd,vhs,video}] <actor> """[--url] [--{dvd,vhs,video}] <actor>
@ -451,11 +451,11 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
bold = self.configurables.get('bold', msg.args[0]) bold = self.configurables.get('bold', msg.args[0])
res = self._genResults(s, attribs, items, url, bold, 'title') res = self._genResults(s, attribs, items, url, bold, 'title')
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
return return
except amazon.AmazonError, e: except amazon.AmazonError, e:
pass pass
irc.error(msg, 'No items were found starring that actor.') irc.error('No items were found starring that actor.')
def director(self, irc, msg, args): def director(self, irc, msg, args):
"""[--url] [--{dvd,vhs,video}] <director> """[--url] [--{dvd,vhs,video}] <director>
@ -491,11 +491,11 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
bold = self.configurables.get('bold', msg.args[0]) bold = self.configurables.get('bold', msg.args[0])
res = self._genResults(s, attribs, items, url, bold, 'title') res = self._genResults(s, attribs, items, url, bold, 'title')
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
return return
except amazon.AmazonError, e: except amazon.AmazonError, e:
pass pass
irc.error(msg, 'No items were found by that director.') irc.error('No items were found by that director.')
def manufacturer(self, irc, msg, args): def manufacturer(self, irc, msg, args):
""" [--url] \ """ [--url] \
@ -530,11 +530,11 @@ class Amazon(callbacks.Privmsg,configurable.Mixin):
bold = self.configurables.get('bold', msg.args[0]) bold = self.configurables.get('bold', msg.args[0])
res = self._genResults(s, attribs, items, url, bold, 'title') res = self._genResults(s, attribs, items, url, bold, 'title')
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
return return
except amazon.AmazonError, e: except amazon.AmazonError, e:
pass pass
irc.error(msg, 'No items were found by that manufacturer.') irc.error('No items were found by that manufacturer.')
Class = Amazon Class = Amazon

View File

@ -77,15 +77,15 @@ class Babelfish(callbacks.Privmsg):
fromLang = self._abbrevs[fromLang.lower()] fromLang = self._abbrevs[fromLang.lower()]
toLang = self._abbrevs[toLang.lower()] toLang = self._abbrevs[toLang.lower()]
translation = babelfish.translate(text, fromLang, toLang) translation = babelfish.translate(text, fromLang, toLang)
irc.reply(msg, translation) irc.reply(translation)
except (KeyError, babelfish.LanguageNotAvailableError), e: except (KeyError, babelfish.LanguageNotAvailableError), e:
irc.error(msg, '%s is not a valid language. Valid languages ' \ irc.error('%s is not a valid language. Valid languages ' \
'include %s' % \ 'include %s' % \
(e, utils.commaAndify(babelfish.available_languages))) (e, utils.commaAndify(babelfish.available_languages)))
except babelfish.BabelizerIOError, e: except babelfish.BabelizerIOError, e:
irc.error(msg, e) irc.error(e)
except babelfish.BabelfishChangedError, e: except babelfish.BabelfishChangedError, e:
irc.error(msg, 'Babelfish has foiled our plans by changing its ' \ irc.error('Babelfish has foiled our plans by changing its ' \
'webpage format') 'webpage format')
def babelize(self, irc, msg, args): def babelize(self, irc, msg, args):
@ -100,18 +100,18 @@ class Babelfish(callbacks.Privmsg):
fromLang = self._abbrevs[fromLang.lower()] fromLang = self._abbrevs[fromLang.lower()]
toLang = self._abbrevs[toLang.lower()] toLang = self._abbrevs[toLang.lower()]
if fromLang != 'english' and toLang != 'english': if fromLang != 'english' and toLang != 'english':
irc.error(msg, 'One language must be English.') irc.error('One language must be English.')
return return
translations = babelfish.babelize(text, fromLang, toLang) translations = babelfish.babelize(text, fromLang, toLang)
irc.reply(msg, translations[-1]) irc.reply(translations[-1])
except (KeyError, babelfish.LanguageNotAvailableError), e: except (KeyError, babelfish.LanguageNotAvailableError), e:
irc.reply(msg, '%s is not a valid language. Valid languages ' \ irc.reply('%s is not a valid language. Valid languages ' \
'include %s' % \ 'include %s' % \
(e, utils.commaAndify(babelfish.available_languages))) (e, utils.commaAndify(babelfish.available_languages)))
except babelfish.BabelizerIOError, e: except babelfish.BabelizerIOError, e:
irc.reply(msg, e) irc.reply(e)
except babelfish.BabelfishChangedError, e: except babelfish.BabelfishChangedError, e:
irc.reply(msg, 'Babelfish has foiled our plans by changing its ' \ irc.reply('Babelfish has foiled our plans by changing its ' \
'webpage format') 'webpage format')
def randomlanguage(self, irc, msg, args): def randomlanguage(self, irc, msg, args):
@ -124,7 +124,7 @@ class Babelfish(callbacks.Privmsg):
language = random.choice(babelfish.available_languages) language = random.choice(babelfish.available_languages)
while not allowEnglish and language == 'English': while not allowEnglish and language == 'English':
language = random.choice(babelfish.available_languages) language = random.choice(babelfish.available_languages)
irc.reply(msg, language) irc.reply(language)

View File

@ -86,7 +86,7 @@ class BadWords(privmsgs.CapabilityCheckingPrivmsg):
for word in words: for word in words:
self._badwords.add(word) self._badwords.add(word)
self.makeRegexp() self.makeRegexp()
irc.replySuccess(msg) irc.replySuccess()
def remove(self, irc, msg, args): def remove(self, irc, msg, args):
"""<word> [<word> ...] """<word> [<word> ...]
@ -97,7 +97,7 @@ class BadWords(privmsgs.CapabilityCheckingPrivmsg):
for word in words: for word in words:
self._badwords.discard(word) self._badwords.discard(word)
self.makeRegexp() self.makeRegexp()
irc.replySuccess(msg) irc.replySuccess()
Class = BadWords Class = BadWords

View File

@ -153,7 +153,7 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
url = url[:-1] url = url[:-1]
self.db[name] = [url, description] self.db[name] = [url, description]
self.shorthand = utils.abbrev(self.db.keys()) self.shorthand = utils.abbrev(self.db.keys())
irc.replySuccess(msg) irc.replySuccess()
def remove(self, irc, msg, args): def remove(self, irc, msg, args):
"""<abbreviation> """<abbreviation>
@ -166,9 +166,9 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
name = self.shorthand[name] name = self.shorthand[name]
del self.db[name] del self.db[name]
self.shorthand = utils.abbrev(self.db.keys()) self.shorthand = utils.abbrev(self.db.keys())
irc.replySuccess(msg) irc.replySuccess()
except KeyError: except KeyError:
irc.error(msg, replyNoBugzilla % name) irc.error(replyNoBugzilla % name)
def list(self, irc, msg, args): def list(self, irc, msg, args):
"""[<abbreviation>] """[<abbreviation>]
@ -181,16 +181,16 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
try: try:
name = self.shorthand[name] name = self.shorthand[name]
(url, description) = self.db[name] (url, description) = self.db[name]
irc.reply(msg, '%s: %s, %s' % (name, description, url)) irc.reply('%s: %s, %s' % (name, description, url))
except KeyError: except KeyError:
irc.error(msg, replyNoBugzilla % name) irc.error(replyNoBugzilla % name)
else: else:
if self.db: if self.db:
L = self.db.keys() L = self.db.keys()
L.sort() L.sort()
irc.reply(msg, utils.commaAndify(L)) irc.reply(utils.commaAndify(L))
else: else:
irc.reply(msg, 'I have no defined bugzillae.') irc.reply('I have no defined bugzillae.')
def bzSnarfer(self, irc, msg, match): def bzSnarfer(self, irc, msg, match):
r"(http://\S+)/show_bug.cgi\?id=([0-9]+)" r"(http://\S+)/show_bug.cgi\?id=([0-9]+)"
@ -201,11 +201,11 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
summary = self._get_short_bug_summary(queryurl, 'Snarfed '\ summary = self._get_short_bug_summary(queryurl, 'Snarfed '\
'Bugzilla URL', match.group(2)) 'Bugzilla URL', match.group(2))
except BugzillaError, e: except BugzillaError, e:
irc.reply(msg, str(e)) irc.reply(str(e))
return return
except IOError, e: except IOError, e:
msgtouser = '%s. Try yourself: %s' % (e, queryurl) msgtouser = '%s. Try yourself: %s' % (e, queryurl)
irc.reply(msg, msgtouser) irc.reply(msgtouser)
return return
report = {} report = {}
report['id'] = match.group(2) report['id'] = match.group(2)
@ -215,7 +215,7 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
report['summary'] = str(self._mk_summary_string(summary)) report['summary'] = str(self._mk_summary_string(summary))
report['product'] = str(summary['product']) report['product'] = str(summary['product'])
s = '%(product)s bug #%(id)s: %(title)s %(summary)s' % report s = '%(product)s bug #%(id)s: %(title)s %(summary)s' % report
irc.reply(msg, s, prefixName=False) irc.reply(s, prefixName=False)
bzSnarfer = privmsgs.urlSnarfer(bzSnarfer) bzSnarfer = privmsgs.urlSnarfer(bzSnarfer)
def urlquery2bugslist(self, url, query): def urlquery2bugslist(self, url, query):
@ -264,7 +264,7 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
name = self.shorthand[name] name = self.shorthand[name]
(url, description) = self.db[name] (url, description) = self.db[name]
except KeyError: except KeyError:
irc.error(msg, replyNoBugzilla % name) irc.error(replyNoBugzilla % name)
return return
bugs = self.urlquery2bugslist(url, query) bugs = self.urlquery2bugslist(url, query)
bugids = bugs.keys() bugids = bugs.keys()
@ -272,7 +272,7 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
s = '%s match %r (%s): %s.' % \ s = '%s match %r (%s): %s.' % \
(utils.nItems('bug', len(bugs)), searchstr, (utils.nItems('bug', len(bugs)), searchstr,
' AND '.join(keywords), utils.commaAndify(map(str, bugids))) ' AND '.join(keywords), utils.commaAndify(map(str, bugids)))
irc.reply(msg, s) irc.reply(s)
def bug(self, irc, msg, args): def bug(self, irc, msg, args):
"""<abbreviation> <number> """<abbreviation> <number>
@ -284,17 +284,17 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
name = self.shorthand[name] name = self.shorthand[name]
(url, description) = self.db[name] (url, description) = self.db[name]
except KeyError: except KeyError:
irc.error(msg, replyNoBugzilla % name) irc.error(replyNoBugzilla % name)
return return
queryurl = '%s/xml.cgi?id=%s' % (url, number) queryurl = '%s/xml.cgi?id=%s' % (url, number)
try: try:
summary = self._get_short_bug_summary(queryurl,description,number) summary = self._get_short_bug_summary(queryurl,description,number)
except BugzillaError, e: except BugzillaError, e:
irc.error(msg, str(e)) irc.error(str(e))
return return
except IOError, e: except IOError, e:
s = '%s. Try yourself: %s' % (e, queryurl) s = '%s. Try yourself: %s' % (e, queryurl)
irc.error(msg, s) irc.error(s)
report = {} report = {}
report['zilla'] = description report['zilla'] = description
report['id'] = number report['id'] = number
@ -302,7 +302,7 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
report['title'] = str(summary['title']) report['title'] = str(summary['title'])
report['summary'] = self._mk_summary_string(summary) report['summary'] = self._mk_summary_string(summary)
s = '%(zilla)s bug #%(id)s: %(title)s %(summary)s %(url)s' % report s = '%(zilla)s bug #%(id)s: %(title)s %(summary)s %(url)s' % report
irc.reply(msg, s) irc.reply(s)
def _mk_summary_string(self, summary): def _mk_summary_string(self, summary):
L = [] L = []

View File

@ -400,7 +400,7 @@ class ChannelDB(plugins.ChannelDBHandler,
hostmask = irc.state.nickToHostmask(name) hostmask = irc.state.nickToHostmask(name)
name = ircdb.users.getUserId(hostmask) name = ircdb.users.getUserId(hostmask)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
else: else:
table = 'nick_seen' table = 'nick_seen'
criterion = 'normalized=%s' criterion = 'normalized=%s'
@ -408,7 +408,7 @@ class ChannelDB(plugins.ChannelDBHandler,
sql = "SELECT last_seen,last_msg FROM %s WHERE %s" % (table,criterion) sql = "SELECT last_seen,last_msg FROM %s WHERE %s" % (table,criterion)
cursor.execute(sql, name) cursor.execute(sql, name)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'I have not seen %s.' % name) irc.reply('I have not seen %s.' % name)
else: else:
(seen, m) = cursor.fetchone() (seen, m) = cursor.fetchone()
seen = int(seen) seen = int(seen)
@ -416,7 +416,7 @@ class ChannelDB(plugins.ChannelDBHandler,
name = ircdb.users.getUser(int(name)).name name = ircdb.users.getUser(int(name)).name
s = '%s was last seen here %s ago saying: %s' % \ s = '%s was last seen here %s ago saying: %s' % \
(name, utils.timeElapsed(time.time() - seen), m) (name, utils.timeElapsed(time.time() - seen), m)
irc.reply(msg, s) irc.reply(s)
def stats(self, irc, msg, args): def stats(self, irc, msg, args):
"""[<channel>] [<name>] """[<channel>] [<name>]
@ -432,14 +432,14 @@ class ChannelDB(plugins.ChannelDBHandler,
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
name = ircdb.users.getUser(id).name name = ircdb.users.getUser(id).name
except KeyError: except KeyError:
irc.error(msg, 'I couldn\'t find you in my user database.') irc.error('I couldn\'t find you in my user database.')
return return
elif not ircdb.users.hasUser(name): elif not ircdb.users.hasUser(name):
try: try:
hostmask = irc.state.nickToHostmask(name) hostmask = irc.state.nickToHostmask(name)
id = ircdb.users.getUserId(hostmask) id = ircdb.users.getUserId(hostmask)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
else: else:
id = ircdb.users.getUserId(name) id = ircdb.users.getUserId(name)
@ -447,7 +447,7 @@ class ChannelDB(plugins.ChannelDBHandler,
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT * FROM user_stats WHERE user_id=%s""", id) cursor.execute("""SELECT * FROM user_stats WHERE user_id=%s""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'I have no stats for that user.') irc.error('I have no stats for that user.')
return return
values = cursor.fetchone() values = cursor.fetchone()
s = '%s has sent %s; a total of %s, %s, ' \ s = '%s has sent %s; a total of %s, %s, ' \
@ -470,7 +470,7 @@ class ChannelDB(plugins.ChannelDBHandler,
utils.nItems('time', values.kicked), utils.nItems('time', values.kicked),
utils.nItems('time', values.topics), utils.nItems('time', values.topics),
utils.nItems('time', values.modes)) utils.nItems('time', values.modes))
irc.reply(msg, s) irc.reply(s)
def channelstats(self, irc, msg, args): def channelstats(self, irc, msg, args):
"""[<channel>] """[<channel>]
@ -491,7 +491,7 @@ class ChannelDB(plugins.ChannelDBHandler,
values.words, values.smileys, values.frowns, values.actions, values.words, values.smileys, values.frowns, values.actions,
values.joins, values.parts, values.quits, values.joins, values.parts, values.quits,
values.kicks, values.modes, values.topics) values.kicks, values.modes, values.topics)
irc.reply(msg, s) irc.reply(s)
def addword(self, irc, msg, args): def addword(self, irc, msg, args):
"""[<channel>] <word> """[<channel>] <word>
@ -503,14 +503,14 @@ class ChannelDB(plugins.ChannelDBHandler,
word = privmsgs.getArgs(args) word = privmsgs.getArgs(args)
word = word.strip() word = word.strip()
if word.strip(self._nonAlphanumeric) != word: if word.strip(self._nonAlphanumeric) != word:
irc.error(msg, '<word> must not contain non-alphanumeric chars.') irc.error('<word> must not contain non-alphanumeric chars.')
return return
word = word.lower() word = word.lower()
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""INSERT INTO words VALUES (NULL, %s)""", word) cursor.execute("""INSERT INTO words VALUES (NULL, %s)""", word)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
def wordstats(self, irc, msg, args): def wordstats(self, irc, msg, args):
"""[<channel>] [<user>] [<word>] """[<channel>] [<user>] [<word>]
@ -530,11 +530,11 @@ class ChannelDB(plugins.ChannelDBHandler,
if not arg1 and not arg2: if not arg1 and not arg2:
cursor.execute("""SELECT word FROM words""") cursor.execute("""SELECT word FROM words""")
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'I am not currently keeping any word stats.') irc.reply('I am not currently keeping any word stats.')
return return
l = [repr(tup[0]) for tup in cursor.fetchall()] l = [repr(tup[0]) for tup in cursor.fetchall()]
s = 'Currently keeping stats for: %s' % utils.commaAndify(l) s = 'Currently keeping stats for: %s' % utils.commaAndify(l)
irc.reply(msg, s) irc.reply(s)
elif arg1 and arg2: elif arg1 and arg2:
user, word = (arg1, arg2) user, word = (arg1, arg2)
try: try:
@ -544,7 +544,7 @@ class ChannelDB(plugins.ChannelDBHandler,
hostmask = irc.state.nickToHostmask(user) hostmask = irc.state.nickToHostmask(user)
id = ircdb.users.getUserId(hostmask) id = ircdb.users.getUserId(hostmask)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
@ -556,13 +556,13 @@ class ChannelDB(plugins.ChannelDBHandler,
if cursor.rowcount == 0: if cursor.rowcount == 0:
cursor.execute("""SELECT id FROM words WHERE word=%s""", word) cursor.execute("""SELECT id FROM words WHERE word=%s""", word)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'I\'m not keeping stats on %r.' % word) irc.error('I\'m not keeping stats on %r.' % word)
else: else:
irc.error(msg, '%s has never said %r.' % (user, word)) irc.error('%s has never said %r.' % (user, word))
return return
count = int(cursor.fetchone()[0]) count = int(cursor.fetchone()[0])
s = '%s has said %r %s.' % (user,word,utils.nItems('time', count)) s = '%s has said %r %s.' % (user,word,utils.nItems('time', count))
irc.reply(msg, s) irc.reply(s)
else: else:
# Figure out if we got a user or a word # Figure out if we got a user or a word
cursor.execute("""SELECT word FROM words cursor.execute("""SELECT word FROM words
@ -576,7 +576,7 @@ class ChannelDB(plugins.ChannelDBHandler,
hostmask = irc.state.nickToHostmask(arg1) hostmask = irc.state.nickToHostmask(arg1)
id = ircdb.users.getUserId(hostmask) id = ircdb.users.getUserId(hostmask)
except KeyError: except KeyError:
irc.error(msg, '%r doesn\'t look like a user I know ' irc.error('%r doesn\'t look like a user I know '
'or a word that I\'m keeping stats ' 'or a word that I\'m keeping stats '
'on' % arg1) 'on' % arg1)
return return
@ -587,11 +587,11 @@ class ChannelDB(plugins.ChannelDBHandler,
ORDER BY words.word""", id) ORDER BY words.word""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
username = ircdb.users.getUser(id).name username = ircdb.users.getUser(id).name
irc.error(msg, '%r has no wordstats' % username) irc.error('%r has no wordstats' % username)
return return
L = [('%r: %s' % (word, count)) for \ L = [('%r: %s' % (word, count)) for \
(word, count) in cursor.fetchall()] (word, count) in cursor.fetchall()]
irc.reply(msg, utils.commaAndify(L)) irc.reply(utils.commaAndify(L))
return return
else: else:
# It's a word, not a user # It's a word, not a user
@ -606,7 +606,7 @@ class ChannelDB(plugins.ChannelDBHandler,
ORDER BY word_stats.count DESC""", ORDER BY word_stats.count DESC""",
word) word)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No one has said %r' % word) irc.error('No one has said %r' % word)
return return
results = cursor.fetchall() results = cursor.fetchall()
numResultsShown = min(cursor.rowcount, numUsers) numResultsShown = min(cursor.rowcount, numUsers)
@ -646,7 +646,7 @@ class ChannelDB(plugins.ChannelDBHandler,
ret = '%s %s. %s' % (ret, utils.commaAndify(L), s) ret = '%s %s. %s' % (ret, utils.commaAndify(L), s)
except KeyError: except KeyError:
ret = '%s %s.' % (ret, utils.commaAndify(L)) ret = '%s %s.' % (ret, utils.commaAndify(L))
irc.reply(msg, ret) irc.reply(ret)
Class = ChannelDB Class = ChannelDB

View File

@ -80,7 +80,7 @@ class DCC(callbacks.Privmsg):
s = 'Error trying to determine the external IP ' \ s = 'Error trying to determine the external IP ' \
'address of this machine via the host %s: %s' 'address of this machine via the host %s: %s'
self.log.warning(s, host, e) self.log.warning(s, host, e)
irc.reply(msg, conf.replyError) irc.reply(conf.replyError)
return return
i = ircutils.dccIP(ip) i = ircutils.dccIP(ip)
sock.bind((host, 0)) sock.bind((host, 0))

View File

@ -126,7 +126,7 @@ class Debian(callbacks.Privmsg,
if not optlist and not rest: if not optlist and not rest:
raise callbacks.ArgumentError raise callbacks.ArgumentError
if len(optlist) + len(rest) > 1: if len(optlist) + len(rest) > 1:
irc.error(msg, 'Only one search option is allowed.') irc.error('Only one search option is allowed.')
return return
for (option, arg) in optlist: for (option, arg) in optlist:
if option == '--exact': if option == '--exact':
@ -139,7 +139,7 @@ class Debian(callbacks.Privmsg,
try: try:
re_obj = re.compile(regexp, re.I) re_obj = re.compile(regexp, re.I)
except re.error, e: except re.error, e:
irc.error(msg, "Error in regexp: %s" % e) irc.error("Error in regexp: %s" % e)
return return
if self.configurables.get('python-zegrep', None): if self.configurables.get('python-zegrep', None):
fd = gzip.open(self.contents) fd = gzip.open(self.contents)
@ -152,7 +152,7 @@ class Debian(callbacks.Privmsg,
w.close() w.close()
except TypeError: except TypeError:
# We're on Windows. # We're on Windows.
irc.error(msg, 'This command won\'t work on this platform. ' irc.error('This command won\'t work on this platform. '
'If you think it should (i.e., you know that ' 'If you think it should (i.e., you know that '
'you have a zegrep binary somewhere) then file ' 'you have a zegrep binary somewhere) then file '
'a bug about it at http://supybot.sf.net/ .') 'a bug about it at http://supybot.sf.net/ .')
@ -161,7 +161,7 @@ class Debian(callbacks.Privmsg,
try: try:
for line in r: for line in r:
if len(packages) > 100: if len(packages) > 100:
irc.error(msg, 'More than 100 packages matched, ' irc.error('More than 100 packages matched, '
'please narrow your search.') 'please narrow your search.')
return return
try: try:
@ -176,9 +176,9 @@ class Debian(callbacks.Privmsg,
if hasattr(r, 'close'): if hasattr(r, 'close'):
r.close() r.close()
if len(packages) == 0: if len(packages) == 0:
irc.reply(msg, 'I found no packages with that file.') irc.reply('I found no packages with that file.')
else: else:
irc.reply(msg, utils.commaAndify(packages)) irc.reply(utils.commaAndify(packages))
_debreflags = re.DOTALL | re.IGNORECASE _debreflags = re.DOTALL | re.IGNORECASE
_debpkgre = re.compile(r'<a[^>]+>(.*?)</a>', _debreflags) _debpkgre = re.compile(r'<a[^>]+>(.*?)</a>', _debreflags)
@ -199,7 +199,7 @@ class Debian(callbacks.Privmsg,
else: else:
branch = 'all' branch = 'all'
if not args: if not args:
irc.error(msg, 'You must give a package name.') irc.error('You must give a package name.')
return return
responses = [] responses = []
numberOfPackages = 0 numberOfPackages = 0
@ -212,17 +212,17 @@ class Debian(callbacks.Privmsg,
html = fd.read() html = fd.read()
fd.close() fd.close()
except urllib2.HTTPError, e: except urllib2.HTTPError, e:
irc.error(msg, 'I couldn\'t reach the search page (%s).' % e) irc.error('I couldn\'t reach the search page (%s).' % e)
return return
except socket.error, e: except socket.error, e:
if e.args[0] == 110 or e.args[0] == 10060: if e.args[0] == 110 or e.args[0] == 10060:
irc.error(msg, 'Connection timed out to packages.debian.org.') irc.error('Connection timed out to packages.debian.org.')
return return
else: else:
raise raise
if 'is down at the moment' in html: if 'is down at the moment' in html:
irc.error(msg, 'Packages.debian.org is down at the moment. ' irc.error('Packages.debian.org is down at the moment. '
'Please try again later.') 'Please try again later.')
return return
m = self._debnumpkgsre.search(html) m = self._debnumpkgsre.search(html)
@ -230,7 +230,7 @@ class Debian(callbacks.Privmsg,
numberOfPackages = m.group(1) numberOfPackages = m.group(1)
m = self._debtablere.search(html) m = self._debtablere.search(html)
if m is None: if m is None:
irc.reply(msg, 'No package found for %s (%s)' % \ irc.reply('No package found for %s (%s)' % \
(urllib.unquote(package), branch)) (urllib.unquote(package), branch))
else: else:
tableData = m.group(1) tableData = m.group(1)
@ -243,7 +243,7 @@ class Debian(callbacks.Privmsg,
responses.append(s) responses.append(s)
resp = 'Total matches: %s, shown: %s. %s' % \ resp = 'Total matches: %s, shown: %s. %s' % \
(numberOfPackages, len(responses), ', '.join(responses)) (numberOfPackages, len(responses), ', '.join(responses))
irc.reply(msg, resp) irc.reply(resp)
_incomingRe = re.compile(r'<a href="(.*?\.deb)">', re.I) _incomingRe = re.compile(r'<a href="(.*?\.deb)">', re.I)
def incoming(self, irc, msg, args): def incoming(self, irc, msg, args):
@ -284,9 +284,9 @@ class Debian(callbacks.Privmsg,
realname = rsplit(name, '_', 1)[0] realname = rsplit(name, '_', 1)[0]
packages.append(realname) packages.append(realname)
if len(packages) == 0: if len(packages) == 0:
irc.error(msg, 'No packages matched that search.') irc.error('No packages matched that search.')
else: else:
irc.reply(msg, utils.commaAndify(packages)) irc.reply(utils.commaAndify(packages))
incoming = privmsgs.thread(incoming) incoming = privmsgs.thread(incoming)
Class = Debian Class = Debian

View File

@ -89,9 +89,9 @@ class Dict(callbacks.Privmsg, configurable.Mixin):
conn = dictclient.Connection(self.configurables.get('server')) conn = dictclient.Connection(self.configurables.get('server'))
dbs = conn.getdbdescs().keys() dbs = conn.getdbdescs().keys()
dbs.sort() dbs.sort()
irc.reply(msg, utils.commaAndify(dbs)) irc.reply(utils.commaAndify(dbs))
except socket.timeout: except socket.timeout:
irc.error(msg, replyTimeout) irc.error(replyTimeout)
def random(self, irc, msg, args): def random(self, irc, msg, args):
"""takes no arguments. """takes no arguments.
@ -101,9 +101,9 @@ class Dict(callbacks.Privmsg, configurable.Mixin):
try: try:
conn = dictclient.Connection(self.configurables.get('server')) conn = dictclient.Connection(self.configurables.get('server'))
dbs = conn.getdbdescs().keys() dbs = conn.getdbdescs().keys()
irc.reply(msg, random.choice(dbs)) irc.reply(random.choice(dbs))
except socket.timeout: except socket.timeout:
irc.error(msg, replyTimeout) irc.error(replyTimeout)
def dict(self, irc, msg, args): def dict(self, irc, msg, args):
"""[<dictionary>] <word> """[<dictionary>] <word>
@ -115,7 +115,7 @@ class Dict(callbacks.Privmsg, configurable.Mixin):
try: try:
conn = dictclient.Connection(self.configurables.get('server')) conn = dictclient.Connection(self.configurables.get('server'))
except socket.timeout: except socket.timeout:
irc.error(msg, 'Timeout on the dict server.') irc.error('Timeout on the dict server.')
return return
dbs = sets.Set(conn.getdbdescs()) dbs = sets.Set(conn.getdbdescs())
if args[0] in dbs: if args[0] in dbs:
@ -127,9 +127,9 @@ class Dict(callbacks.Privmsg, configurable.Mixin):
dbs = sets.Set() dbs = sets.Set()
if not definitions: if not definitions:
if dictionary == '*': if dictionary == '*':
irc.reply(msg, 'No definition for %r could be found.' % word) irc.reply('No definition for %r could be found.' % word)
else: else:
irc.reply(msg, 'No definition for %r could be found in %s' % \ irc.reply('No definition for %r could be found in %s' % \
(word, ircutils.bold(dictionary))) (word, ircutils.bold(dictionary)))
return return
L = [] L = []
@ -144,7 +144,7 @@ class Dict(callbacks.Privmsg, configurable.Mixin):
s = '%s responded: %s' % (utils.commaAndify(dbs), '; '.join(L)) s = '%s responded: %s' % (utils.commaAndify(dbs), '; '.join(L))
else: else:
s = '; '.join(L) s = '; '.join(L)
irc.reply(msg, s) irc.reply(s)
Class = Dict Class = Dict

View File

@ -91,7 +91,7 @@ class Dunno(callbacks.Privmsg):
if cursor.rowcount != 0: if cursor.rowcount != 0:
dunno = cursor.fetchone()[0] dunno = cursor.fetchone()[0]
dunno = plugins.standardSubstitute(irc, msg, dunno) dunno = plugins.standardSubstitute(irc, msg, dunno)
irc.reply(msg, dunno, prefixName=False) irc.reply(dunno, prefixName=False)
def add(self, irc, msg, args): def add(self, irc, msg, args):
"""<text> """<text>
@ -104,7 +104,7 @@ class Dunno(callbacks.Privmsg):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
text = privmsgs.getArgs(args, required=1) text = privmsgs.getArgs(args, required=1)
cursor = self.db.cursor() cursor = self.db.cursor()
@ -112,7 +112,7 @@ class Dunno(callbacks.Privmsg):
VALUES(NULL, %s, %s, %s)""", VALUES(NULL, %s, %s, %s)""",
id, int(time.time()), text) id, int(time.time()), text)
self.db.commit() self.db.commit()
irc.replySuccess(msg) irc.replySuccess()
def remove(self, irc, msg, args): def remove(self, irc, msg, args):
"""<id> """<id>
@ -123,7 +123,7 @@ class Dunno(callbacks.Privmsg):
try: try:
user_id = ircdb.users.getUserId(msg.prefix) user_id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
dunno_id = privmsgs.getArgs(args, required=1) dunno_id = privmsgs.getArgs(args, required=1)
cursor = self.db.cursor() cursor = self.db.cursor()
@ -131,17 +131,17 @@ class Dunno(callbacks.Privmsg):
FROM dunnos FROM dunnos
WHERE id = %s""" % dunno_id) WHERE id = %s""" % dunno_id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No dunno with id: %s' % dunno_id) irc.error('No dunno with id: %s' % dunno_id)
return return
(added_by, dunno) = cursor.fetchone() (added_by, dunno) = cursor.fetchone()
if not (ircdb.checkCapability(user_id, 'admin') or \ if not (ircdb.checkCapability(user_id, 'admin') or \
added_by == user_id): added_by == user_id):
irc.error(msg, 'Only admins and the dunno creator may delete a ' irc.error('Only admins and the dunno creator may delete a '
'dunno.') 'dunno.')
return return
cursor.execute("""DELETE FROM dunnos WHERE id = %s""" % dunno_id) cursor.execute("""DELETE FROM dunnos WHERE id = %s""" % dunno_id)
self.db.commit() self.db.commit()
irc.replySuccess(msg) irc.replySuccess()
def search(self, irc, msg, args): def search(self, irc, msg, args):
"""<text> """<text>
@ -155,12 +155,12 @@ class Dunno(callbacks.Privmsg):
cursor.execute("""SELECT id FROM dunnos cursor.execute("""SELECT id FROM dunnos
WHERE dunno LIKE %s""", glob) WHERE dunno LIKE %s""", glob)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No dunnos with %r found.' % text) irc.error('No dunnos with %r found.' % text)
return return
ids = [str(t[0]) for t in cursor.fetchall()] ids = [str(t[0]) for t in cursor.fetchall()]
s = 'Dunno search for %r (%s found): %s' % \ s = 'Dunno search for %r (%s found): %s' % \
(text, len(ids), utils.commaAndify(ids)) (text, len(ids), utils.commaAndify(ids))
irc.reply(msg, s) irc.reply(s)
def get(self, irc, msg, args): def get(self, irc, msg, args):
"""<id> """<id>
@ -171,15 +171,15 @@ class Dunno(callbacks.Privmsg):
try: try:
id = int(id) id = int(id)
except ValueError: except ValueError:
irc.error(msg, '%r is not a valid dunno id' % id) irc.error('%r is not a valid dunno id' % id)
return return
cursor = self.db.cursor() cursor = self.db.cursor()
cursor.execute("""SELECT dunno FROM dunnos WHERE id = %s""", id) cursor.execute("""SELECT dunno FROM dunnos WHERE id = %s""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No dunno found with id #%s' % id) irc.error('No dunno found with id #%s' % id)
return return
dunno = cursor.fetchone()[0] dunno = cursor.fetchone()[0]
irc.reply(msg, "Dunno #%s: %r" % (id, dunno)) irc.reply("Dunno #%s: %r" % (id, dunno))
Class = Dunno Class = Dunno

View File

@ -118,13 +118,13 @@ class Ebay(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
""" """
item = privmsgs.getArgs(args) item = privmsgs.getArgs(args)
if not item.isdigit(): if not item.isdigit():
irc.error(msg, '<item> must be an integer value.') irc.error('<item> must be an integer value.')
return return
url = 'http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=%s' % item url = 'http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=%s' % item
try: try:
irc.reply(msg, self._getResponse(url)) irc.reply(self._getResponse(url))
except EbayError, e: except EbayError, e:
irc.reply(msg, str(e)) irc.reply(str(e))
def ebaySnarfer(self, irc, msg, match): def ebaySnarfer(self, irc, msg, match):
r"http://cgi\.ebay\.(?:com(?:.au)?|ca|co.uk)/(?:.*?/)?(?:ws/)?" \ r"http://cgi\.ebay\.(?:com(?:.au)?|ca|co.uk)/(?:.*?/)?(?:ws/)?" \
@ -133,7 +133,7 @@ class Ebay(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
return return
url = match.group(0) url = match.group(0)
try: try:
irc.reply(msg, self._getResponse(url), prefixName=False) irc.reply(self._getResponse(url), prefixName=False)
except EbayError, e: except EbayError, e:
self.log.exception('ebaySnarfer exception at %s:', url) self.log.exception('ebaySnarfer exception at %s:', url)
ebaySnarfer = privmsgs.urlSnarfer(ebaySnarfer) ebaySnarfer = privmsgs.urlSnarfer(ebaySnarfer)

View File

@ -99,7 +99,7 @@ class Enforcer(callbacks.Privmsg, configurable.Mixin):
self.started = True self.started = True
for channel in irc.state.channels: for channel in irc.state.channels:
irc.queueMsg(ircmsgs.topic(channel)) irc.queueMsg(ircmsgs.topic(channel))
irc.replySuccess(msg) irc.replySuccess()
start = privmsgs.checkCapability(start, 'admin') start = privmsgs.checkCapability(start, 'admin')
def doJoin(self, irc, msg): def doJoin(self, irc, msg):

View File

@ -133,7 +133,7 @@ class Factoids(plugins.ChannelDBHandler,
capability = ircdb.makeChannelCapability(channel, 'factoids') capability = ircdb.makeChannelCapability(channel, 'factoids')
if not locked: if not locked:
if not ircdb.checkCapability(msg.prefix, capability): if not ircdb.checkCapability(msg.prefix, capability):
irc.error(msg, conf.replyNoCapability % capability) irc.error(conf.replyNoCapability % capability)
return return
if ircdb.users.hasUser(msg.prefix): if ircdb.users.hasUser(msg.prefix):
name = ircdb.users.getUser(msg.prefix).name name = ircdb.users.getUser(msg.prefix).name
@ -143,9 +143,9 @@ class Factoids(plugins.ChannelDBHandler,
(NULL, %s, %s, %s, %s)""", (NULL, %s, %s, %s, %s)""",
id, name, int(time.time()), factoid) id, name, int(time.time()), factoid)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, 'That factoid is locked.') irc.error('That factoid is locked.')
def whatis(self, irc, msg, args): def whatis(self, irc, msg, args):
"""[<channel>] <key> [<number>] """[<channel>] <key> [<number>]
@ -164,7 +164,7 @@ class Factoids(plugins.ChannelDBHandler,
try: try:
number = int(number) number = int(number)
except ValueError: except ValueError:
irc.error(msg, '%s is not a valid number.' % number) irc.error('%s is not a valid number.' % number)
return return
else: else:
number = 0 number = 0
@ -175,7 +175,7 @@ class Factoids(plugins.ChannelDBHandler,
ORDER BY factoids.id ORDER BY factoids.id
LIMIT 20""", key) LIMIT 20""", key)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No factoid matches that key.') irc.error('No factoid matches that key.')
else: else:
if not number: if not number:
factoids = [] factoids = []
@ -183,12 +183,12 @@ class Factoids(plugins.ChannelDBHandler,
for result in cursor.fetchall(): for result in cursor.fetchall():
factoids.append('(#%s) %s' % (counter, result[0])) factoids.append('(#%s) %s' % (counter, result[0]))
counter += 1 counter += 1
irc.reply(msg,'%r could be %s' % (key, ', or '.join(factoids))) irc.reply('%r could be %s' % (key, ', or '.join(factoids)))
else: else:
try: try:
irc.reply(msg, cursor.fetchall()[number-1][0]) irc.reply(cursor.fetchall()[number-1][0])
except IndexError: except IndexError:
irc.error(msg, 'That\'s not a valid number for this key.') irc.error('That\'s not a valid number for this key.')
return return
def lock(self, irc, msg, args): def lock(self, irc, msg, args):
@ -206,9 +206,9 @@ class Factoids(plugins.ChannelDBHandler,
cursor = db.cursor() cursor = db.cursor()
cursor.execute("UPDATE keys SET locked=1 WHERE key LIKE %s", key) cursor.execute("UPDATE keys SET locked=1 WHERE key LIKE %s", key)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, conf.replyNoCapability % capability) irc.error(conf.replyNoCapability % capability)
def unlock(self, irc, msg, args): def unlock(self, irc, msg, args):
"""[<channel>] <key> """[<channel>] <key>
@ -225,9 +225,9 @@ class Factoids(plugins.ChannelDBHandler,
cursor = db.cursor() cursor = db.cursor()
cursor.execute("UPDATE keys SET locked=0 WHERE key LIKE %s", key) cursor.execute("UPDATE keys SET locked=0 WHERE key LIKE %s", key)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, conf.replyNoCapability % capability) irc.error(conf.replyNoCapability % capability)
def forget(self, irc, msg, args): def forget(self, irc, msg, args):
"""[<channel>] <key> [<number>|*] """[<channel>] <key> [<number>|*]
@ -243,7 +243,7 @@ class Factoids(plugins.ChannelDBHandler,
number = int(args.pop()) number = int(args.pop())
number -= 1 number -= 1
if number < 0: if number < 0:
irc.error(msg, 'Negative numbers aren\'t valid.') irc.error('Negative numbers aren\'t valid.')
return return
elif args[-1] == '*': elif args[-1] == '*':
del args[-1] del args[-1]
@ -260,31 +260,31 @@ class Factoids(plugins.ChannelDBHandler,
WHERE key LIKE %s AND WHERE key LIKE %s AND
factoids.key_id=keys.id""", key) factoids.key_id=keys.id""", key)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such factoid.') irc.error('There is no such factoid.')
elif cursor.rowcount == 1 or number is True: elif cursor.rowcount == 1 or number is True:
(id, _) = cursor.fetchone() (id, _) = cursor.fetchone()
cursor.execute("""DELETE FROM factoids WHERE key_id=%s""", id) cursor.execute("""DELETE FROM factoids WHERE key_id=%s""", id)
cursor.execute("""DELETE FROM keys WHERE key LIKE %s""", key) cursor.execute("""DELETE FROM keys WHERE key LIKE %s""", key)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
else: else:
if number is not None: if number is not None:
results = cursor.fetchall() results = cursor.fetchall()
try: try:
(_, id) = results[number] (_, id) = results[number]
except IndexError: except IndexError:
irc.error(msg, 'Invalid factoid number.') irc.error('Invalid factoid number.')
return return
cursor.execute("DELETE FROM factoids WHERE id=%s", id) cursor.execute("DELETE FROM factoids WHERE id=%s", id)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, '%s factoids have that key. ' \ irc.error('%s factoids have that key. ' \
'Please specify which one to remove, ' \ 'Please specify which one to remove, ' \
'or use * to designate all of them.' % \ 'or use * to designate all of them.' % \
cursor.rowcount) cursor.rowcount)
else: else:
irc.error(msg, conf.replyNoCapability % capability) irc.error(conf.replyNoCapability % capability)
def random(self, irc, msg, args): def random(self, irc, msg, args):
"""[<channel>] """[<channel>]
@ -304,9 +304,9 @@ class Factoids(plugins.ChannelDBHandler,
cursor.execute("""SELECT key FROM keys WHERE id=%s""", id) cursor.execute("""SELECT key FROM keys WHERE id=%s""", id)
(key,) = cursor.fetchone() (key,) = cursor.fetchone()
L.append('"%s": %s' % (ircutils.bold(key), factoid)) L.append('"%s": %s' % (ircutils.bold(key), factoid))
irc.reply(msg, '; '.join(L)) irc.reply('; '.join(L))
else: else:
irc.error(msg, 'I couldn\'t find a factoid.') irc.error('I couldn\'t find a factoid.')
def info(self, irc, msg, args): def info(self, irc, msg, args):
"""[<channel>] <key> """[<channel>] <key>
@ -321,7 +321,7 @@ class Factoids(plugins.ChannelDBHandler,
cursor = db.cursor() cursor = db.cursor()
cursor.execute("SELECT id, locked FROM keys WHERE key LIKE %s", key) cursor.execute("SELECT id, locked FROM keys WHERE key LIKE %s", key)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No factoid matches that key.') irc.error('No factoid matches that key.')
return return
(id, locked) = imap(int, cursor.fetchone()) (id, locked) = imap(int, cursor.fetchone())
cursor.execute("""SELECT added_by, added_at FROM factoids cursor.execute("""SELECT added_by, added_at FROM factoids
@ -339,7 +339,7 @@ class Factoids(plugins.ChannelDBHandler,
s = 'Key %r is %s and has %s associated with it: %s' % \ s = 'Key %r is %s and has %s associated with it: %s' % \
(key, locked and 'locked' or 'not locked', (key, locked and 'locked' or 'not locked',
utils.nItems('factoid', counter), factoids) utils.nItems('factoid', counter), factoids)
irc.reply(msg, s) irc.reply(s)
def change(self, irc, msg, args): def change(self, irc, msg, args):
"""[<channel>] <key> <number> <regexp> """[<channel>] <key> <number> <regexp>
@ -352,14 +352,14 @@ class Factoids(plugins.ChannelDBHandler,
try: try:
replacer = utils.perlReToReplacer(regexp) replacer = utils.perlReToReplacer(regexp)
except ValueError, e: except ValueError, e:
irc.error(msg, 'Invalid regexp: %s' % e) irc.error('Invalid regexp: %s' % e)
return return
try: try:
number = int(number) number = int(number)
if number <= 0: if number <= 0:
raise ValueError raise ValueError
except ValueError: except ValueError:
irc.error(msg, 'Invalid key id.') irc.error('Invalid key id.')
return return
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
@ -368,16 +368,16 @@ class Factoids(plugins.ChannelDBHandler,
WHERE keys.key LIKE %s AND WHERE keys.key LIKE %s AND
keys.id=factoids.key_id""", key) keys.id=factoids.key_id""", key)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'I couldn\'t find any key %r' % key) irc.error('I couldn\'t find any key %r' % key)
return return
elif cursor.rowcount < number: elif cursor.rowcount < number:
irc.error(msg, 'That\'s not a valid key id.') irc.error('That\'s not a valid key id.')
return return
(id, fact) = cursor.fetchall()[number-1] (id, fact) = cursor.fetchall()[number-1]
newfact = replacer(fact) newfact = replacer(fact)
cursor.execute("UPDATE factoids SET fact=%s WHERE id=%s", newfact, id) cursor.execute("UPDATE factoids SET fact=%s WHERE id=%s", newfact, id)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
_sqlTrans = string.maketrans('*?', '%_') _sqlTrans = string.maketrans('*?', '%_')
def search(self, irc, msg, args): def search(self, irc, msg, args):
@ -400,7 +400,7 @@ class Factoids(plugins.ChannelDBHandler,
try: try:
r = utils.perlReToPythonRe(arg) r = utils.perlReToPythonRe(arg)
except ValueError, e: except ValueError, e:
irc.error(msg, 'Invalid regexp: %s' % e) irc.error('Invalid regexp: %s' % e)
return return
def p(s, r=r): def p(s, r=r):
return int(bool(r.search(s))) return int(bool(r.search(s)))
@ -415,17 +415,17 @@ class Factoids(plugins.ChannelDBHandler,
sql = """SELECT key FROM keys WHERE %s""" % ' AND '.join(criteria) sql = """SELECT key FROM keys WHERE %s""" % ' AND '.join(criteria)
cursor.execute(sql, formats) cursor.execute(sql, formats)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'No keys matched that query.') irc.reply('No keys matched that query.')
elif cursor.rowcount == 1 and \ elif cursor.rowcount == 1 and \
self.configurables.get('show-factoid-if-only-one-match',channel): self.configurables.get('show-factoid-if-only-one-match',channel):
self.whatis(irc, msg, [cursor.fetchone()[0]]) self.whatis(irc, msg, [cursor.fetchone()[0]])
elif cursor.rowcount > 100: elif cursor.rowcount > 100:
irc.reply(msg, 'More than 100 keys matched that query; ' irc.reply('More than 100 keys matched that query; '
'please narrow your query.') 'please narrow your query.')
else: else:
keys = [repr(t[0]) for t in cursor.fetchall()] keys = [repr(t[0]) for t in cursor.fetchall()]
s = utils.commaAndify(keys) s = utils.commaAndify(keys)
irc.reply(msg, s) irc.reply(s)
Class = Factoids Class = Factoids

View File

@ -30,7 +30,8 @@
### ###
""" """
Provides a multitude of fun, useless commands. Provides numerous filters, and a command (outfilter) to set them as filters on
the output of the bot.
""" """
__revision__ = "$Id$" __revision__ = "$Id$"
@ -49,7 +50,7 @@ import privmsgs
import callbacks import callbacks
class MyFilterProxy(object): class MyFilterProxy(object):
def reply(self, msg, s): def reply(self, s):
self.s = s self.s = s
class Filter(callbacks.Privmsg): class Filter(callbacks.Privmsg):
@ -90,12 +91,12 @@ class Filter(callbacks.Privmsg):
if command in self._filterCommands: if command in self._filterCommands:
method = getattr(self, command) method = getattr(self, command)
self.outFilters.setdefault(channel, []).append(method) self.outFilters.setdefault(channel, []).append(method)
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, 'That\'s not a valid filter command.') irc.error('That\'s not a valid filter command.')
else: else:
self.outFilters[channel] = [] self.outFilters[channel] = []
irc.replySuccess(msg) irc.replySuccess()
outfilter = privmsgs.checkChannelCapability(outfilter, 'op') outfilter = privmsgs.checkChannelCapability(outfilter, 'op')
def squish(self, irc, msg, args): def squish(self, irc, msg, args):
@ -105,7 +106,7 @@ class Filter(callbacks.Privmsg):
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
text = ''.join(text.split()) text = ''.join(text.split())
irc.reply(msg, text) irc.reply(text)
def binary(self, irc, msg, args): def binary(self, irc, msg, args):
"""<text> """<text>
@ -129,7 +130,7 @@ class Filter(callbacks.Privmsg):
counter -= 1 counter -= 1
LL.reverse() LL.reverse()
L.extend(LL) L.extend(LL)
irc.reply(msg, ''.join(L)) irc.reply(''.join(L))
def hexlify(self, irc, msg, args): def hexlify(self, irc, msg, args):
"""<text> """<text>
@ -138,7 +139,7 @@ class Filter(callbacks.Privmsg):
composed of the hexadecimal value of each character in the string composed of the hexadecimal value of each character in the string
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
irc.reply(msg, text.encode('hex_codec')) irc.reply(text.encode('hex_codec'))
def unhexlify(self, irc, msg, args): def unhexlify(self, irc, msg, args):
"""<hexstring> """<hexstring>
@ -148,9 +149,9 @@ class Filter(callbacks.Privmsg):
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
try: try:
irc.reply(msg, text.decode('hex_codec')) irc.reply(text.decode('hex_codec'))
except TypeError: except TypeError:
irc.error(msg, 'Invalid input.') irc.error('Invalid input.')
def rot13(self, irc, msg, args): def rot13(self, irc, msg, args):
"""<text> """<text>
@ -160,7 +161,7 @@ class Filter(callbacks.Privmsg):
reading by roaming eyes, since it's easily reversible. reading by roaming eyes, since it's easily reversible.
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
irc.reply(msg, text.encode('rot13')) irc.reply(text.encode('rot13'))
def lithp(self, irc, msg, args): def lithp(self, irc, msg, args):
"""<text> """<text>
@ -182,7 +183,7 @@ class Filter(callbacks.Privmsg):
text = text.replace('CCE', 'KTH') text = text.replace('CCE', 'KTH')
text = text.replace('tion', 'thion') text = text.replace('tion', 'thion')
text = text.replace('TION', 'THION') text = text.replace('TION', 'THION')
irc.reply(msg, text) irc.reply(text)
_leettrans = string.maketrans('oOaAeElBTiIts', '004433187!1+5') _leettrans = string.maketrans('oOaAeElBTiIts', '004433187!1+5')
_leetres = ((re.compile(r'\b(?:(?:[yY][o0O][oO0uU])|u)\b'), 'j00'), _leetres = ((re.compile(r'\b(?:(?:[yY][o0O][oO0uU])|u)\b'), 'j00'),
@ -200,7 +201,7 @@ class Filter(callbacks.Privmsg):
for (r, sub) in self._leetres: for (r, sub) in self._leetres:
s = re.sub(r, sub, s) s = re.sub(r, sub, s)
s = s.translate(self._leettrans) s = s.translate(self._leettrans)
irc.reply(msg, s) irc.reply(s)
_scrambleRe = re.compile(r'(?:\b|(?![a-zA-Z]))([a-zA-Z])([a-zA-Z]*)'\ _scrambleRe = re.compile(r'(?:\b|(?![a-zA-Z]))([a-zA-Z])([a-zA-Z]*)'\
r'([a-zA-Z])(?:\b|(?![a-zA-Z]))') r'([a-zA-Z])(?:\b|(?![a-zA-Z]))')
@ -216,7 +217,7 @@ class Filter(callbacks.Privmsg):
return '%s%s%s' % (m.group(1), ''.join(L), m.group(3)) return '%s%s%s' % (m.group(1), ''.join(L), m.group(3))
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
s = self._scrambleRe.sub(_subber, text) s = self._scrambleRe.sub(_subber, text)
irc.reply(msg, s) irc.reply(s)
_code = { _code = {
"A" : ".-", "A" : ".-",
@ -272,7 +273,7 @@ class Filter(callbacks.Privmsg):
text = text.replace(' ', '\x00') text = text.replace(' ', '\x00')
text = text.replace(' ', '') text = text.replace(' ', '')
text = text.replace('\x00', ' ') text = text.replace('\x00', ' ')
irc.reply(msg, text) irc.reply(text)
def morse(self, irc, msg, args): def morse(self, irc, msg, args):
"""<text> """<text>
@ -286,7 +287,7 @@ class Filter(callbacks.Privmsg):
L.append(self._code[c]) L.append(self._code[c])
else: else:
L.append(c) L.append(c)
irc.reply(msg, ' '.join(L)) irc.reply(' '.join(L))
def reverse(self, irc, msg, args): def reverse(self, irc, msg, args):
"""<text> """<text>
@ -294,7 +295,7 @@ class Filter(callbacks.Privmsg):
Reverses <text>. Reverses <text>.
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
irc.reply(msg, text[::-1]) irc.reply(text[::-1])
def _color(self, c): def _color(self, c):
if c == ' ': if c == ' ':
@ -309,7 +310,7 @@ class Filter(callbacks.Privmsg):
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
L = [self._color(c) for c in text] L = [self._color(c) for c in text]
irc.reply(msg, ''.join(L)) irc.reply(''.join(L))
def jeffk(self, irc, msg, args): def jeffk(self, irc, msg, args):
"""<text> """<text>
@ -365,7 +366,7 @@ class Filter(callbacks.Privmsg):
return text return text
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
if random.random() < .03: if random.random() < .03:
irc.reply(msg, randomlyLaugh('NO YUO', probability=1)) irc.reply(randomlyLaugh('NO YUO', probability=1))
return return
alwaysInsertions = { alwaysInsertions = {
r'er\b': 'ar', r'er\b': 'ar',
@ -403,7 +404,7 @@ class Filter(callbacks.Privmsg):
text = randomlyLaugh(text) text = randomlyLaugh(text)
if random.random() < .4: if random.random() < .4:
text = text.upper() text = text.upper()
irc.reply(msg, text) irc.reply(text)
Class = Filter Class = Filter

View File

@ -46,7 +46,7 @@ class Friendly(callbacks.PrivmsgRegexp):
r"^(?:heya?|(?:w(?:hat'?s\b|as)s?up)|howdy|hi|hello)$" r"^(?:heya?|(?:w(?:hat'?s\b|as)s?up)|howdy|hi|hello)$"
if irc.nick in msg.args[1]: if irc.nick in msg.args[1]:
s = 'howdy, %s :)' % msg.nick s = 'howdy, %s :)' % msg.nick
irc.reply(msg, s, prefixName=False) irc.reply(s, prefixName=False)
def greet2(self, irc, msg, match): def greet2(self, irc, msg, match):
r"^(?:heya?|(?:w(?:hat'?s\b|as)s*up)|howdy|hi|hello)" \ r"^(?:heya?|(?:w(?:hat'?s\b|as)s*up)|howdy|hi|hello)" \
@ -54,25 +54,25 @@ class Friendly(callbacks.PrivmsgRegexp):
r"([0-9A-Za-z_\[\]\`^{}\|-]+)[^A-Za-z_\[\]\`^{}\|-]*$" r"([0-9A-Za-z_\[\]\`^{}\|-]+)[^A-Za-z_\[\]\`^{}\|-]*$"
if ircutils.nickEqual(match.group(1), irc.nick): if ircutils.nickEqual(match.group(1), irc.nick):
s = 'howdy, %s :)' % msg.nick s = 'howdy, %s :)' % msg.nick
irc.reply(msg, s, prefixName=False) irc.reply(s, prefixName=False)
def goodbye(self, irc, msg, match): def goodbye(self, irc, msg, match):
r"(?:good)?bye|adios|vale|ciao|au revoir|seeya|night$" r"(?:good)?bye|adios|vale|ciao|au revoir|seeya|night$"
if irc.nick in msg.args[1]: if irc.nick in msg.args[1]:
s = 'seeya, %s!' % msg.nick s = 'seeya, %s!' % msg.nick
irc.reply(msg, s, prefixName=False) irc.reply(s, prefixName=False)
def exclaim(self, irc, msg, match): def exclaim(self, irc, msg, match):
r"^([^\s]+)!$" r"^([^\s]+)!$"
if match.group(1) == irc.nick: if match.group(1) == irc.nick:
s = msg.nick + '!' s = msg.nick + '!'
irc.reply(msg, s, prefixName=False) irc.reply(s, prefixName=False)
def beGracious(self, irc, msg, match): def beGracious(self, irc, msg, match):
r"\b(?:thank'?s?|thx|tnks?)\b" r"\b(?:thank'?s?|thx|tnks?)\b"
if irc.nick in msg.args[1]: if irc.nick in msg.args[1]:
s = 'you\'re welcome, %s' % msg.nick s = 'you\'re welcome, %s' % msg.nick
irc.reply(msg, s, prefixName=False) irc.reply(s, prefixName=False)
Class = Friendly Class = Friendly

View File

@ -69,7 +69,7 @@ class Fun(callbacks.Privmsg):
Checks to see if the bot is alive. Checks to see if the bot is alive.
""" """
irc.reply(msg, 'pong', prefixName=False) irc.reply('pong', prefixName=False)
def hexip(self, irc, msg, args): def hexip(self, irc, msg, args):
"""<ip> """<ip>
@ -78,14 +78,14 @@ class Fun(callbacks.Privmsg):
""" """
ip = privmsgs.getArgs(args) ip = privmsgs.getArgs(args)
if not ircutils.isIP(ip): if not ircutils.isIP(ip):
irc.error(msg, '%r is not a valid IP.' % ip) irc.error('%r is not a valid IP.' % ip)
return return
quads = ip.split('.') quads = ip.split('.')
ret = "" ret = ""
for quad in quads: for quad in quads:
i = int(quad) i = int(quad)
ret += '%02x' % i ret += '%02x' % i
irc.reply(msg, ret.upper()) irc.reply(ret.upper())
def ord(self, irc, msg, args): def ord(self, irc, msg, args):
"""<letter> """<letter>
@ -94,9 +94,9 @@ class Fun(callbacks.Privmsg):
""" """
letter = privmsgs.getArgs(args) letter = privmsgs.getArgs(args)
if len(letter) != 1: if len(letter) != 1:
irc.error(msg, 'Letter must be of length 1 (for obvious reasons)') irc.error('Letter must be of length 1 (for obvious reasons)')
else: else:
irc.reply(msg, str(ord(letter))) irc.reply(str(ord(letter)))
def chr(self, irc, msg, args): def chr(self, irc, msg, args):
"""<number> """<number>
@ -115,9 +115,9 @@ class Fun(callbacks.Privmsg):
else: else:
base = 10 base = 10
i = int(i, base) i = int(i, base)
irc.reply(msg, chr(i)) irc.reply(chr(i))
except ValueError: except ValueError:
irc.error(msg, 'That number doesn\'t map to an 8-bit character.') irc.error('That number doesn\'t map to an 8-bit character.')
def base(self, irc, msg, args): def base(self, irc, msg, args):
"""<base> <number> """<base> <number>
@ -125,7 +125,7 @@ class Fun(callbacks.Privmsg):
Converts from base <base> the number <number> Converts from base <base> the number <number>
""" """
(base, number) = privmsgs.getArgs(args, required=2) (base, number) = privmsgs.getArgs(args, required=2)
irc.reply(msg, str(long(number, int(base)))) irc.reply(str(long(number, int(base))))
def encode(self, irc, msg, args): def encode(self, irc, msg, args):
"""<encoding> <text> """<encoding> <text>
@ -136,9 +136,9 @@ class Fun(callbacks.Privmsg):
""" """
encoding, text = privmsgs.getArgs(args, required=2) encoding, text = privmsgs.getArgs(args, required=2)
try: try:
irc.reply(msg, text.encode(encoding)) irc.reply(text.encode(encoding))
except LookupError: except LookupError:
irc.error(msg, 'There is no such encoding %r' % encoding) irc.error('There is no such encoding %r' % encoding)
def decode(self, irc, msg, args): def decode(self, irc, msg, args):
"""<encoding> <text> """<encoding> <text>
@ -149,9 +149,9 @@ class Fun(callbacks.Privmsg):
""" """
encoding, text = privmsgs.getArgs(args, required=2) encoding, text = privmsgs.getArgs(args, required=2)
try: try:
irc.reply(msg, text.decode(encoding).encode('utf-8')) irc.reply(text.decode(encoding).encode('utf-8'))
except LookupError: except LookupError:
irc.error(msg, 'There is no such encoding %r' % encoding) irc.error('There is no such encoding %r' % encoding)
def xor(self, irc, msg, args): def xor(self, irc, msg, args):
"""<password> <text> """<password> <text>
@ -167,7 +167,7 @@ class Fun(callbacks.Privmsg):
for c in text: for c in text:
ret.append(chr(ord(c) ^ ord(password[i]))) ret.append(chr(ord(c) ^ ord(password[i])))
i = (i + 1) % passwordlen i = (i + 1) % passwordlen
irc.reply(msg, ''.join(ret)) irc.reply(''.join(ret))
def mimetype(self, irc, msg, args): def mimetype(self, irc, msg, args):
"""<filename> """<filename>
@ -177,10 +177,10 @@ class Fun(callbacks.Privmsg):
filename = privmsgs.getArgs(args) filename = privmsgs.getArgs(args)
(type, encoding) = mimetypes.guess_type(filename) (type, encoding) = mimetypes.guess_type(filename)
if type is not None: if type is not None:
irc.reply(msg, type) irc.reply(type)
else: else:
s = 'I couldn\'t figure out that filename.' s = 'I couldn\'t figure out that filename.'
irc.reply(msg, s) irc.reply(s)
def md5(self, irc, msg, args): def md5(self, irc, msg, args):
"""<text> """<text>
@ -190,7 +190,7 @@ class Fun(callbacks.Privmsg):
about md5. about md5.
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
irc.reply(msg, md5.md5(text).hexdigest()) irc.reply(md5.md5(text).hexdigest())
def sha(self, irc, msg, args): def sha(self, irc, msg, args):
"""<text> """<text>
@ -200,7 +200,7 @@ class Fun(callbacks.Privmsg):
about SHA. about SHA.
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
irc.reply(msg, sha.sha(text).hexdigest()) irc.reply(sha.sha(text).hexdigest())
def urlquote(self, irc, msg, args): def urlquote(self, irc, msg, args):
"""<text> """<text>
@ -208,7 +208,7 @@ class Fun(callbacks.Privmsg):
Returns the URL quoted form of the text. Returns the URL quoted form of the text.
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
irc.reply(msg, urllib.quote(text)) irc.reply(urllib.quote(text))
def urlunquote(self, irc, msg, args): def urlunquote(self, irc, msg, args):
"""<text> """<text>
@ -217,7 +217,7 @@ class Fun(callbacks.Privmsg):
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
s = urllib.unquote(text) s = urllib.unquote(text)
irc.reply(msg, s) irc.reply(s)
def coin(self, irc, msg, args): def coin(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -225,9 +225,9 @@ class Fun(callbacks.Privmsg):
Flips a coin and returns the result. Flips a coin and returns the result.
""" """
if random.randrange(0, 2): if random.randrange(0, 2):
irc.reply(msg, 'heads') irc.reply('heads')
else: else:
irc.reply(msg, 'tails') irc.reply('tails')
_dicere = re.compile(r'(\d+)d(\d+)') _dicere = re.compile(r'(\d+)d(\d+)')
def dice(self, irc, msg, args): def dice(self, irc, msg, args):
@ -242,16 +242,16 @@ class Fun(callbacks.Privmsg):
if m: if m:
(dice, sides) = imap(int, m.groups()) (dice, sides) = imap(int, m.groups())
if dice > 6: if dice > 6:
irc.error(msg, 'You can\'t roll more than 6 dice.') irc.error('You can\'t roll more than 6 dice.')
elif sides > 100: elif sides > 100:
irc.error(msg, 'Dice can\'t have more than 100 sides.') irc.error('Dice can\'t have more than 100 sides.')
else: else:
L = [0] * dice L = [0] * dice
for i in xrange(dice): for i in xrange(dice):
L[i] = random.randrange(1, sides+1) L[i] = random.randrange(1, sides+1)
irc.reply(msg, utils.commaAndify([str(x) for x in L])) irc.reply(utils.commaAndify([str(x) for x in L]))
else: else:
irc.error(msg, 'Dice must be of the form <dice>d<sides>') irc.error('Dice must be of the form <dice>d<sides>')
def objects(self, irc, msg, args): def objects(self, irc, msg, args):
"""takes no arguments. """takes no arguments.
@ -289,7 +289,7 @@ class Fun(callbacks.Privmsg):
'I have a total of %s references.' %\ 'I have a total of %s references.' %\
(len(objs), modules, classes, functions, (len(objs), modules, classes, functions,
dicts, lists, tuples, strings, refcounts) dicts, lists, tuples, strings, refcounts)
irc.reply(msg, response) irc.reply(response)
def levenshtein(self, irc, msg, args): def levenshtein(self, irc, msg, args):
"""<string1> <string2> """<string1> <string2>
@ -298,7 +298,7 @@ class Fun(callbacks.Privmsg):
between <string1> and <string2> between <string1> and <string2>
""" """
(s1, s2) = privmsgs.getArgs(args, required=2) (s1, s2) = privmsgs.getArgs(args, required=2)
irc.reply(msg, str(utils.distance(s1, s2))) irc.reply(str(utils.distance(s1, s2)))
def soundex(self, irc, msg, args): def soundex(self, irc, msg, args):
"""<string> [<length>] """<string> [<length>]
@ -312,11 +312,11 @@ class Fun(callbacks.Privmsg):
try: try:
length = int(length) length = int(length)
except ValueError: except ValueError:
irc.error(msg, '%r isn\'t a valid length.' % length) irc.error('%r isn\'t a valid length.' % length)
return return
else: else:
length = 4 length = 4
irc.reply(msg, utils.soundex(s, length)) irc.reply(utils.soundex(s, length))
_eightballs = ( _eightballs = (
'outlook not so good.', 'outlook not so good.',
@ -344,7 +344,7 @@ class Fun(callbacks.Privmsg):
Asks the magic eightball a question. Asks the magic eightball a question.
""" """
irc.reply(msg, random.choice(self._eightballs)) irc.reply(random.choice(self._eightballs))
def roulette(self, irc, msg, args): def roulette(self, irc, msg, args):
"""takes no arguments. """takes no arguments.
@ -355,11 +355,11 @@ class Fun(callbacks.Privmsg):
nick = msg.nick nick = msg.nick
channel = msg.args[0] channel = msg.args[0]
if not ircutils.isChannel(channel): if not ircutils.isChannel(channel):
irc.error(msg, 'This message must be sent in a channel.') irc.error('This message must be sent in a channel.')
if random.randint(1, 6) == 1: if random.randint(1, 6) == 1:
irc.queueMsg(ircmsgs.kick(channel, nick, 'BANG!')) irc.queueMsg(ircmsgs.kick(channel, nick, 'BANG!'))
else: else:
irc.reply(msg, '*click*') irc.reply('*click*')
Class = Fun Class = Fun

View File

@ -138,15 +138,15 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
try: try:
name = ircdb.users.getUser(msg.prefix).name name = ircdb.users.getUser(msg.prefix).name
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
if table == "lart" or table == "praise": if table == "lart" or table == "praise":
if '$who' not in s: if '$who' not in s:
irc.error(msg, 'There must be a $who in the lart/praise '\ irc.error('There must be a $who in the lart/praise '\
'somewhere.') 'somewhere.')
return return
elif table not in self._tables: elif table not in self._tables:
irc.error(msg, '"%s" is not valid. Valid values include %s.' % irc.error('"%s" is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
db = self.getDb(channel) db = self.getDb(channel)
@ -158,7 +158,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
cursor.execute(sql, s) cursor.execute(sql, s)
id = cursor.fetchone()[0] id = cursor.fetchone()[0]
response = '%s (%s #%s)' % (conf.replySuccess, table, id) response = '%s (%s #%s)' % (conf.replySuccess, table, id)
irc.reply(msg, response) irc.reply(response)
def remove(self, irc, msg, args): def remove(self, irc, msg, args):
"""[<channel>] <lart|excuse|insult|praise> <id> """[<channel>] <lart|excuse|insult|praise> <id>
@ -173,15 +173,15 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
try: try:
ircdb.users.getUser(msg.prefix).name ircdb.users.getUser(msg.prefix).name
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
try: try:
id = int(id) id = int(id)
except ValueError: except ValueError:
irc.error(msg, 'The <id> argument must be an integer.') irc.error('The <id> argument must be an integer.')
return return
if table not in self._tables: if table not in self._tables:
irc.error(msg, '"%s" is not valid. Valid values include %s.' % irc.error('"%s" is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
db = self.getDb(channel) db = self.getDb(channel)
@ -189,7 +189,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
sql = """DELETE FROM %ss WHERE id=%%s""" % table sql = """DELETE FROM %ss WHERE id=%%s""" % table
cursor.execute(sql, id) cursor.execute(sql, id)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
def change(self, irc, msg, args): def change(self, irc, msg, args):
"""[<channel>] <lart|excuse|insult|praise> <id> <regexp> """[<channel>] <lart|excuse|insult|praise> <id> <regexp>
@ -206,30 +206,30 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
try: try:
name = ircdb.users.getUser(msg.prefix).name name = ircdb.users.getUser(msg.prefix).name
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
try: try:
id = int(id) id = int(id)
except ValueError: except ValueError:
irc.error(msg, 'The <id> argument must be an integer.') irc.error('The <id> argument must be an integer.')
return return
if table not in self._tables: if table not in self._tables:
irc.error(msg, '"%s" is not valid. Valid values include %s.' % irc.error('"%s" is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
try: try:
replacer = utils.perlReToReplacer(regexp) replacer = utils.perlReToReplacer(regexp)
except ValueError, e: except ValueError, e:
irc.error(msg, 'The regexp wasn\'t valid: %s.' % e.args[0]) irc.error('The regexp wasn\'t valid: %s.' % e.args[0])
except re.error, e: except re.error, e:
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
return return
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
sql = """SELECT %s FROM %ss WHERE id=%%s""" % (table, table) sql = """SELECT %s FROM %ss WHERE id=%%s""" % (table, table)
cursor.execute(sql, id) cursor.execute(sql, id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such %s.' % table) irc.error('There is no such %s.' % table)
else: else:
old_entry = cursor.fetchone()[0] old_entry = cursor.fetchone()[0]
new_entry = replacer(old_entry) new_entry = replacer(old_entry)
@ -237,7 +237,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
(table, table) (table, table)
cursor.execute(sql, new_entry, name, id) cursor.execute(sql, new_entry, name, id)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
def num(self, irc, msg, args): def num(self, irc, msg, args):
"""[<channel>] <lart|excuse|insult|praise> """[<channel>] <lart|excuse|insult|praise>
@ -250,7 +250,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
table = privmsgs.getArgs(args) table = privmsgs.getArgs(args)
table = table.lower() table = table.lower()
if table not in self._tables: if table not in self._tables:
irc.error(msg, '%r is not valid. Valid values include %s.' % irc.error('%r is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
db = self.getDb(channel) db = self.getDb(channel)
@ -258,7 +258,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
sql = """SELECT count(*) FROM %ss""" % table sql = """SELECT count(*) FROM %ss""" % table
cursor.execute(sql) cursor.execute(sql)
total = int(cursor.fetchone()[0]) total = int(cursor.fetchone()[0])
irc.reply(msg, 'There %s currently %s in my database.' % irc.reply('There %s currently %s in my database.' %
(utils.be(total), utils.nItems(table, total))) (utils.be(total), utils.nItems(table, total)))
def get(self, irc, msg, args): def get(self, irc, msg, args):
@ -273,10 +273,10 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
try: try:
id = int(id) id = int(id)
except ValueError: except ValueError:
irc.error(msg, 'The <id> argument must be an integer.') irc.error('The <id> argument must be an integer.')
return return
if table not in self._tables: if table not in self._tables:
irc.error(msg, '"%s" is not valid. Valid values include %s.' % irc.error('"%s" is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
db = self.getDb(channel) db = self.getDb(channel)
@ -284,10 +284,10 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
sql = """SELECT %s FROM %ss WHERE id=%%s""" % (table, table) sql = """SELECT %s FROM %ss WHERE id=%%s""" % (table, table)
cursor.execute(sql, id) cursor.execute(sql, id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such %s.' % table) irc.error('There is no such %s.' % table)
else: else:
reply = cursor.fetchone()[0] reply = cursor.fetchone()[0]
irc.reply(msg, reply) irc.reply(reply)
def info(self, irc, msg, args): def info(self, irc, msg, args):
"""[<channel>] <lart|excuse|insult|praise> <id> """[<channel>] <lart|excuse|insult|praise> <id>
@ -302,10 +302,10 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
try: try:
id = int(id) id = int(id)
except ValueError: except ValueError:
irc.error(msg, 'The <id> argument must be an integer.') irc.error('The <id> argument must be an integer.')
return return
if table not in self._tables: if table not in self._tables:
irc.error(msg, '"%s" is not valid. Valid values include %s.' % irc.error('"%s" is not valid. Valid values include %s.' %
(table, utils.commaAndify(self._tables))) (table, utils.commaAndify(self._tables)))
return return
db = self.getDb(channel) db = self.getDb(channel)
@ -313,11 +313,11 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
sql = """SELECT added_by FROM %ss WHERE id=%%s""" % table sql = """SELECT added_by FROM %ss WHERE id=%%s""" % table
cursor.execute(sql, id) cursor.execute(sql, id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such %s.' % table) irc.error('There is no such %s.' % table)
else: else:
add = cursor.fetchone()[0] add = cursor.fetchone()[0]
reply = '%s #%s: Created by %s.' % (table, id, add) reply = '%s #%s: Created by %s.' % (table, id, add)
irc.reply(msg, reply) irc.reply(reply)
def _formatResponse(self, s, id, showids): def _formatResponse(self, s, id, showids):
if showids: if showids:
@ -342,14 +342,14 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
ORDER BY random() ORDER BY random()
LIMIT 1""") LIMIT 1""")
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There are currently no available insults.') irc.error('There are currently no available insults.')
else: else:
(id, insult) = cursor.fetchone() (id, insult) = cursor.fetchone()
nick = re.sub(r'\bme\b', msg.nick, nick) nick = re.sub(r'\bme\b', msg.nick, nick)
nick = re.sub(r'\bmy\b', '%s\'s' % msg.nick, nick) nick = re.sub(r'\bmy\b', '%s\'s' % msg.nick, nick)
insult = insult.replace('$who', nick) insult = insult.replace('$who', nick)
showid = self.configurables.get('show-ids', channel) showid = self.configurables.get('show-ids', channel)
irc.reply(msg, self._formatResponse(insult, id, showid), to=nick) irc.reply(self._formatResponse(insult, id, showid), to=nick)
def excuse(self, irc, msg, args): def excuse(self, irc, msg, args):
"""[<channel>] [<id>] """[<channel>] [<id>]
@ -366,12 +366,12 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
try: try:
id = int(id) id = int(id)
except ValueError: except ValueError:
irc.error(msg, 'The <id> argument must be an integer.') irc.error('The <id> argument must be an integer.')
return return
cursor.execute("""SELECT id, excuse FROM excuses WHERE id=%s""", cursor.execute("""SELECT id, excuse FROM excuses WHERE id=%s""",
id) id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such excuse.') irc.error('There is no such excuse.')
return return
else: else:
cursor.execute("""SELECT id, excuse FROM excuses cursor.execute("""SELECT id, excuse FROM excuses
@ -379,11 +379,11 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
ORDER BY random() ORDER BY random()
LIMIT 1""") LIMIT 1""")
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There are currently no available excuses.') irc.error('There are currently no available excuses.')
else: else:
(id, excuse) = cursor.fetchone() (id, excuse) = cursor.fetchone()
showid = self.configurables.get('show-ids', channel) showid = self.configurables.get('show-ids', channel)
irc.reply(msg, self._formatResponse(excuse, id, showid)) irc.reply(self._formatResponse(excuse, id, showid))
def lart(self, irc, msg, args): def lart(self, irc, msg, args):
"""[<channel>] [<id>] <text> [for <reason>] """[<channel>] [<id>] <text> [for <reason>]
@ -397,7 +397,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
try: try:
id = int(id) id = int(id)
if id < 1: if id < 1:
irc.error(msg, 'There is no such lart.') irc.error('There is no such lart.')
return return
except ValueError: except ValueError:
nick = ' '.join([id, nick]).strip() nick = ' '.join([id, nick]).strip()
@ -417,7 +417,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
if id: if id:
cursor.execute("""SELECT id, lart FROM larts WHERE id=%s""", id) cursor.execute("""SELECT id, lart FROM larts WHERE id=%s""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such lart.') irc.error('There is no such lart.')
return return
else: else:
cursor.execute("""SELECT id, lart FROM larts cursor.execute("""SELECT id, lart FROM larts
@ -425,7 +425,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
ORDER BY random() ORDER BY random()
LIMIT 1""") LIMIT 1""")
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There are currently no available larts.') irc.error('There are currently no available larts.')
else: else:
(id, lart) = cursor.fetchone() (id, lart) = cursor.fetchone()
nick = re.sub(r'\bme\b', msg.nick, nick) nick = re.sub(r'\bme\b', msg.nick, nick)
@ -438,7 +438,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
s = '%s for %s' % (s, reason) s = '%s for %s' % (s, reason)
s = s.rstrip('.') s = s.rstrip('.')
showid = self.configurables.get('show-ids', channel) showid = self.configurables.get('show-ids', channel)
irc.reply(msg, self._formatResponse(s, id, showid), action=True) irc.reply(self._formatResponse(s, id, showid), action=True)
def praise(self, irc, msg, args): def praise(self, irc, msg, args):
"""[<channel>] [<id>] <text> [for <reason>] """[<channel>] [<id>] <text> [for <reason>]
@ -453,7 +453,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
try: try:
id = int(id) id = int(id)
if id < 1: if id < 1:
irc.error(msg, 'There is no such praise.') irc.error('There is no such praise.')
return return
except ValueError: except ValueError:
nick = ' '.join([id, nick]).strip() nick = ' '.join([id, nick]).strip()
@ -471,7 +471,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
if id: if id:
cursor.execute("""SELECT id, praise FROM praises WHERE id=%s""",id) cursor.execute("""SELECT id, praise FROM praises WHERE id=%s""",id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such praise.') irc.error('There is no such praise.')
return return
else: else:
cursor.execute("""SELECT id, praise FROM praises cursor.execute("""SELECT id, praise FROM praises
@ -479,7 +479,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
ORDER BY random() ORDER BY random()
LIMIT 1""") LIMIT 1""")
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There are currently no available praises.') irc.error('There are currently no available praises.')
else: else:
(id, praise) = cursor.fetchone() (id, praise) = cursor.fetchone()
nick = re.sub(r'\bme\b', msg.nick, nick) nick = re.sub(r'\bme\b', msg.nick, nick)
@ -492,7 +492,7 @@ class FunDB(callbacks.Privmsg, configurable.Mixin, plugins.ChannelDBHandler):
s = '%s for %s' % (s, reason) s = '%s for %s' % (s, reason)
s = s.rstrip('.') s = s.rstrip('.')
showid = self.configurables.get('show-ids', channel) showid = self.configurables.get('show-ids', channel)
irc.reply(msg, self._formatResponse(s, id, showid), action=True) irc.reply(self._formatResponse(s, id, showid), action=True)
Class = FunDB Class = FunDB

View File

@ -172,7 +172,7 @@ class Gameknot(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
somewhat faster) against players from all over the world. somewhat faster) against players from all over the world.
""" """
name = privmsgs.getArgs(args) name = privmsgs.getArgs(args)
irc.reply(msg, self.getStats(name)) irc.reply(self.getStats(name))
_gkPlayer = re.compile(r"popd\('(Rating[^']+)'\).*?>([^<]+)<") _gkPlayer = re.compile(r"popd\('(Rating[^']+)'\).*?>([^<]+)<")
_gkRating = re.compile(r": (\d+)[^:]+:<br>(\d+)[^,]+, (\d+)[^,]+, (\d+)") _gkRating = re.compile(r": (\d+)[^:]+:<br>(\d+)[^,]+, (\d+)[^,]+, (\d+)")
@ -190,7 +190,7 @@ class Gameknot(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
try: try:
if 'no longer available' in s: if 'no longer available' in s:
s = 'That game is no longer available.' s = 'That game is no longer available.'
irc.reply(msg, s, prefixName=True) irc.reply(s, prefixName=True)
return return
m = self._gkGameTitle.search(s) m = self._gkGameTitle.search(s)
if m is None: if m is None:
@ -234,12 +234,12 @@ class Gameknot(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
bStats = '%s; W-%s, L-%s, D-%s' % (bRating, bWins, bLosses, bDraws) bStats = '%s; W-%s, L-%s, D-%s' % (bRating, bWins, bLosses, bDraws)
s = '%s: %s (%s) vs. %s (%s); %s' % \ s = '%s: %s (%s) vs. %s (%s); %s' % \
(gameTitle, wName, wStats, bName, bStats, toMove) (gameTitle, wName, wStats, bName, bStats, toMove)
irc.reply(msg, s, prefixName=False) irc.reply(s, prefixName=False)
except ValueError: except ValueError:
irc.error(msg,'That doesn\'t appear to be a proper Gameknot game.'\ irc.error('That doesn\'t appear to be a proper Gameknot game.'\
' (%s)' % conf.replyPossibleBug) ' (%s)' % conf.replyPossibleBug)
except Exception, e: except Exception, e:
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
gameknotSnarfer = privmsgs.urlSnarfer(gameknotSnarfer) gameknotSnarfer = privmsgs.urlSnarfer(gameknotSnarfer)
def gameknotStatsSnarfer(self, irc, msg, match): def gameknotStatsSnarfer(self, irc, msg, match):
@ -248,7 +248,7 @@ class Gameknot(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
return return
name = match.group(1) name = match.group(1)
s = self.getStats(name) s = self.getStats(name)
irc.reply(msg, s, prefixName=False) irc.reply(s, prefixName=False)
gameknotStatsSnarfer = privmsgs.urlSnarfer(gameknotStatsSnarfer) gameknotStatsSnarfer = privmsgs.urlSnarfer(gameknotStatsSnarfer)
Class = Gameknot Class = Gameknot

View File

@ -189,10 +189,10 @@ class Google(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
""" """
key = privmsgs.getArgs(args) key = privmsgs.getArgs(args)
if len(key) != 32: if len(key) != 32:
irc.error(msg, 'That doesn\'t seem to be a valid license key.') irc.error('That doesn\'t seem to be a valid license key.')
return return
google.setLicense(key) google.setLicense(key)
irc.replySuccess(msg) irc.replySuccess()
licensekey = privmsgs.checkCapability(licensekey, 'admin') licensekey = privmsgs.checkCapability(licensekey, 'admin')
def google(self, irc, msg, args): def google(self, irc, msg, args):
@ -218,7 +218,7 @@ class Google(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
data = search(self.log, searchString, **kwargs) data = search(self.log, searchString, **kwargs)
bold = self.configurables.get('bold', msg.args[0]) bold = self.configurables.get('bold', msg.args[0])
max = self.configurables.get('maximum-results', msg.args[0]) max = self.configurables.get('maximum-results', msg.args[0])
irc.reply(msg, self.formatData(data, bold=bold, max=max)) irc.reply(self.formatData(data, bold=bold, max=max))
def metagoogle(self, irc, msg, args): def metagoogle(self, irc, msg, args):
"""<search> [--(language,restrict)=<value>] [--{similar,notsafe}] """<search> [--(language,restrict)=<value>] [--{similar,notsafe}]
@ -252,7 +252,7 @@ class Google(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
meta.estimatedTotalResultsCount, meta.estimatedTotalResultsCount,
meta.searchTime, meta.searchTime,
categories and ' Categories include %s.' % categories) categories and ' Categories include %s.' % categories)
irc.reply(msg, s) irc.reply(s)
def fight(self, irc, msg, args): def fight(self, irc, msg, args):
"""<search string> <search string> [<search string> ...] """<search string> <search string> [<search string> ...]
@ -268,7 +268,7 @@ class Google(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
results.sort() results.sort()
results.reverse() results.reverse()
s = ', '.join(['%r: %s' % (s, i) for (i, s) in results]) s = ', '.join(['%r: %s' % (s, i) for (i, s) in results])
irc.reply(msg, s) irc.reply(s)
def spell(self, irc, msg, args): def spell(self, irc, msg, args):
"""<word> """<word>
@ -278,9 +278,9 @@ class Google(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
word = privmsgs.getArgs(args) word = privmsgs.getArgs(args)
result = google.doSpellingSuggestion(word) result = google.doSpellingSuggestion(word)
if result: if result:
irc.reply(msg, result) irc.reply(result)
else: else:
irc.reply(msg, 'No spelling suggestion made.') irc.reply('No spelling suggestion made.')
def info(self, irc, msg, args): def info(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -289,7 +289,7 @@ class Google(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
useful for making sure you don't go over your 1000 requests/day limit. useful for making sure you don't go over your 1000 requests/day limit.
""" """
recent = len(last24hours) recent = len(last24hours)
irc.reply(msg, 'This google module has been called %s time%stotal; '\ irc.reply('This google module has been called %s time%stotal; '\
'%s time%sin the past 24 hours. ' \ '%s time%sin the past 24 hours. ' \
'Google has spent %s seconds searching for me.' % \ 'Google has spent %s seconds searching for me.' % \
(totalSearches, totalSearches != 1 and 's ' or ' ', (totalSearches, totalSearches != 1 and 's ' or ' ',
@ -307,9 +307,9 @@ class Google(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
return return
if data.results: if data.results:
url = data.results[0].URL url = data.results[0].URL
irc.reply(msg, url) irc.reply(url)
else: else:
irc.reply(msg, 'No results for "%s"' % searchString) irc.reply('No results for "%s"' % searchString)
googleSnarfer = privmsgs.urlSnarfer(googleSnarfer) googleSnarfer = privmsgs.urlSnarfer(googleSnarfer)
_ggThread = re.compile(r'<br>Subject: ([^<]+)<br>') _ggThread = re.compile(r'<br>Subject: ([^<]+)<br>')
@ -347,10 +347,10 @@ class Google(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
mThread = self._ggThread.search(text) mThread = self._ggThread.search(text)
mGroup = self._ggGroup.search(text) mGroup = self._ggGroup.search(text)
if mThread and mGroup: if mThread and mGroup:
irc.reply(msg, 'Google Groups: %s, %s' % (mGroup.group(1), irc.reply('Google Groups: %s, %s' % (mGroup.group(1),
mThread.group(1)), prefixName = False) mThread.group(1)), prefixName = False)
else: else:
irc.error(msg, 'That doesn\'t appear to be a proper '\ irc.error('That doesn\'t appear to be a proper '\
'Google Groups page. (%s)' % conf.replyPossibleBug) 'Google Groups page. (%s)' % conf.replyPossibleBug)
googleGroups = privmsgs.urlSnarfer(googleGroups) googleGroups = privmsgs.urlSnarfer(googleGroups)

View File

@ -170,10 +170,10 @@ class Herald(callbacks.Privmsg, configurable.Mixin):
try: try:
id = self._getId(userNickHostmask) id = self._getId(userNickHostmask)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
self.db.setHerald(id, channel, herald) self.db.setHerald(id, channel, herald)
irc.replySuccess(msg) irc.replySuccess()
def remove(self, irc, msg, args): def remove(self, irc, msg, args):
"""[<channel>] <user|nick|hostmask> """[<channel>] <user|nick|hostmask>
@ -188,10 +188,10 @@ class Herald(callbacks.Privmsg, configurable.Mixin):
try: try:
id = self._getId(userNickHostmask) id = self._getId(userNickHostmask)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
self.db.delHerald(id, channel) self.db.delHerald(id, channel)
irc.replySuccess(msg) irc.replySuccess()
Class = Herald Class = Herald

View File

@ -63,7 +63,7 @@ class Http(callbacks.Privmsg):
try: try:
callbacks.Privmsg.callCommand(self, method, irc, msg, *L) callbacks.Privmsg.callCommand(self, method, irc, msg, *L)
except webutils.WebError, e: except webutils.WebError, e:
irc.error(msg, str(e)) irc.error(str(e))
def headers(self, irc, msg, args): def headers(self, irc, msg, args):
"""<url> """<url>
@ -73,11 +73,11 @@ class Http(callbacks.Privmsg):
""" """
url = privmsgs.getArgs(args) url = privmsgs.getArgs(args)
if not url.startswith('http://'): if not url.startswith('http://'):
irc.error(msg, 'Only HTTP urls are valid.') irc.error('Only HTTP urls are valid.')
return return
fd = webutils.getUrlFd(url) fd = webutils.getUrlFd(url)
s = ', '.join(['%s: %s' % (k, v) for (k, v) in fd.headers.items()]) s = ', '.join(['%s: %s' % (k, v) for (k, v) in fd.headers.items()])
irc.reply(msg, s) irc.reply(s)
_doctypeRe = re.compile(r'(<!DOCTYPE[^>]+>)', re.M) _doctypeRe = re.compile(r'(<!DOCTYPE[^>]+>)', re.M)
def doctype(self, irc, msg, args): def doctype(self, irc, msg, args):
@ -88,15 +88,15 @@ class Http(callbacks.Privmsg):
""" """
url = privmsgs.getArgs(args) url = privmsgs.getArgs(args)
if not url.startswith('http://'): if not url.startswith('http://'):
irc.error(msg, 'Only HTTP urls are valid.') irc.error('Only HTTP urls are valid.')
return return
s = webutils.getUrl(url, size=self.maxSize) s = webutils.getUrl(url, size=self.maxSize)
m = self._doctypeRe.search(s) m = self._doctypeRe.search(s)
if m: if m:
s = utils.normalizeWhitespace(m.group(0)) s = utils.normalizeWhitespace(m.group(0))
irc.reply(msg, '%s has the following doctype: %s' % (url, s)) irc.reply('%s has the following doctype: %s' % (url, s))
else: else:
irc.reply(msg, '%s has no specified doctype.' % url) irc.reply('%s has no specified doctype.' % url)
def size(self, irc, msg, args): def size(self, irc, msg, args):
"""<url> """<url>
@ -106,18 +106,18 @@ class Http(callbacks.Privmsg):
""" """
url = privmsgs.getArgs(args) url = privmsgs.getArgs(args)
if not url.startswith('http://'): if not url.startswith('http://'):
irc.error(msg, 'Only HTTP urls are valid.') irc.error('Only HTTP urls are valid.')
return return
fd = webutils.getUrlFd(url) fd = webutils.getUrlFd(url)
try: try:
size = fd.headers['Content-Length'] size = fd.headers['Content-Length']
irc.reply(msg, '%s is %s bytes long.' % (url, size)) irc.reply('%s is %s bytes long.' % (url, size))
except KeyError: except KeyError:
s = fd.read(self.maxSize) s = fd.read(self.maxSize)
if len(s) != self.maxSize: if len(s) != self.maxSize:
irc.reply(msg, '%s is %s bytes long.' % (url, len(s))) irc.reply('%s is %s bytes long.' % (url, len(s)))
else: else:
irc.reply(msg, 'The server didn\'t tell me how long %s is ' irc.reply('The server didn\'t tell me how long %s is '
'but it\'s longer than %s bytes.' % 'but it\'s longer than %s bytes.' %
(url,self.maxSize)) (url,self.maxSize))
@ -132,9 +132,9 @@ class Http(callbacks.Privmsg):
text = webutils.getUrl(url, size=self.maxSize) text = webutils.getUrl(url, size=self.maxSize)
m = self._titleRe.search(text) m = self._titleRe.search(text)
if m is not None: if m is not None:
irc.reply(msg, utils.htmlToText(m.group(1).strip())) irc.reply(utils.htmlToText(m.group(1).strip()))
else: else:
irc.reply(msg, 'That URL appears to have no HTML title ' irc.reply('That URL appears to have no HTML title '
'within the first %s bytes.' % self.maxSize) 'within the first %s bytes.' % self.maxSize)
def freshmeat(self, irc, msg, args): def freshmeat(self, irc, msg, args):
@ -159,12 +159,11 @@ class Http(callbacks.Privmsg):
vitality = getNode('vitality_percent') vitality = getNode('vitality_percent')
popularity = getNode('popularity_percent') popularity = getNode('popularity_percent')
lastupdated = getNode('date_updated') lastupdated = getNode('date_updated')
irc.reply(msg, irc.reply('%s, last updated %s, with a vitality percent of %s '
'%s, last updated %s, with a vitality percent of %s '\ 'and a popularity of %s, is in version %s.' %
'and a popularity of %s, is in version %s.' % \
(project, lastupdated, vitality, popularity, version)) (project, lastupdated, vitality, popularity, version))
except FreshmeatException, e: except FreshmeatException, e:
irc.error(msg, str(e)) irc.error(str(e))
def stockquote(self, irc, msg, args): def stockquote(self, irc, msg, args):
"""<company symbol> """<company symbol>
@ -178,13 +177,12 @@ class Http(callbacks.Privmsg):
quote = webutils.getUrl(url) quote = webutils.getUrl(url)
data = quote.split(',') data = quote.split(',')
if data[1] != '0.00': if data[1] != '0.00':
irc.reply(msg, irc.reply('The current price of %s is %s, as of %s EST. '
'The current price of %s is %s, as of %s EST. '\ 'A change of %s from the last business day.' %
'A change of %s from the last business day.' %\ (data[0][1:-1], data[1], data[3][1:-1], data[4]))
(data[0][1:-1], data[1], data[3][1:-1], data[4]))
else: else:
m = 'I couldn\'t find a listing for %s' % symbol m = 'I couldn\'t find a listing for %s' % symbol
irc.error(msg, m) irc.error(m)
_mlgeekquotere = re.compile('<p class="qt">(.*?)</p>', re.M | re.DOTALL) _mlgeekquotere = re.compile('<p class="qt">(.*?)</p>', re.M | re.DOTALL)
def geekquote(self, irc, msg, args): def geekquote(self, irc, msg, args):
@ -198,11 +196,11 @@ class Http(callbacks.Privmsg):
html = webutils.getUrl('http://bash.org/?%s' % id) html = webutils.getUrl('http://bash.org/?%s' % id)
m = self._mlgeekquotere.search(html) m = self._mlgeekquotere.search(html)
if m is None: if m is None:
irc.error(msg, 'No quote found.') irc.error('No quote found.')
return return
quote = utils.htmlToText(m.group(1)) quote = utils.htmlToText(m.group(1))
quote = ' // '.join(quote.splitlines()) quote = ' // '.join(quote.splitlines())
irc.reply(msg, quote) irc.reply(quote)
_acronymre = re.compile(r'valign="middle" width="7\d%" bgcolor="[^"]+">' _acronymre = re.compile(r'valign="middle" width="7\d%" bgcolor="[^"]+">'
r'(?:<b>)?([^<]+)') r'(?:<b>)?([^<]+)')
@ -219,7 +217,7 @@ class Http(callbacks.Privmsg):
html = webutils.getUrl(request) html = webutils.getUrl(request)
if 'daily limit' in html: if 'daily limit' in html:
s = 'Acronymfinder.com says I\'ve reached my daily limit. Sorry.' s = 'Acronymfinder.com says I\'ve reached my daily limit. Sorry.'
irc.error(msg, s) irc.error(s)
return return
# The following definitions are stripped and empties are removed. # The following definitions are stripped and empties are removed.
defs = filter(None, imap(str.strip, self._acronymre.findall(html))) defs = filter(None, imap(str.strip, self._acronymre.findall(html)))
@ -228,10 +226,10 @@ class Http(callbacks.Privmsg):
if s.startswith('[not an acronym]'): if s.startswith('[not an acronym]'):
defs[i] = s.split('is ', 1)[1] defs[i] = s.split('is ', 1)[1]
if len(defs) == 0: if len(defs) == 0:
irc.reply(msg,'No definitions found. (%s)'%conf.replyPossibleBug) irc.reply('No definitions found. (%s)' % conf.replyPossibleBug)
else: else:
s = ', or '.join(defs) s = ', or '.join(defs)
irc.reply(msg, '%s could be %s' % (acronym, s)) irc.reply('%s could be %s' % (acronym, s))
_netcraftre = re.compile(r'whatos text -->(.*?)<a href="/up/acc', re.S) _netcraftre = re.compile(r'whatos text -->(.*?)<a href="/up/acc', re.S)
def netcraft(self, irc, msg, args): def netcraft(self, irc, msg, args):
@ -247,11 +245,11 @@ class Http(callbacks.Privmsg):
if m: if m:
html = m.group(1) html = m.group(1)
s = utils.htmlToText(html, tagReplace='').strip('\xa0 ') s = utils.htmlToText(html, tagReplace='').strip('\xa0 ')
irc.reply(msg, s[9:]) # Snip off "the site" irc.reply(s[9:]) # Snip off "the site"
elif 'We could not get any results' in html: elif 'We could not get any results' in html:
irc.reply(msg, 'No results found for %s.' % hostname) irc.reply('No results found for %s.' % hostname)
else: else:
irc.error(msg, 'The format of page the was odd.') irc.error('The format of page the was odd.')
def kernel(self, irc, msg, args): def kernel(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -270,7 +268,7 @@ class Http(callbacks.Privmsg):
beta = version.strip() beta = version.strip()
finally: finally:
fd.close() fd.close()
irc.reply(msg, 'The latest stable kernel is %s; ' \ irc.reply('The latest stable kernel is %s; ' \
'the latest beta kernel is %s.' % (stable, beta)) 'the latest beta kernel is %s.' % (stable, beta))
_pgpkeyre = re.compile(r'pub\s+\d{4}\w/<a '\ _pgpkeyre = re.compile(r'pub\s+\d{4}\w/<a '\
@ -293,10 +291,10 @@ class Http(callbacks.Privmsg):
if info: if info:
L.append('%s <%s%s>' % (info.group(3),host,info.group(1))) L.append('%s <%s%s>' % (info.group(3),host,info.group(1)))
if len(L) == 0: if len(L) == 0:
irc.reply(msg, 'No results found for %s.' % search) irc.reply('No results found for %s.' % search)
else: else:
s = 'Matches found for %s: %s' % (search, ' :: '.join(L)) s = 'Matches found for %s: %s' % (search, ' :: '.join(L))
irc.reply(msg, s) irc.reply(s)
finally: finally:
fd.close() fd.close()
@ -315,7 +313,7 @@ class Http(callbacks.Privmsg):
invalid = '|<>\^=?/[]";,*' invalid = '|<>\^=?/[]";,*'
for c in invalid: for c in invalid:
if c in ext: if c in ext:
irc.error(msg, '\'%s\' is an invalid extension character' % c) irc.error('\'%s\' is an invalid extension character' % c)
return return
s = 'http://www.filext.com/detaillist.php?extdetail=%s&goButton=Go' s = 'http://www.filext.com/detaillist.php?extdetail=%s&goButton=Go'
text = webutils.getUrl(s % ext) text = webutils.getUrl(s % ext)
@ -337,9 +335,9 @@ class Http(callbacks.Privmsg):
else: else:
res.append(filetype) res.append(filetype)
if res: if res:
irc.reply(msg, utils.commaAndify(res)) irc.reply(utils.commaAndify(res))
else: else:
irc.error(msg, 'No matching file extenstions were found.') irc.error('No matching file extenstions were found.')
Class = Http Class = Http

View File

@ -130,7 +130,7 @@ class Infobot(callbacks.PrivmsgRegexp):
cursor = self.db.cursor() cursor = self.db.cursor()
cursor.execute('DELETE FROM is_factoids WHERE key=%s', key) cursor.execute('DELETE FROM is_factoids WHERE key=%s', key)
cursor.execute('DELETE FROM are_factoids WHERE key=%s', key) cursor.execute('DELETE FROM are_factoids WHERE key=%s', key)
irc.reply(msg, self.getRandomSaying('confirms')) irc.reply(self.getRandomSaying('confirms'))
def tell(self, irc, msg, match): def tell(self, irc, msg, match):
r"^tell\s+(.+?)\s+about\s+(.+?)(?!\?+)[.! ]*$" r"^tell\s+(.+?)\s+about\s+(.+?)(?!\?+)[.! ]*$"
@ -139,7 +139,7 @@ class Infobot(callbacks.PrivmsgRegexp):
s = '%s wants you to know that %s' %(msg.nick,self.getFactoid(key)) s = '%s wants you to know that %s' %(msg.nick,self.getFactoid(key))
irc.reply(nick, s) irc.reply(nick, s)
except KeyError: except KeyError:
irc.reply(msg, 'I don\'t know anything about %s' % key) irc.reply('I don\'t know anything about %s' % key)
def factoid(self, irc, msg, match): def factoid(self, irc, msg, match):
r"^(no[ :,-]+)?(.+?)\s+(was|is|am|were|are)\s+(also\s+)?(.+?)(?!\?+)$" r"^(no[ :,-]+)?(.+?)\s+(was|is|am|were|are)\s+(also\s+)?(.+?)(?!\?+)$"
@ -147,27 +147,27 @@ class Infobot(callbacks.PrivmsgRegexp):
if self.hasFactoid(key, isAre): if self.hasFactoid(key, isAre):
if not correction: if not correction:
factoid = self.getFactoid(key) factoid = self.getFactoid(key)
irc.reply(msg, 'No, %s %s %s' % (key, isAre, factoid)) irc.reply('No, %s %s %s' % (key, isAre, factoid))
elif addition: elif addition:
factoid = self.getFactoid(key) factoid = self.getFactoid(key)
newFactoid = '%s, or %s' % (factoid, value) newFactoid = '%s, or %s' % (factoid, value)
self.insertFactoid(key, isAre, newFactoid) self.insertFactoid(key, isAre, newFactoid)
irc.reply(msg, self.getRandomSaying('confirms')) irc.reply(self.getRandomSaying('confirms'))
else: else:
self.insertFactoid(key, isAre, value) self.insertFactoid(key, isAre, value)
irc.reply(msg, self.getRandomSaying('confirms')) irc.reply(self.getRandomSaying('confirms'))
return return
else: else:
self.insertFactoid(key, isAre, value) self.insertFactoid(key, isAre, value)
irc.reply(msg, self.getRandomSaying('confirms')) irc.reply(self.getRandomSaying('confirms'))
def unknown(self, irc, msg, match): def unknown(self, irc, msg, match):
r"^(.+?)\?[?.! ]*$" r"^(.+?)\?[?.! ]*$"
key = match.group(1) key = match.group(1)
try: try:
irc.reply(msg, self.getFactoid(key)) irc.reply(self.getFactoid(key))
except KeyError: except KeyError:
irc.reply(msg, self.getRandomSaying('dont_knows')) irc.reply(self.getRandomSaying('dont_knows'))
def info(self, irc, msg, match): def info(self, irc, msg, match):
r"^info$" r"^info$"
@ -177,7 +177,7 @@ class Infobot(callbacks.PrivmsgRegexp):
cursor.execute("SELECT COUNT(*) FROM are_factoids") cursor.execute("SELECT COUNT(*) FROM are_factoids")
numAre = cursor.fetchone()[0] numAre = cursor.fetchone()[0]
s = 'I have %s is factoids and %s are factoids' % (numIs, numAre) s = 'I have %s is factoids and %s are factoids' % (numIs, numAre)
irc.reply(msg, s) irc.reply(s)

View File

@ -127,7 +127,7 @@ class Karma(callbacks.PrivmsgCommandAndRegexp,
FROM karma FROM karma
WHERE normalized=%s""", normalized) WHERE normalized=%s""", normalized)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, '%s has no karma.' % name) irc.reply('%s has no karma.' % name)
else: else:
(added, subtracted) = imap(int, cursor.fetchone()) (added, subtracted) = imap(int, cursor.fetchone())
total = added - subtracted total = added - subtracted
@ -138,7 +138,7 @@ class Karma(callbacks.PrivmsgCommandAndRegexp,
'and decreased %s for a total karma of %s.' % \ 'and decreased %s for a total karma of %s.' % \
(name, utils.nItems('time', added), (name, utils.nItems('time', added),
utils.nItems('time', subtracted), total) utils.nItems('time', subtracted), total)
irc.reply(msg, s) irc.reply(s)
elif len(args) > 1: elif len(args) > 1:
normalizedArgs = sets.Set(imap(str.lower, args)) normalizedArgs = sets.Set(imap(str.lower, args))
criteria = ' OR '.join(['normalized=%s'] * len(normalizedArgs)) criteria = ' OR '.join(['normalized=%s'] * len(normalizedArgs))
@ -161,9 +161,9 @@ class Karma(callbacks.PrivmsgCommandAndRegexp,
s = '%s. %s.' % (utils.commaAndify(L), ss) s = '%s. %s.' % (utils.commaAndify(L), ss)
else: else:
s = utils.commaAndify(L) + '.' s = utils.commaAndify(L) + '.'
irc.reply(msg, s) irc.reply(s)
else: else:
irc.reply(msg, 'I didn\'t know the karma for any ' irc.reply('I didn\'t know the karma for any '
'of those things.') 'of those things.')
else: # No name was given. Return the top/bottom N karmas. else: # No name was given. Return the top/bottom N karmas.
limit = self.configurables.get('karma-ranking-display', channel) limit = self.configurables.get('karma-ranking-display', channel)
@ -178,11 +178,11 @@ class Karma(callbacks.PrivmsgCommandAndRegexp,
LIMIT %s""", limit) LIMIT %s""", limit)
lowest=['%r (%s)' % (t[0], int(t[1])) for t in cursor.fetchall()] lowest=['%r (%s)' % (t[0], int(t[1])) for t in cursor.fetchall()]
if not (highest and lowest): if not (highest and lowest):
irc.error(msg, 'I have no karma for this channel.') irc.error('I have no karma for this channel.')
else: else:
s = 'Highest karma: %s. Lowest karma: %s.' % \ s = 'Highest karma: %s. Lowest karma: %s.' % \
(utils.commaAndify(highest), utils.commaAndify(lowest)) (utils.commaAndify(highest), utils.commaAndify(lowest))
irc.reply(msg, s) irc.reply(s)
_mostAbbrev = utils.abbrev(['increased', 'decreased', 'active']) _mostAbbrev = utils.abbrev(['increased', 'decreased', 'active'])
def most(self, irc, msg, args): def most(self, irc, msg, args):
@ -204,7 +204,7 @@ class Karma(callbacks.PrivmsgCommandAndRegexp,
orderby = 'added+subtracted' orderby = 'added+subtracted'
else: else:
self.log.error('Impossible condition in most: kind=%s' % kind) self.log.error('Impossible condition in most: kind=%s' % kind)
irc.error(msg, conf.replyPossibleBug) irc.error(conf.replyPossibleBug)
return return
sql = "SELECT name, %s FROM karma ORDER BY %s DESC LIMIT %s" % \ sql = "SELECT name, %s FROM karma ORDER BY %s DESC LIMIT %s" % \
(orderby, orderby, (orderby, orderby,
@ -214,9 +214,9 @@ class Karma(callbacks.PrivmsgCommandAndRegexp,
cursor.execute(sql) cursor.execute(sql)
L = ['%s: %s' % (name, int(i)) for (name, i) in cursor.fetchall()] L = ['%s: %s' % (name, int(i)) for (name, i) in cursor.fetchall()]
if L: if L:
irc.reply(msg, utils.commaAndify(L)) irc.reply(utils.commaAndify(L))
else: else:
irc.error(msg, 'I have no karma for this channel.') irc.error('I have no karma for this channel.')
except KeyError: except KeyError:
raise callbacks.ArgumentError raise callbacks.ArgumentError
@ -232,7 +232,7 @@ class Karma(callbacks.PrivmsgCommandAndRegexp,
SET added=added+1 SET added=added+1
WHERE normalized=%s""", normalized) WHERE normalized=%s""", normalized)
if self.configurables.get('karma-response', msg.args[0]): if self.configurables.get('karma-response', msg.args[0]):
irc.replySuccess(msg) irc.replySuccess()
def decreaseKarma(self, irc, msg, match): def decreaseKarma(self, irc, msg, match):
r"^(\S+)--(|\s+)$" r"^(\S+)--(|\s+)$"
@ -246,7 +246,7 @@ class Karma(callbacks.PrivmsgCommandAndRegexp,
SET subtracted=subtracted+1 SET subtracted=subtracted+1
WHERE normalized=%s""", normalized) WHERE normalized=%s""", normalized)
if self.configurables.get('karma-response', msg.args[0]): if self.configurables.get('karma-response', msg.args[0]):
irc.replySuccess(msg) irc.replySuccess()
Class = Karma Class = Karma

View File

@ -114,7 +114,7 @@ class Lookup(callbacks.Privmsg):
name = privmsgs.getArgs(args) name = privmsgs.getArgs(args)
name = callbacks.canonicalName(name) name = callbacks.canonicalName(name)
if name not in self.lookupDomains: if name not in self.lookupDomains:
irc.error(msg, 'That\'s not a valid lookup to remove.') irc.error('That\'s not a valid lookup to remove.')
return return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
@ -122,9 +122,9 @@ class Lookup(callbacks.Privmsg):
cursor.execute("""DROP TABLE %s""" % name) cursor.execute("""DROP TABLE %s""" % name)
db.commit() db.commit()
delattr(self.__class__, name) delattr(self.__class__, name)
irc.replySuccess(msg) irc.replySuccess()
except sqlite.DatabaseError: except sqlite.DatabaseError:
irc.error(msg, 'No such lookup exists.') irc.error('No such lookup exists.')
remove = privmsgs.checkCapability(remove, 'admin') remove = privmsgs.checkCapability(remove, 'admin')
_splitRe = re.compile(r'(?<!\\):') _splitRe = re.compile(r'(?<!\\):')
@ -141,21 +141,21 @@ class Lookup(callbacks.Privmsg):
name = callbacks.canonicalName(name) name = callbacks.canonicalName(name)
if hasattr(self, name): if hasattr(self, name):
s = 'I already have a command in this plugin named %s' % name s = 'I already have a command in this plugin named %s' % name
irc.error(msg, s) irc.error(s)
return return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
try: try:
cursor.execute("""SELECT * FROM %s LIMIT 1""" % name) cursor.execute("""SELECT * FROM %s LIMIT 1""" % name)
self.addCommand(name) self.addCommand(name)
irc.replySuccess(msg) irc.replySuccess()
except sqlite.DatabaseError: except sqlite.DatabaseError:
# Good, there's no such database. # Good, there's no such database.
try: try:
filename = os.path.join(conf.dataDir, filename) filename = os.path.join(conf.dataDir, filename)
fd = file(filename) fd = file(filename)
except EnvironmentError, e: except EnvironmentError, e:
irc.error(msg, 'Could not open %s: %s' % (filename, e.args[1])) irc.error('Could not open %s: %s' % (filename, e.args[1]))
return return
try: try:
cursor.execute("""SELECT COUNT(*) FROM %s""" % name) cursor.execute("""SELECT COUNT(*) FROM %s""" % name)
@ -172,13 +172,13 @@ class Lookup(callbacks.Privmsg):
except ValueError: except ValueError:
cursor.execute("""DROP TABLE %s""" % name) cursor.execute("""DROP TABLE %s""" % name)
s = 'Invalid line in %s: %r' % (filename, line) s = 'Invalid line in %s: %r' % (filename, line)
irc.error(msg, s) irc.error(s)
return return
cursor.execute(sql, key, value) cursor.execute(sql, key, value)
cursor.execute("CREATE INDEX %s_keys ON %s (key)" %(name,name)) cursor.execute("CREATE INDEX %s_keys ON %s (key)" %(name,name))
db.commit() db.commit()
self.addCommand(name) self.addCommand(name)
irc.reply(msg, '%s (lookup %s added)' % (conf.replySuccess, name)) irc.reply('%s (lookup %s added)' % (conf.replySuccess, name))
add = privmsgs.checkCapability(add, 'admin') add = privmsgs.checkCapability(add, 'admin')
def addCommand(self, name): def addCommand(self, name):
@ -228,7 +228,7 @@ class Lookup(callbacks.Privmsg):
try: try:
r = utils.perlReToPythonRe(arg) r = utils.perlReToPythonRe(arg)
except ValueError, e: except ValueError, e:
irc.error(msg, '%r is not a valid regular expression' % irc.error('%r is not a valid regular expression' %
arg) arg)
return return
def p(s, r=r): def p(s, r=r):
@ -250,11 +250,11 @@ class Lookup(callbacks.Privmsg):
#print 'sql: %s' % sql #print 'sql: %s' % sql
cursor.execute(sql, formats) cursor.execute(sql, formats)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'No %s matched that query.' % utils.pluralize(name)) irc.reply('No %s matched that query.' % utils.pluralize(name))
else: else:
lookups = ['%s: %s' % (item[0], self._shrink(item[1])) lookups = ['%s: %s' % (item[0], self._shrink(item[1]))
for item in cursor.fetchall()] for item in cursor.fetchall()]
irc.reply(msg, utils.commaAndify(lookups)) irc.reply(utils.commaAndify(lookups))
def _lookup(self, irc, msg, args): def _lookup(self, irc, msg, args):
"""<name> <key> """<name> <key>
@ -270,17 +270,17 @@ class Lookup(callbacks.Privmsg):
cursor.execute(sql, key) cursor.execute(sql, key)
except sqlite.DatabaseError, e: except sqlite.DatabaseError, e:
if 'no such table' in str(e): if 'no such table' in str(e):
irc.error(msg, 'I don\'t have a domain %s' % name) irc.error('I don\'t have a domain %s' % name)
else: else:
irc.error(msg, str(e)) irc.error(str(e))
return return
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'I couldn\'t find %s in %s' % (key, name)) irc.error('I couldn\'t find %s in %s' % (key, name))
elif cursor.rowcount == 1: elif cursor.rowcount == 1:
irc.reply(msg, cursor.fetchone()[0]) irc.reply(cursor.fetchone()[0])
else: else:
values = [t[0] for t in cursor.fetchall()] values = [t[0] for t in cursor.fetchall()]
irc.reply(msg, '%s could be %s' % (key, ', or '.join(values))) irc.reply('%s could be %s' % (key, ', or '.join(values)))
else: else:
sql = """SELECT key, value FROM %s sql = """SELECT key, value FROM %s
ORDER BY random() LIMIT 1""" % name ORDER BY random() LIMIT 1""" % name
@ -288,12 +288,12 @@ class Lookup(callbacks.Privmsg):
cursor.execute(sql) cursor.execute(sql)
except sqlite.DatabaseError, e: except sqlite.DatabaseError, e:
if 'no such table' in str(e): if 'no such table' in str(e):
irc.error(msg, 'I don\'t have a domain %r' % name) irc.error('I don\'t have a domain %r' % name)
else: else:
irc.error(msg, str(e)) irc.error(str(e))
return return
(key, value) = cursor.fetchone() (key, value) = cursor.fetchone()
irc.reply(msg, '%s: %s' % (key, value)) irc.reply('%s: %s' % (key, value))
Class = Lookup Class = Lookup

View File

@ -140,7 +140,7 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
ORDER BY random() ORDER BY random()
LIMIT 1""") LIMIT 1""")
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'I have no records for that channel.') irc.error('I have no records for that channel.')
return return
(id, first, second) = cursor.fetchone() (id, first, second) = cursor.fetchone()
id = int(id) id = int(id)
@ -164,7 +164,7 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
if len(words) < self._minMarkovLength: if len(words) < self._minMarkovLength:
self.markov(irc, msg, args) self.markov(irc, msg, args)
else: else:
irc.reply(msg, ' '.join(words)) irc.reply(' '.join(words))
def pairs(self, irc, msg, args): def pairs(self, irc, msg, args):
"""[<channel>] """[<channel>]
@ -178,7 +178,7 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
cursor.execute("""SELECT COUNT(*) FROM pairs""") cursor.execute("""SELECT COUNT(*) FROM pairs""")
n = int(cursor.fetchone()[0]) n = int(cursor.fetchone()[0])
s = 'There are %s pairs in my Markov database for %s' % (n, channel) s = 'There are %s pairs in my Markov database for %s' % (n, channel)
irc.reply(msg, s) irc.reply(s)
def firsts(self, irc, msg, args): def firsts(self, irc, msg, args):
"""[<channel>] """[<channel>]
@ -192,7 +192,7 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
cursor.execute("""SELECT COUNT(*) FROM pairs WHERE is_first=1""") cursor.execute("""SELECT COUNT(*) FROM pairs WHERE is_first=1""")
n = int(cursor.fetchone()[0]) n = int(cursor.fetchone()[0])
s = 'There are %s first pairs in my Markov database for %s'%(n,channel) s = 'There are %s first pairs in my Markov database for %s'%(n,channel)
irc.reply(msg, s) irc.reply(s)
def follows(self, irc, msg, args): def follows(self, irc, msg, args):
"""[<channel>] """[<channel>]
@ -206,7 +206,7 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
cursor.execute("""SELECT COUNT(*) FROM follows""") cursor.execute("""SELECT COUNT(*) FROM follows""")
n = int(cursor.fetchone()[0]) n = int(cursor.fetchone()[0])
s = 'There are %s follows in my Markov database for %s' % (n, channel) s = 'There are %s follows in my Markov database for %s' % (n, channel)
irc.reply(msg, s) irc.reply(s)
def lasts(self, irc, msg, args): def lasts(self, irc, msg, args):
"""[<channel>] """[<channel>]
@ -220,7 +220,7 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
cursor.execute("""SELECT COUNT(*) FROM follows WHERE word ISNULL""") cursor.execute("""SELECT COUNT(*) FROM follows WHERE word ISNULL""")
n = int(cursor.fetchone()[0]) n = int(cursor.fetchone()[0])
s = 'There are %s lasts in my Markov database for %s' % (n, channel) s = 'There are %s lasts in my Markov database for %s' % (n, channel)
irc.reply(msg, s) irc.reply(s)
Class = Markov Class = Markov

View File

@ -118,7 +118,7 @@ class Math(callbacks.Privmsg):
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
if text != text.translate(string.ascii, '_[]'): if text != text.translate(string.ascii, '_[]'):
irc.error(msg, 'There\'s really no reason why you should have ' irc.error('There\'s really no reason why you should have '
'underscores or brackets in your mathematical ' 'underscores or brackets in your mathematical '
'expression. Please remove them.') 'expression. Please remove them.')
return return
@ -126,7 +126,7 @@ class Math(callbacks.Privmsg):
# safety's sake. # safety's sake.
text = text.translate(string.ascii, '_[] \t') text = text.translate(string.ascii, '_[] \t')
if 'lambda' in text: if 'lambda' in text:
irc.error(msg, 'You can\'t use lambda in this command.') irc.error('You can\'t use lambda in this command.')
return return
text = text.replace('lambda', '') # Let's leave it in for safety. text = text.replace('lambda', '') # Let's leave it in for safety.
def handleMatch(m): def handleMatch(m):
@ -148,16 +148,16 @@ class Math(callbacks.Privmsg):
try: try:
self.log.info('evaluating %r from %s' % (text, msg.prefix)) self.log.info('evaluating %r from %s' % (text, msg.prefix))
x = complex(eval(text, self._mathEnv, self._mathEnv)) x = complex(eval(text, self._mathEnv, self._mathEnv))
irc.reply(msg, self._complexToString(x)) irc.reply(self._complexToString(x))
except OverflowError: except OverflowError:
maxFloat = math.ldexp(0.9999999999999999, 1024) maxFloat = math.ldexp(0.9999999999999999, 1024)
irc.error(msg, 'The answer exceeded %s or so.' % maxFloat) irc.error('The answer exceeded %s or so.' % maxFloat)
except TypeError: except TypeError:
irc.error(msg, 'Something in there wasn\'t a valid number.') irc.error('Something in there wasn\'t a valid number.')
except NameError, e: except NameError, e:
irc.error(msg, '%s is not a defined function.' % str(e).split()[1]) irc.error('%s is not a defined function.' % str(e).split()[1])
except Exception, e: except Exception, e:
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
def icalc(self, irc, msg, args): def icalc(self, irc, msg, args):
"""<math expression> """<math expression>
@ -168,7 +168,7 @@ class Math(callbacks.Privmsg):
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
if text != text.translate(string.ascii, '_[]'): if text != text.translate(string.ascii, '_[]'):
irc.error(msg, 'There\'s really no reason why you should have ' irc.error('There\'s really no reason why you should have '
'underscores or brackets in your mathematical ' 'underscores or brackets in your mathematical '
'expression. Please remove them.') 'expression. Please remove them.')
return return
@ -176,21 +176,21 @@ class Math(callbacks.Privmsg):
# safety's sake. # safety's sake.
text = text.translate(string.ascii, '_[] \t') text = text.translate(string.ascii, '_[] \t')
if 'lambda' in text: if 'lambda' in text:
irc.error(msg, 'You can\'t use lambda in this command.') irc.error('You can\'t use lambda in this command.')
return return
text = text.replace('lambda', '') text = text.replace('lambda', '')
try: try:
self.log.info('evaluating %r from %s' % (text, msg.prefix)) self.log.info('evaluating %r from %s' % (text, msg.prefix))
irc.reply(msg, str(eval(text, self._mathEnv, self._mathEnv))) irc.reply(str(eval(text, self._mathEnv, self._mathEnv)))
except OverflowError: except OverflowError:
maxFloat = math.ldexp(0.9999999999999999, 1024) maxFloat = math.ldexp(0.9999999999999999, 1024)
irc.error(msg, 'The answer exceeded %s or so.' % maxFloat) irc.error('The answer exceeded %s or so.' % maxFloat)
except TypeError: except TypeError:
irc.error(msg, 'Something in there wasn\'t a valid number.') irc.error('Something in there wasn\'t a valid number.')
except NameError, e: except NameError, e:
irc.error(msg, '%s is not a defined function.' % str(e).split()[1]) irc.error('%s is not a defined function.' % str(e).split()[1])
except Exception, e: except Exception, e:
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
icalc = privmsgs.checkCapability(icalc, 'trusted') icalc = privmsgs.checkCapability(icalc, 'trusted')
_rpnEnv = { _rpnEnv = {
@ -223,7 +223,7 @@ class Math(callbacks.Privmsg):
except TypeError: except TypeError:
pass pass
if not called: if not called:
irc.error(msg, 'Not enough arguments for %s' % arg) irc.error('Not enough arguments for %s' % arg)
return return
else: else:
stack.append(f) stack.append(f)
@ -236,13 +236,13 @@ class Math(callbacks.Privmsg):
try: try:
stack.append(eval(s, self._mathEnv, self._mathEnv)) stack.append(eval(s, self._mathEnv, self._mathEnv))
except SyntaxError: except SyntaxError:
irc.error(msg, '%r is not a defined function.' % arg) irc.error('%r is not a defined function.' % arg)
return return
if len(stack) == 1: if len(stack) == 1:
irc.reply(msg, str(self._complexToString(complex(stack[0])))) irc.reply(str(self._complexToString(complex(stack[0]))))
else: else:
s = ', '.join(imap(self._complexToString, imap(complex, stack))) s = ', '.join(imap(self._complexToString, imap(complex, stack)))
irc.reply(msg, 'Stack: [%s]' % s) irc.reply('Stack: [%s]' % s)
_convertEnv = {'__builtins__': types.ModuleType('__builtins__')} _convertEnv = {'__builtins__': types.ModuleType('__builtins__')}
for (k, v) in unum.units.__dict__.iteritems(): for (k, v) in unum.units.__dict__.iteritems():
@ -265,26 +265,26 @@ class Math(callbacks.Privmsg):
try: try:
n = float(n) n = float(n)
except ValueError: except ValueError:
irc.error(msg, '%s is not a valid number.' % n) irc.error('%s is not a valid number.' % n)
return return
try: try:
unit1 = unit1.lower() unit1 = unit1.lower()
self.log.info('evaluating %r from %s' % (unit1, msg.prefix)) self.log.info('evaluating %r from %s' % (unit1, msg.prefix))
u1 = eval(unit1, self._convertEnv, self._convertEnv) u1 = eval(unit1, self._convertEnv, self._convertEnv)
except: except:
irc.error(msg, '%s is not a valid units expression.' % unit1) irc.error('%s is not a valid units expression.' % unit1)
return return
try: try:
unit2 = unit2.lower() unit2 = unit2.lower()
self.log.info('evaluating %r from %s' % (unit2, msg.prefix)) self.log.info('evaluating %r from %s' % (unit2, msg.prefix))
u2 = eval(unit2, self._convertEnv, self._convertEnv) u2 = eval(unit2, self._convertEnv, self._convertEnv)
except: except:
irc.error(msg, '%s is not a valid units expression.' % unit2) irc.error('%s is not a valid units expression.' % unit2)
return return
try: try:
irc.reply(msg, str((n*u1).as(u2))) irc.reply(str((n*u1).as(u2)))
except Exception, e: except Exception, e:
irc.error(msg, str(e)) irc.error(str(e))
def units(self, irc, msg, args): def units(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -294,7 +294,7 @@ class Math(callbacks.Privmsg):
L = self._convertEnv.keys() L = self._convertEnv.keys()
L.remove('__builtins__') L.remove('__builtins__')
L.sort() L.sort()
irc.reply(msg, utils.commaAndify(L)) irc.reply(utils.commaAndify(L))
Class = Math Class = Math

View File

@ -197,10 +197,10 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
cursor.execute("""SELECT fact, key FROM factoids cursor.execute("""SELECT fact, key FROM factoids
ORDER BY random() LIMIT 1""") ORDER BY random() LIMIT 1""")
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No factoids in the database.') irc.error('No factoids in the database.')
return return
(fact, key) = cursor.fetchone() (fact, key) = cursor.fetchone()
irc.reply(msg, "%r is %r" % (key, fact)) irc.reply("%r is %r" % (key, fact))
def invalidCommand(self, irc, msg, tokens): def invalidCommand(self, irc, msg, tokens):
key = ' '.join(tokens) key = ' '.join(tokens)
@ -221,13 +221,13 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
# Now actually get the factoid and respond accordingly # Now actually get the factoid and respond accordingly
(type, text) = self._parseFactoid(irc, msg, fact) (type, text) = self._parseFactoid(irc, msg, fact)
if type == "action": if type == "action":
irc.reply(msg, text, action=True) irc.reply(text, action=True)
elif type == "reply": elif type == "reply":
irc.reply(msg, text, prefixName=False) irc.reply(text, prefixName=False)
elif type == "define": elif type == "define":
irc.reply(msg, "%s is %s" % (key, text), prefixName=False) irc.reply("%s is %s" % (key, text), prefixName=False)
else: else:
irc.error(msg, "Spurious type from _parseFactoid.") irc.error("Spurious type from _parseFactoid.")
return True return True
def addFactoid(self, irc, msg, match): def addFactoid(self, irc, msg, match):
@ -236,7 +236,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
# get caught due to nesting # get caught due to nesting
# cb = callbacks.findCallbackForCommand(irc, msg) # cb = callbacks.findCallbackForCommand(irc, msg)
# if cb: # if cb:
# irc.reply(msg, irc.getHelp(cb[0].config)) # irc.reply(irc.getHelp(cb[0].config))
# return # return
# First, check and see if the entire message matches a factoid key # First, check and see if the entire message matches a factoid key
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
@ -251,7 +251,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
key, fact = match.groups() key, fact = match.groups()
# These are okay, unless there's an _is_ in there, in which case # These are okay, unless there's an _is_ in there, in which case
@ -263,7 +263,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
# Check and make sure it's not in the DB already # Check and make sure it's not in the DB already
cursor.execute("""SELECT * FROM factoids WHERE key LIKE %s""", key) cursor.execute("""SELECT * FROM factoids WHERE key LIKE %s""", key)
if cursor.rowcount != 0: if cursor.rowcount != 0:
irc.error(msg, 'Factoid %r already exists.' % key) irc.error('Factoid %r already exists.' % key)
return return
# Otherwise, # Otherwise,
cursor.execute("""INSERT INTO factoids VALUES cursor.execute("""INSERT INTO factoids VALUES
@ -271,7 +271,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
%s, 0)""", %s, 0)""",
key, id, int(time.time()), fact) key, id, int(time.time()), fact)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
def changeFactoid(self, irc, msg, match): def changeFactoid(self, irc, msg, match):
r"(.+)\s+=~\s+(.+)" r"(.+)\s+=~\s+(.+)"
@ -279,7 +279,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
key, regexp = match.groups() key, regexp = match.groups()
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
@ -288,18 +288,18 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
cursor.execute("""SELECT locked_at, fact FROM factoids cursor.execute("""SELECT locked_at, fact FROM factoids
WHERE key LIKE %s""", key) WHERE key LIKE %s""", key)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, "Factoid %r not found." % key) irc.error("Factoid %r not found." % key)
return return
# No dice if it's locked, no matter who it is # No dice if it's locked, no matter who it is
(locked_at, fact) = cursor.fetchone() (locked_at, fact) = cursor.fetchone()
if locked_at is not None: if locked_at is not None:
irc.error(msg, "Factoid %r is locked." % key) irc.error("Factoid %r is locked." % key)
return return
# It's fair game if we get to here # It's fair game if we get to here
try: try:
r = utils.perlReToReplacer(regexp) r = utils.perlReToReplacer(regexp)
except ValueError, e: except ValueError, e:
irc.error(msg, "Invalid regexp: %r" % regexp) irc.error("Invalid regexp: %r" % regexp)
return return
new_fact = r(fact) new_fact = r(fact)
cursor.execute("""UPDATE factoids cursor.execute("""UPDATE factoids
@ -307,7 +307,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
modified_at = %s WHERE key = %s""", modified_at = %s WHERE key = %s""",
new_fact, id, int(time.time()), key) new_fact, id, int(time.time()), key)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
def augmentFactoid(self, irc, msg, match): def augmentFactoid(self, irc, msg, match):
r"(.+?) is also (.+)" r"(.+?) is also (.+)"
@ -315,7 +315,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
key, new_text = match.groups() key, new_text = match.groups()
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
@ -324,12 +324,12 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
cursor.execute("""SELECT locked_at, fact FROM factoids cursor.execute("""SELECT locked_at, fact FROM factoids
WHERE key LIKE %s""", key) WHERE key LIKE %s""", key)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, "Factoid %r not found." % key) irc.error("Factoid %r not found." % key)
return return
# No dice if it's locked, no matter who it is # No dice if it's locked, no matter who it is
(locked_at, fact) = cursor.fetchone() (locked_at, fact) = cursor.fetchone()
if locked_at is not None: if locked_at is not None:
irc.error(msg, "Factoid %r is locked." % key) irc.error("Factoid %r is locked." % key)
return return
# It's fair game if we get to here # It's fair game if we get to here
new_fact = "%s, or %s" % (fact, new_text) new_fact = "%s, or %s" % (fact, new_text)
@ -338,7 +338,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
modified_at = %s WHERE key = %s""", modified_at = %s WHERE key = %s""",
new_fact, id, int(time.time()), key) new_fact, id, int(time.time()), key)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
def replaceFactoid(self, irc, msg, match): def replaceFactoid(self, irc, msg, match):
r"^no,?\s+(.+?)\s+is\s+(.+)" r"^no,?\s+(.+?)\s+is\s+(.+)"
@ -346,7 +346,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
key, new_fact = match.groups() key, new_fact = match.groups()
# These are okay, unless there's an _is_ in there, in which case # These are okay, unless there's an _is_ in there, in which case
@ -360,12 +360,12 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
cursor.execute("""SELECT locked_at, fact FROM factoids cursor.execute("""SELECT locked_at, fact FROM factoids
WHERE key LIKE %s""", key) WHERE key LIKE %s""", key)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, "Factoid %r not found." % key) irc.error("Factoid %r not found." % key)
return return
# No dice if it's locked, no matter who it is # No dice if it's locked, no matter who it is
(locked_at, _) = cursor.fetchone() (locked_at, _) = cursor.fetchone()
if locked_at is not None: if locked_at is not None:
irc.error(msg, "Factoid %r is locked." % key) irc.error("Factoid %r is locked." % key)
return return
# It's fair game if we get to here # It's fair game if we get to here
cursor.execute("""UPDATE factoids cursor.execute("""UPDATE factoids
@ -377,7 +377,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
WHERE key = %s""", WHERE key = %s""",
new_fact, id, int(time.time()), key) new_fact, id, int(time.time()), key)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
def literal(self, irc, msg, args): def literal(self, irc, msg, args):
"""<factoid key> """<factoid key>
@ -390,11 +390,11 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT fact FROM factoids WHERE key LIKE %s""", key) cursor.execute("""SELECT fact FROM factoids WHERE key LIKE %s""", key)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, "No such factoid: %r" % key) irc.error("No such factoid: %r" % key)
return return
else: else:
fact = cursor.fetchone()[0] fact = cursor.fetchone()[0]
irc.reply(msg, fact) irc.reply(fact)
def factinfo(self, irc, msg, args): def factinfo(self, irc, msg, args):
"""<factoid key> """<factoid key>
@ -412,7 +412,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
requested_count, locked_by, locked_at FROM requested_count, locked_by, locked_at FROM
factoids WHERE key LIKE %s""", key) factoids WHERE key LIKE %s""", key)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, "No such factoid: %r" % key) irc.error("No such factoid: %r" % key)
return return
(created_by, created_at, modified_by, modified_at, last_requested_by, (created_by, created_at, modified_by, modified_at, last_requested_by,
last_requested_at, requested_count, locked_by, last_requested_at, requested_count, locked_by,
@ -444,13 +444,13 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
time.localtime(int(locked_at))) time.localtime(int(locked_at)))
lock_by = ircdb.users.getUser(locked_by).name lock_by = ircdb.users.getUser(locked_by).name
s += " Locked by %s on %s." % (lock_by, lock_at) s += " Locked by %s on %s." % (lock_by, lock_at)
irc.reply(msg, s) irc.reply(s)
def _lock(self, irc, msg, args, lock=True): def _lock(self, irc, msg, args, lock=True):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
key = privmsgs.getArgs(args, required=1) key = privmsgs.getArgs(args, required=1)
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
@ -458,24 +458,24 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
cursor.execute("""SELECT created_by, locked_by FROM factoids cursor.execute("""SELECT created_by, locked_by FROM factoids
WHERE key LIKE %s""", key) WHERE key LIKE %s""", key)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, "No such factoid: %r" % key) irc.error("No such factoid: %r" % key)
return return
(created_by, locked_by) = cursor.fetchone() (created_by, locked_by) = cursor.fetchone()
# Don't perform redundant operations # Don't perform redundant operations
if lock: if lock:
if locked_by is not None: if locked_by is not None:
irc.error(msg, "Factoid %r is already locked." % key) irc.error("Factoid %r is already locked." % key)
return return
else: else:
if locked_by is None: if locked_by is None:
irc.error(msg, "Factoid %r is not locked." % key) irc.error("Factoid %r is not locked." % key)
return return
# Can only lock/unlock own factoids unless you're an admin # Can only lock/unlock own factoids unless you're an admin
if not (ircdb.checkCapability(id, 'admin') or created_by == id): if not (ircdb.checkCapability(id, 'admin') or created_by == id):
s = "unlock" s = "unlock"
if lock: if lock:
s = "lock" s = "lock"
irc.error(msg, "Cannot %s someone else's factoid unless you " irc.error("Cannot %s someone else's factoid unless you "
"are an admin." % s) "are an admin." % s)
return return
# Okay, we're done, ready to lock/unlock # Okay, we're done, ready to lock/unlock
@ -487,7 +487,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
cursor.execute("""UPDATE factoids SET locked_at = %s, locked_by = %s cursor.execute("""UPDATE factoids SET locked_at = %s, locked_by = %s
WHERE key = %s""", locked_at, id, key) WHERE key = %s""", locked_at, id, key)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
def lock(self, irc, msg, args): def lock(self, irc, msg, args):
"""<factoid key> """<factoid key>
@ -524,12 +524,12 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT COUNT(*) FROM factoids""") cursor.execute("""SELECT COUNT(*) FROM factoids""")
if int(cursor.fetchone()[0]) == 0: if int(cursor.fetchone()[0]) == 0:
irc.error(msg, 'I don\'t have any factoids in my database!') irc.error('I don\'t have any factoids in my database!')
else: else:
try: try:
irc.reply(msg, method(cursor, self._mostCount)) irc.reply(method(cursor, self._mostCount))
except self.MostException, e: except self.MostException, e:
irc.error(msg, str(e)) irc.error(str(e))
def _mostAuthored(self, cursor, limit): def _mostAuthored(self, cursor, limit):
cursor.execute("""SELECT created_by, count(key) FROM factoids cursor.execute("""SELECT created_by, count(key) FROM factoids
@ -570,7 +570,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
try: try:
id = ircdb.users.getUserId(author) id = ircdb.users.getUserId(author)
except KeyError: except KeyError:
irc.error(msg, "No such user: %r" % author) irc.error("No such user: %r" % author)
return return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
@ -578,12 +578,12 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
WHERE created_by = %s WHERE created_by = %s
ORDER BY key""", id) ORDER BY key""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, "No factoids by %r found." % author) irc.reply("No factoids by %r found." % author)
return return
keys = [repr(tup[0]) for tup in cursor.fetchall()] keys = [repr(tup[0]) for tup in cursor.fetchall()]
s = "Author search for %r (%s found): %s" % \ s = "Author search for %r (%s found): %s" % \
(author, len(keys), utils.commaAndify(keys)) (author, len(keys), utils.commaAndify(keys))
irc.reply(msg, s) irc.reply(s)
def listkeys(self, irc, msg, args): def listkeys(self, irc, msg, args):
"""<text> """<text>
@ -599,7 +599,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
ORDER BY key""", ORDER BY key""",
glob) glob)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, "No keys matching %r found." % search) irc.reply("No keys matching %r found." % search)
return return
elif cursor.rowcount == 1: elif cursor.rowcount == 1:
key = cursor.fetchone()[0] key = cursor.fetchone()[0]
@ -608,7 +608,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
keys = [repr(tup[0]) for tup in cursor.fetchall()] keys = [repr(tup[0]) for tup in cursor.fetchall()]
s = "Key search for %r (%s found): %s" % \ s = "Key search for %r (%s found): %s" % \
(search, len(keys), utils.commaAndify(keys)) (search, len(keys), utils.commaAndify(keys))
irc.reply(msg, s) irc.reply(s)
def listvalues(self, irc, msg, args): def listvalues(self, irc, msg, args):
"""<text> """<text>
@ -624,12 +624,12 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
ORDER BY key""", ORDER BY key""",
glob) glob)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, "No values matching %r found." % search) irc.reply("No values matching %r found." % search)
return return
keys = [repr(tup[0]) for tup in cursor.fetchall()] keys = [repr(tup[0]) for tup in cursor.fetchall()]
s = "Value search for %r (%s found): %s" % \ s = "Value search for %r (%s found): %s" % \
(search, len(keys), utils.commaAndify(keys)) (search, len(keys), utils.commaAndify(keys))
irc.reply(msg, s) irc.reply(s)
def delete(self, irc, msg, args): def delete(self, irc, msg, args):
"""<factoid key> """<factoid key>
@ -640,7 +640,7 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
try: try:
ircdb.users.getUserId(msg.prefix) ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
key = privmsgs.getArgs(args, required=1) key = privmsgs.getArgs(args, required=1)
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
@ -648,15 +648,15 @@ class MoobotFactoids(callbacks.PrivmsgCommandAndRegexp):
cursor.execute("""SELECT key, locked_at FROM factoids cursor.execute("""SELECT key, locked_at FROM factoids
WHERE key LIKE %s""", key) WHERE key LIKE %s""", key)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, "No such factoid: %r" % key) irc.error("No such factoid: %r" % key)
return return
(_, locked_at) = cursor.fetchone() (_, locked_at) = cursor.fetchone()
if locked_at is not None: if locked_at is not None:
irc.error(msg, "Factoid is locked, cannot remove.") irc.error("Factoid is locked, cannot remove.")
return return
cursor.execute("""DELETE FROM factoids WHERE key = %s""", key) cursor.execute("""DELETE FROM factoids WHERE key = %s""", key)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
Class = MoobotFactoids Class = MoobotFactoids

View File

@ -77,29 +77,29 @@ class Movies(callbacks.Privmsg):
db = IMDb.IMDb() db = IMDb.IMDb()
movies = db.search(movieTitle) movies = db.search(movieTitle)
if len(movies) == 0: if len(movies) == 0:
irc.reply(msg, 'No movies matched that title.') irc.reply('No movies matched that title.')
elif len(movies) == 1: elif len(movies) == 1:
movie = movies[0] movie = movies[0]
if 'Name?' in movie.url: if 'Name?' in movie.url:
s = '"%s" is apparently a person. ' \ s = '"%s" is apparently a person. ' \
'More information is available at <%s>' % \ 'More information is available at <%s>' % \
(movie.title(), movie.url) (movie.title(), movie.url)
irc.reply(msg, s) irc.reply(s)
else: else:
irc.reply(msg, self._formatMovie(movie)) irc.reply(self._formatMovie(movie))
elif len(movies) > 20: elif len(movies) > 20:
s = 'More than 20 movies matched, please narrow your search.' s = 'More than 20 movies matched, please narrow your search.'
irc.reply(msg, s) irc.reply(s)
else: else:
for movie in movies: for movie in movies:
title = movie.title().lower() title = movie.title().lower()
if utils.unCommaThe(title) == movieTitle.lower(): if utils.unCommaThe(title) == movieTitle.lower():
irc.reply(msg, self._formatMovie(movie)) irc.reply(self._formatMovie(movie))
return return
titles = ['%s (%s)' % \ titles = ['%s (%s)' % \
(utils.unCommaThe(movie.title()), movie.year()) (utils.unCommaThe(movie.title()), movie.year())
for movie in movies] for movie in movies]
irc.reply(msg, 'Matches: ' + utils.commaAndify(titles)) irc.reply('Matches: ' + utils.commaAndify(titles))
Class = Movies Class = Movies

View File

@ -66,18 +66,18 @@ class Network(callbacks.Privmsg):
if ircutils.isIP(host): if ircutils.isIP(host):
hostname = socket.getfqdn(host) hostname = socket.getfqdn(host)
if hostname == host: if hostname == host:
irc.reply(msg, 'Host not found.') irc.reply('Host not found.')
else: else:
irc.reply(msg, hostname) irc.reply(hostname)
else: else:
try: try:
ip = socket.gethostbyname(host) ip = socket.gethostbyname(host)
if ip == '64.94.110.11': # Verisign sucks! if ip == '64.94.110.11': # Verisign sucks!
irc.reply(msg, 'Host not found.') irc.reply('Host not found.')
else: else:
irc.reply(msg, ip) irc.reply(ip)
except socket.error: except socket.error:
irc.reply(msg, 'Host not found.') irc.reply('Host not found.')
_tlds = sets.Set(['com', 'net', 'edu']) _tlds = sets.Set(['com', 'net', 'edu'])
def whois(self, irc, msg, args): def whois(self, irc, msg, args):
@ -88,10 +88,10 @@ class Network(callbacks.Privmsg):
""" """
domain = privmsgs.getArgs(args) domain = privmsgs.getArgs(args)
if '.' not in domain or domain.split('.')[-1] not in self._tlds: if '.' not in domain or domain.split('.')[-1] not in self._tlds:
irc.error(msg, '<domain> must be in .com, .net, or .edu.') irc.error('<domain> must be in .com, .net, or .edu.')
return return
elif len(domain.split('.')) != 2: elif len(domain.split('.')) != 2:
irc.error(msg, '<domain> must be a domain, not a hostname.') irc.error('<domain> must be a domain, not a hostname.')
return return
t = telnetlib.Telnet('rs.internic.net', 43) t = telnetlib.Telnet('rs.internic.net', 43)
t.write(domain) t.write(domain)
@ -116,9 +116,9 @@ class Network(callbacks.Privmsg):
try: try:
s = '%s <%s> is %s; registered %s, updated %s, expires %s.' % \ s = '%s <%s> is %s; registered %s, updated %s, expires %s.' % \
(domain, url, status, created, updated, expires) (domain, url, status, created, updated, expires)
irc.reply(msg, s) irc.reply(s)
except NameError, e: except NameError, e:
irc.error(msg, 'I couldn\'t find such a domain.') irc.error('I couldn\'t find such a domain.')
Class = Network Class = Network

View File

@ -115,7 +115,7 @@ class News(plugins.ChannelDBHandler, callbacks.Privmsg):
cursor.execute("INSERT INTO news VALUES (NULL, %s, %s, %s, %s, %s)", cursor.execute("INSERT INTO news VALUES (NULL, %s, %s, %s, %s, %s)",
subject[:-1], text, added_at, expires, name) subject[:-1], text, added_at, expires, name)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
add = privmsgs.checkChannelCapability(add, 'news') add = privmsgs.checkChannelCapability(add, 'news')
def _readnews(self, irc, msg, args): def _readnews(self, irc, msg, args):
@ -133,7 +133,7 @@ class News(plugins.ChannelDBHandler, callbacks.Privmsg):
news.expires_at, news.added_by FROM news news.expires_at, news.added_by FROM news
WHERE news.id=%s""", id) WHERE news.id=%s""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No news item matches that id.') irc.error('No news item matches that id.')
else: else:
item, subject, added_at, expires_at, added_by = cursor.fetchone() item, subject, added_at, expires_at, added_by = cursor.fetchone()
if int(expires_at) == 0: if int(expires_at) == 0:
@ -148,7 +148,7 @@ class News(plugins.ChannelDBHandler, callbacks.Privmsg):
time.localtime(int(added_at))), time.localtime(int(added_at))),
time.strftime(conf.humanTimestampFormat, time.strftime(conf.humanTimestampFormat,
time.localtime(int(expires_at)))) time.localtime(int(expires_at))))
irc.reply(msg, s) irc.reply(s)
def news(self, irc, msg, args): def news(self, irc, msg, args):
"""[<channel>] [<number>] """[<channel>] [<number>]
@ -169,11 +169,11 @@ class News(plugins.ChannelDBHandler, callbacks.Privmsg):
WHERE news.expires_at > %s WHERE news.expires_at > %s
OR news.expires_at=0""", int(time.time())) OR news.expires_at=0""", int(time.time()))
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'No news for %s' % channel) irc.reply('No news for %s' % channel)
else: else:
items = ['(#%s) %s' % (id, s) for (id, s) in cursor.fetchall()] items = ['(#%s) %s' % (id, s) for (id, s) in cursor.fetchall()]
s = 'News for %s: %s' % (channel, '; '.join(items)) s = 'News for %s: %s' % (channel, '; '.join(items))
irc.reply(msg, s) irc.reply(s)
def remove(self, irc, msg, args, channel): def remove(self, irc, msg, args, channel):
"""[<channel>] <number> """[<channel>] <number>
@ -186,11 +186,11 @@ class News(plugins.ChannelDBHandler, callbacks.Privmsg):
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT * FROM news WHERE id=%s""", id) cursor.execute("""SELECT * FROM news WHERE id=%s""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No news item matches that id.') irc.error('No news item matches that id.')
else: else:
cursor.execute("""DELETE FROM news WHERE news.id = %s""", id) cursor.execute("""DELETE FROM news WHERE news.id = %s""", id)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
remove = privmsgs.checkChannelCapability(remove, 'news') remove = privmsgs.checkChannelCapability(remove, 'news')
def change(self, irc, msg, args, channel): def change(self, irc, msg, args, channel):
@ -205,13 +205,13 @@ class News(plugins.ChannelDBHandler, callbacks.Privmsg):
try: try:
replacer = utils.perlReToReplacer(regexp) replacer = utils.perlReToReplacer(regexp)
except ValueError, e: except ValueError, e:
irc.error(msg, str(e)) irc.error(str(e))
return return
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT subject, item FROM news WHERE id=%s""", id) cursor.execute("""SELECT subject, item FROM news WHERE id=%s""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No news item matches that id.') irc.error('No news item matches that id.')
return return
(subject, item) = cursor.fetchone() (subject, item) = cursor.fetchone()
s = '%s: %s' % (subject, item) s = '%s: %s' % (subject, item)
@ -219,7 +219,7 @@ class News(plugins.ChannelDBHandler, callbacks.Privmsg):
(newSubject, newItem) = s.split(': ') (newSubject, newItem) = s.split(': ')
cursor.execute("""UPDATE news SET subject=%s, item=%s WHERE id=%s""", cursor.execute("""UPDATE news SET subject=%s, item=%s WHERE id=%s""",
newSubject, newItem, id) newSubject, newItem, id)
irc.replySuccess(msg) irc.replySuccess()
change = privmsgs.checkChannelCapability(change, 'news') change = privmsgs.checkChannelCapability(change, 'news')
def old(self, irc, msg, args): def old(self, irc, msg, args):
@ -237,23 +237,23 @@ class News(plugins.ChannelDBHandler, callbacks.Privmsg):
try: try:
id = int(id) id = int(id)
except ValueError: except ValueError:
irc.error(msg, '%r isn\'t a valid id.' % id) irc.error('%r isn\'t a valid id.' % id)
return return
cursor.execute("""SELECT subject, item FROM news WHERE id=%s""",id) cursor.execute("""SELECT subject, item FROM news WHERE id=%s""",id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No news item matches that id.') irc.error('No news item matches that id.')
else: else:
(subject, item) = cursor.fetchone() (subject, item) = cursor.fetchone()
irc.reply(msg, '%s: %s' % (cursor, item)) irc.reply('%s: %s' % (cursor, item))
else: else:
cursor.execute("""SELECT id, subject FROM news cursor.execute("""SELECT id, subject FROM news
WHERE expires_at <> 0 AND expires_at < %s WHERE expires_at <> 0 AND expires_at < %s
ORDER BY id DESC""", int(time.time())) ORDER BY id DESC""", int(time.time()))
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'I have no news for that channel.') irc.error('I have no news for that channel.')
return return
subjects = ['#%s: %s' % (id, s) for (id, s) in cursor.fetchall()] subjects = ['#%s: %s' % (id, s) for (id, s) in cursor.fetchall()]
irc.reply(msg, utils.commaAndify(subjects)) irc.reply(utils.commaAndify(subjects))

View File

@ -134,12 +134,12 @@ class Note(callbacks.Privmsg):
hostmask = irc.state.nickToHostmask(name) hostmask = irc.state.nickToHostmask(name)
toId = ircdb.users.getUserId(hostmask) toId = ircdb.users.getUserId(hostmask)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
try: try:
fromId = ircdb.users.getUserId(msg.prefix) fromId = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
if ircutils.isChannel(msg.args[0]): if ircutils.isChannel(msg.args[0]):
public = 1 public = 1
@ -156,7 +156,7 @@ class Note(callbacks.Privmsg):
from_id=%s AND to_id=%s AND added_at=%s""", from_id=%s AND to_id=%s AND added_at=%s""",
fromId, toId, now) fromId, toId, now)
id = cursor.fetchone()[0] id = cursor.fetchone()[0]
irc.reply(msg, 'Note #%s sent to %s.' % (id, name)) irc.reply('Note #%s sent to %s.' % (id, name))
def unsend(self, irc, msg, args): def unsend(self, irc, msg, args):
"""<id> """<id>
@ -168,24 +168,24 @@ class Note(callbacks.Privmsg):
try: try:
userid = ircdb.users.getUserId(msg.prefix) userid = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT from_id, read FROM notes WHERE id=%s""", id) cursor.execute("""SELECT from_id, read FROM notes WHERE id=%s""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'That\'s not a valid note id.') irc.error('That\'s not a valid note id.')
return return
(from_id, read) = map(int, cursor.fetchone()) (from_id, read) = map(int, cursor.fetchone())
if from_id == userid: if from_id == userid:
if not read: if not read:
cursor.execute("""DELETE FROM notes WHERE id=%s""", id) cursor.execute("""DELETE FROM notes WHERE id=%s""", id)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, 'That note has been read already.') irc.error('That note has been read already.')
else: else:
irc.error(msg, 'That note wasn\'t sent by you.') irc.error('That note wasn\'t sent by you.')
def note(self, irc, msg, args): def note(self, irc, msg, args):
@ -197,12 +197,12 @@ class Note(callbacks.Privmsg):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
try: try:
noteid = int(noteid) noteid = int(noteid)
except ValueError: except ValueError:
irc.error(msg, '%r is not a valid note id.' % noteid) irc.error('%r is not a valid note id.' % noteid)
return return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
@ -212,7 +212,7 @@ class Note(callbacks.Privmsg):
id, id, noteid) id, id, noteid)
if cursor.rowcount == 0: if cursor.rowcount == 0:
s = 'You may only retrieve notes you\'ve sent or received.' s = 'You may only retrieve notes you\'ve sent or received.'
irc.error(msg, s) irc.error(s)
return return
(note, toId, fromId, addedAt, public) = cursor.fetchone() (note, toId, fromId, addedAt, public) = cursor.fetchone()
(toId,fromId,addedAt,public) = imap(int, (toId,fromId,addedAt,public)) (toId,fromId,addedAt,public) = imap(int, (toId,fromId,addedAt,public))
@ -223,7 +223,7 @@ class Note(callbacks.Privmsg):
elif fromId == id: elif fromId == id:
recipient = ircdb.users.getUser(toId).name recipient = ircdb.users.getUser(toId).name
newnote = '%s (Sent to %s %s ago)' % (note, recipient, elapsed) newnote = '%s (Sent to %s %s ago)' % (note, recipient, elapsed)
irc.reply(msg, newnote, private=(not public)) irc.reply(newnote, private=(not public))
self.setAsRead(noteid) self.setAsRead(noteid)
def _formatNoteData(self, msg, id, fromId, public): def _formatNoteData(self, msg, id, fromId, public):
@ -247,7 +247,7 @@ class Note(callbacks.Privmsg):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
@ -257,10 +257,10 @@ class Note(callbacks.Privmsg):
count = cursor.rowcount count = cursor.rowcount
L = [] L = []
if count == 0: if count == 0:
irc.reply(msg, 'You have no unread notes.') irc.reply('You have no unread notes.')
else: else:
L = [self._formatNoteData(msg, *t) for t in cursor.fetchall()] L = [self._formatNoteData(msg, *t) for t in cursor.fetchall()]
irc.reply(msg, utils.commaAndify(L)) irc.reply(utils.commaAndify(L))
def _oldnotes(self, irc, msg, args): def _oldnotes(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -270,7 +270,7 @@ class Note(callbacks.Privmsg):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
@ -278,11 +278,11 @@ class Note(callbacks.Privmsg):
FROM notes FROM notes
WHERE notes.to_id=%s AND notes.read=1""", id) WHERE notes.to_id=%s AND notes.read=1""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'I couldn\'t find any read notes for your user.') irc.reply('I couldn\'t find any read notes for your user.')
else: else:
ids = [self._formatNoteData(msg, *t) for t in cursor.fetchall()] ids = [self._formatNoteData(msg, *t) for t in cursor.fetchall()]
ids.reverse() ids.reverse()
irc.reply(msg, utils.commaAndify(ids)) irc.reply(utils.commaAndify(ids))
Class = Note Class = Note

View File

@ -254,13 +254,13 @@ class OSU(callbacks.Privmsg):
if 'Published address' in line: if 'Published address' in line:
emails.append(line.split()[-1]) emails.append(line.split()[-1])
if len(emails) == 0: if len(emails) == 0:
irc.reply(msg, 'There seem to be no matches to that name.') irc.reply('There seem to be no matches to that name.')
elif len(emails) == 1: elif len(emails) == 1:
irc.reply(msg, emails[0]) irc.reply(emails[0])
else: else:
irc.reply(msg, 'Possible matches: %s' % ', '.join(emails)) irc.reply('Possible matches: %s' % ', '.join(emails))
except Exception, e: except Exception, e:
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
def building(self, irc, msg, args): def building(self, irc, msg, args):
"""<building abbreviation> """<building abbreviation>
@ -270,9 +270,9 @@ class OSU(callbacks.Privmsg):
""" """
building = privmsgs.getArgs(args) building = privmsgs.getArgs(args)
try: try:
irc.reply(msg, buildings[building.upper()]) irc.reply(buildings[building.upper()])
except KeyError: except KeyError:
irc.reply(msg, 'I don\'t know of any such OSU building.') irc.reply('I don\'t know of any such OSU building.')
Class = OSU Class = OSU

View File

@ -76,7 +76,7 @@ class Parter(callbacks.Privmsg):
""" """
channel = privmsgs.getArgs(args) channel = privmsgs.getArgs(args)
self.channels.add(channel) self.channels.add(channel)
irc.replySuccess(msg) irc.replySuccess()
autopart = privmsgs.checkCapability(autopart, 'admin') autopart = privmsgs.checkCapability(autopart, 'admin')
def removeautopart(self, irc, msg, args): def removeautopart(self, irc, msg, args):
@ -86,7 +86,7 @@ class Parter(callbacks.Privmsg):
""" """
channel = privmsgs.getArgs(args) channel = privmsgs.getArgs(args)
self.channels.discard(channel) self.channels.discard(channel)
irc.replySuccess(msg) irc.replySuccess()
removeautopart = privmsgs.checkCapability(removeautopart, 'admin') removeautopart = privmsgs.checkCapability(removeautopart, 'admin')
def doJoin(self, irc, msg): def doJoin(self, irc, msg):

View File

@ -105,7 +105,7 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
FROM polls WHERE id=%s""", FROM polls WHERE id=%s""",
poll_id) poll_id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no poll with id %s' % poll_id) irc.error('There is no poll with id %s' % poll_id)
return return
_, question, started_by, open = cursor.fetchone() _, question, started_by, open = cursor.fetchone()
starter = ircdb.users.getUser(started_by).name starter = ircdb.users.getUser(started_by).name
@ -125,7 +125,7 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
for id, option in options]) for id, option in options])
pollstr = 'Poll #%s: %r started by %s. %s. Poll is %s.' % \ pollstr = 'Poll #%s: %r started by %s. %s. Poll is %s.' % \
(poll_id, question, starter, optionstr, statusstr) (poll_id, question, starter, optionstr, statusstr)
irc.reply(msg, pollstr) irc.reply(pollstr)
def open(self, irc, msg, args): def open(self, irc, msg, args):
"""[<channel>] <question> """[<channel>] <question>
@ -138,7 +138,7 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
try: try:
userId = ircdb.users.getUserId(msg.prefix) userId = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
@ -148,7 +148,7 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
db.commit() db.commit()
cursor.execute("""SELECT id FROM polls WHERE question=%s""", question) cursor.execute("""SELECT id FROM polls WHERE question=%s""", question)
id = cursor.fetchone()[0] id = cursor.fetchone()[0]
irc.reply(msg, '%s (poll #%s)' % (conf.replySuccess, id)) irc.reply('%s (poll #%s)' % (conf.replySuccess, id))
def close(self, irc, msg, args): def close(self, irc, msg, args):
"""[<channel>] <id> """[<channel>] <id>
@ -160,17 +160,17 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
try: try:
id = int(id) id = int(id)
except ValueError: except ValueError:
irc.error(msg, 'The id must be an integer.') irc.error('The id must be an integer.')
return return
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
# Check to make sure that the poll exists # Check to make sure that the poll exists
cursor.execute("""SELECT id FROM polls WHERE id=%s""", id) cursor.execute("""SELECT id FROM polls WHERE id=%s""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'Id #%s is not an existing poll.') irc.error('Id #%s is not an existing poll.')
return return
cursor.execute("""UPDATE polls SET open=0 WHERE id=%s""", id) cursor.execute("""UPDATE polls SET open=0 WHERE id=%s""", id)
irc.replySuccess(msg) irc.replySuccess()
def add(self, irc, msg, args): def add(self, irc, msg, args):
"""[<channel>] <id> <option text> """[<channel>] <id> <option text>
@ -182,12 +182,12 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
try: try:
poll_id = int(poll_id) poll_id = int(poll_id)
except ValueError: except ValueError:
irc.error(msg, 'The id must be an integer.') irc.error('The id must be an integer.')
return return
try: try:
userId = ircdb.users.getUserId(msg.prefix) userId = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
@ -196,18 +196,18 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
WHERE id=%s""", WHERE id=%s""",
poll_id) poll_id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such poll.') irc.error('There is no such poll.')
return return
if not ((userId == cursor.fetchone()[0]) or if not ((userId == cursor.fetchone()[0]) or
(ircdb.checkCapability(userId, 'admin'))): (ircdb.checkCapability(userId, 'admin'))):
irc.error(msg, 'That poll isn\'t yours and you aren\'t an admin.') irc.error('That poll isn\'t yours and you aren\'t an admin.')
return return
# and NOBODY can add options once a poll has votes # and NOBODY can add options once a poll has votes
cursor.execute("""SELECT COUNT(user_id) FROM votes cursor.execute("""SELECT COUNT(user_id) FROM votes
WHERE poll_id=%s""", WHERE poll_id=%s""",
poll_id) poll_id)
if int(cursor.fetchone()[0]) != 0: if int(cursor.fetchone()[0]) != 0:
irc.error(msg, 'Cannot add options to a poll with votes.') irc.error('Cannot add options to a poll with votes.')
return return
# Get the next highest id # Get the next highest id
cursor.execute("""SELECT MAX(id)+1 FROM options cursor.execute("""SELECT MAX(id)+1 FROM options
@ -217,7 +217,7 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
cursor.execute("""INSERT INTO options VALUES cursor.execute("""INSERT INTO options VALUES
(%s, %s, %s)""", (%s, %s, %s)""",
option_id, poll_id, option) option_id, poll_id, option)
irc.replySuccess(msg) irc.replySuccess()
def vote(self, irc, msg, args): def vote(self, irc, msg, args):
"""[<channel>] <poll id> <option id> """[<channel>] <poll id> <option id>
@ -231,13 +231,13 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
poll_id = int(poll_id) poll_id = int(poll_id)
option_id = int(option_id) option_id = int(option_id)
except ValueError: except ValueError:
irc.error(msg, 'The poll id and option id ' irc.error('The poll id and option id '
'arguments must be an integers.') 'arguments must be an integers.')
return return
try: try:
userId = ircdb.users.getUserId(msg.prefix) userId = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
@ -245,17 +245,17 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
FROM polls WHERE id=%s""", FROM polls WHERE id=%s""",
poll_id) poll_id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such poll.') irc.error('There is no such poll.')
return return
elif int(cursor.fetchone()[0]) == 0: elif int(cursor.fetchone()[0]) == 0:
irc.error(msg, 'That poll is closed.') irc.error('That poll is closed.')
return return
cursor.execute("""SELECT id FROM options cursor.execute("""SELECT id FROM options
WHERE poll_id=%s WHERE poll_id=%s
AND id=%s""", AND id=%s""",
poll_id, option_id) poll_id, option_id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such option.') irc.error('There is no such option.')
return return
cursor.execute("""SELECT option_id FROM votes cursor.execute("""SELECT option_id FROM votes
WHERE user_id=%s AND poll_id=%s""", WHERE user_id=%s AND poll_id=%s""",
@ -267,7 +267,7 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
cursor.execute("""UPDATE votes SET option_id=%s cursor.execute("""UPDATE votes SET option_id=%s
WHERE user_id=%s AND poll_id=%s""", WHERE user_id=%s AND poll_id=%s""",
option_id, userId, poll_id) option_id, userId, poll_id)
irc.replySuccess(msg) irc.replySuccess()
def results(self, irc, msg, args): def results(self, irc, msg, args):
"""[<channel>] <id> """[<channel>] <id>
@ -279,7 +279,7 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
try: try:
poll_id = int(poll_id) poll_id = int(poll_id)
except ValueError: except ValueError:
irc.error(msg, 'The id argument must be an integer.') irc.error('The id argument must be an integer.')
return return
db = self.getDb(channel) db = self.getDb(channel)
cursor = db.cursor() cursor = db.cursor()
@ -287,7 +287,7 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
FROM polls WHERE id=%s""", FROM polls WHERE id=%s""",
poll_id) poll_id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There is no such poll.') irc.error('There is no such poll.')
return return
(id, question, startedBy, open) = cursor.fetchone() (id, question, startedBy, open) = cursor.fetchone()
try: try:
@ -323,7 +323,7 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
results.append('%r: %s' % (option, int(count))) results.append('%r: %s' % (option, int(count)))
s = utils.commaAndify(results) s = utils.commaAndify(results)
reply += ' - %s' % s reply += ' - %s' % s
irc.reply(msg, reply) irc.reply(reply)
def list(self, irc, msg, args): def list(self, irc, msg, args):
"""takes no arguments. """takes no arguments.
@ -335,10 +335,10 @@ class Poll(callbacks.Privmsg, plugins.ChannelDBHandler):
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT id, question FROM polls WHERE open=1""") cursor.execute("""SELECT id, question FROM polls WHERE open=1""")
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'This channel currently has no open polls.') irc.reply('This channel currently has no open polls.')
return return
polls = ['#%s: %r' % (id, q) for id, q in cursor.fetchall()] polls = ['#%s: %r' % (id, q) for id, q in cursor.fetchall()]
irc.reply(msg, utils.commaAndify(polls)) irc.reply(utils.commaAndify(polls))
Class = Poll Class = Poll

View File

@ -121,7 +121,7 @@ class Python(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
return newmodule return newmodule
name = privmsgs.getArgs(args) name = privmsgs.getArgs(args)
if name.translate(string.ascii, self.modulechars) != '': if name.translate(string.ascii, self.modulechars) != '':
irc.error(msg, 'That\'s not a valid module or function name.') irc.error('That\'s not a valid module or function name.')
return return
if '.' in name: if '.' in name:
(moduleName, funcName) = rsplit(name, '.', 1) (moduleName, funcName) = rsplit(name, '.', 1)
@ -130,42 +130,42 @@ class Python(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
if hasattr(obj, funcName): if hasattr(obj, funcName):
obj = getattr(obj, funcName) obj = getattr(obj, funcName)
if hasattr(obj, '__doc__'): if hasattr(obj, '__doc__'):
irc.reply(msg, normalize(obj.__doc__)) irc.reply(normalize(obj.__doc__))
else: else:
irc.reply(msg, '%s has no documentation' % name) irc.reply('%s has no documentation' % name)
else: else:
s = '%s has no method %s' % (moduleName, funcName) s = '%s has no method %s' % (moduleName, funcName)
irc.reply(msg, s) irc.reply(s)
elif moduleName: elif moduleName:
newmodule = getModule(moduleName) newmodule = getModule(moduleName)
if newmodule is None: if newmodule is None:
irc.error(msg, 'No module %s exists.' % moduleName) irc.error('No module %s exists.' % moduleName)
else: else:
if hasattr(newmodule, funcName): if hasattr(newmodule, funcName):
f = getattr(newmodule, funcName) f = getattr(newmodule, funcName)
if hasattr(f, '__doc__') and f.__doc__: if hasattr(f, '__doc__') and f.__doc__:
s = normalize(f.__doc__) s = normalize(f.__doc__)
irc.reply(msg, s) irc.reply(s)
else: else:
irc.error(msg, '%s has no documentation.' % name) irc.error('%s has no documentation.' % name)
else: else:
s = '%s has no function %s' % (moduleName, funcName) s = '%s has no function %s' % (moduleName, funcName)
irc.error(msg, s) irc.error(s)
else: else:
if name in sys.modules: if name in sys.modules:
newmodule = sys.modules[name] newmodule = sys.modules[name]
if hasattr(newmodule, '__doc__') and newmodule.__doc__: if hasattr(newmodule, '__doc__') and newmodule.__doc__:
irc.reply(msg, normalize(newmodule.__doc__)) irc.reply(normalize(newmodule.__doc__))
else: else:
irc.reply(msg, 'Module %s has no documentation.' % name) irc.reply('Module %s has no documentation.' % name)
elif name in __builtins__: elif name in __builtins__:
f = __builtins__[name] f = __builtins__[name]
if hasattr(f, '__doc__') and f.__doc__: if hasattr(f, '__doc__') and f.__doc__:
irc.reply(msg, normalize(f.__doc__)) irc.reply(normalize(f.__doc__))
else: else:
irc.error(msg, 'That function has no documentation.') irc.error('That function has no documentation.')
else: else:
irc.error(msg, 'No function or module %s exists.' % name) irc.error('No function or module %s exists.' % name)
_these = [str(s) for s in this.s.decode('rot13').splitlines() if s] _these = [str(s) for s in this.s.decode('rot13').splitlines() if s]
_these.pop(0) # Initial line (The Zen of Python...) _these.pop(0) # Initial line (The Zen of Python...)
@ -174,7 +174,7 @@ class Python(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
Returns one of the zen of Python statements. Returns one of the zen of Python statements.
""" """
irc.reply(msg, random.choice(self._these)) irc.reply(random.choice(self._these))
_title = re.compile(r'<b>(Title):</b>&nbsp;(.*)', re.I) _title = re.compile(r'<b>(Title):</b>&nbsp;(.*)', re.I)
_submit = re.compile(r'<b>(Submitter):</b>&nbsp;(.*)', re.I) _submit = re.compile(r'<b>(Submitter):</b>&nbsp;(.*)', re.I)
@ -198,7 +198,7 @@ class Python(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
if m: if m:
resp.append('%s: %s' % self._bold(m.groups())) resp.append('%s: %s' % self._bold(m.groups()))
if resp: if resp:
irc.reply(msg, '; '.join(resp), prefixName = False) irc.reply('; '.join(resp), prefixName = False)
aspnRecipes = privmsgs.urlSnarfer(aspnRecipes) aspnRecipes = privmsgs.urlSnarfer(aspnRecipes)

View File

@ -156,14 +156,14 @@ class QuoteGrabs(plugins.ChannelDBHandler,
channel = privmsgs.getChannel(msg, args) channel = privmsgs.getChannel(msg, args)
nick = privmsgs.getArgs(args) nick = privmsgs.getArgs(args)
if nick == msg.nick: if nick == msg.nick:
irc.error(msg, 'You can\'t quote grab yourself.') irc.error('You can\'t quote grab yourself.')
return return
for m in reviter(irc.state.history): for m in reviter(irc.state.history):
if m.command == 'PRIVMSG' and ircutils.nickEqual(m.nick, nick): if m.command == 'PRIVMSG' and ircutils.nickEqual(m.nick, nick):
self._grab(irc, m, msg.prefix) self._grab(irc, m, msg.prefix)
irc.replySuccess(msg) irc.replySuccess()
return return
irc.error(msg, 'I couldn\'t find a proper message to grab.') irc.error('I couldn\'t find a proper message to grab.')
def quote(self, irc, msg, args): def quote(self, irc, msg, args):
"""[<channel>] <nick> """[<channel>] <nick>
@ -179,10 +179,10 @@ class QuoteGrabs(plugins.ChannelDBHandler,
WHERE nickeq(nick, %s) WHERE nickeq(nick, %s)
ORDER BY id DESC LIMIT 1""", nick) ORDER BY id DESC LIMIT 1""", nick)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg,'I couldn\'t find a matching quotegrab for %s'%nick) irc.error('I couldn\'t find a matching quotegrab for %s'%nick)
else: else:
text = cursor.fetchone()[0] text = cursor.fetchone()[0]
irc.reply(msg, text) irc.reply(text)
def list(self, irc, msg, args): def list(self, irc, msg, args):
"""<nick> """<nick>
@ -199,7 +199,7 @@ class QuoteGrabs(plugins.ChannelDBHandler,
WHERE nick=%s WHERE nick=%s
ORDER BY id ASC""", nick) ORDER BY id ASC""", nick)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'I couldn\'t find any quotegrabs for %s' % nick) irc.error('I couldn\'t find any quotegrabs for %s' % nick)
else: else:
l = [] l = []
for (id, quote) in cursor.fetchall(): for (id, quote) in cursor.fetchall():
@ -207,7 +207,7 @@ class QuoteGrabs(plugins.ChannelDBHandler,
quote = quote.replace('<%s> ' % nick, '', 1) quote = quote.replace('<%s> ' % nick, '', 1)
item_str = utils.ellipsisify('#%s: %s' % (id, quote), 50) item_str = utils.ellipsisify('#%s: %s' % (id, quote), 50)
l.append(item_str) l.append(item_str)
irc.reply(msg, utils.commaAndify(l)) irc.reply(utils.commaAndify(l))
def randomquote(self, irc, msg, args): def randomquote(self, irc, msg, args):
"""[<nick>] """[<nick>]
@ -228,13 +228,13 @@ class QuoteGrabs(plugins.ChannelDBHandler,
ORDER BY random() LIMIT 1""") ORDER BY random() LIMIT 1""")
if cursor.rowcount == 0: if cursor.rowcount == 0:
if nick: if nick:
irc.error(msg, 'Couldn\'t get a random quote for that nick.') irc.error('Couldn\'t get a random quote for that nick.')
else: else:
irc.error(msg, 'Couldn\'t get a random quote. Are there any' irc.error('Couldn\'t get a random quote. Are there any'
'grabbed quotes in the database?') 'grabbed quotes in the database?')
return return
quote = cursor.fetchone()[0] quote = cursor.fetchone()[0]
irc.reply(msg, quote) irc.reply(quote)
def get(self, irc, msg, args): def get(self, irc, msg, args):
"""<id> """<id>
@ -245,7 +245,7 @@ class QuoteGrabs(plugins.ChannelDBHandler,
try: try:
id = int(id) id = int(id)
except ValueError: except ValueError:
irc.error(msg, '%r does not appear to be a valid quotegrab id'%id) irc.error('%r does not appear to be a valid quotegrab id'%id)
return return
channel = privmsgs.getChannel(msg, args) channel = privmsgs.getChannel(msg, args)
db = self.getDb(channel) db = self.getDb(channel)
@ -253,12 +253,12 @@ class QuoteGrabs(plugins.ChannelDBHandler,
cursor.execute("""SELECT quote, hostmask, added_at cursor.execute("""SELECT quote, hostmask, added_at
FROM quotegrabs WHERE id = %s""", id) FROM quotegrabs WHERE id = %s""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No quotegrab for id %r' % id) irc.error('No quotegrab for id %r' % id)
return return
quote, hostmask, timestamp = cursor.fetchone() quote, hostmask, timestamp = cursor.fetchone()
time_str = time.strftime(conf.humanTimestampFormat, time_str = time.strftime(conf.humanTimestampFormat,
time.localtime(float(timestamp))) time.localtime(float(timestamp)))
irc.reply(msg, '%s (Said by: %s on %s)' % (quote, hostmask, time_str)) irc.reply('%s (Said by: %s on %s)' % (quote, hostmask, time_str))
Class = QuoteGrabs Class = QuoteGrabs

View File

@ -94,7 +94,7 @@ class Quotes(plugins.ChannelDBHandler, callbacks.Privmsg):
WHERE added_by=%s AND added_at=%s AND quote=%s""" WHERE added_by=%s AND added_at=%s AND quote=%s"""
cursor.execute(sql, msg.nick, quotetime, quote) cursor.execute(sql, msg.nick, quotetime, quote)
quoteid = cursor.fetchone()[0] quoteid = cursor.fetchone()[0]
irc.reply(msg, '%s (Quote #%s added)' % (conf.replySuccess, quoteid)) irc.reply('%s (Quote #%s added)' % (conf.replySuccess, quoteid))
def num(self, irc, msg, args): def num(self, irc, msg, args):
"""[<channel>] """[<channel>]
@ -112,7 +112,7 @@ class Quotes(plugins.ChannelDBHandler, callbacks.Privmsg):
maxid = 0 maxid = 0
s = 'There %s %s in my database.' % \ s = 'There %s %s in my database.' % \
(utils.be(maxid), utils.nItems('quote', maxid)) (utils.be(maxid), utils.nItems('quote', maxid))
irc.reply(msg, s) irc.reply(s)
def get(self, irc, msg, args): def get(self, irc, msg, args):
"""[<channel>] --{id,regexp,from,with}=<value> ] """[<channel>] --{id,regexp,from,with}=<value> ]
@ -137,7 +137,7 @@ class Quotes(plugins.ChannelDBHandler, callbacks.Privmsg):
argument = int(argument) argument = int(argument)
criteria.append('id=%s' % argument) criteria.append('id=%s' % argument)
except ValueError: except ValueError:
irc.error(msg, '--id value must be an integer.') irc.error('--id value must be an integer.')
return return
elif option == 'with': elif option == 'with':
criteria.append('quote LIKE %s') criteria.append('quote LIKE %s')
@ -152,7 +152,7 @@ class Quotes(plugins.ChannelDBHandler, callbacks.Privmsg):
try: try:
r = re.compile(argument, re.I) r = re.compile(argument, re.I)
except re.error, e: except re.error, e:
irc.error(msg, str(e)) irc.error(str(e))
return return
def p(s): def p(s):
return int(bool(r.search(s))) return int(bool(r.search(s)))
@ -172,12 +172,12 @@ class Quotes(plugins.ChannelDBHandler, callbacks.Privmsg):
cursor = db.cursor() cursor = db.cursor()
cursor.execute(sql, *formats) cursor.execute(sql, *formats)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'No quotes matched that criteria.') irc.reply('No quotes matched that criteria.')
elif cursor.rowcount == 1: elif cursor.rowcount == 1:
(id, quote) = cursor.fetchone() (id, quote) = cursor.fetchone()
irc.reply(msg, '#%s: %s' % (id, quote)) irc.reply('#%s: %s' % (id, quote))
elif cursor.rowcount > 10: elif cursor.rowcount > 10:
irc.reply(msg, 'More than 10 quotes matched your criteria. ' irc.reply('More than 10 quotes matched your criteria. '
'Please narrow your query.') 'Please narrow your query.')
else: else:
results = cursor.fetchall() results = cursor.fetchall()
@ -185,7 +185,7 @@ class Quotes(plugins.ChannelDBHandler, callbacks.Privmsg):
for (id, quote) in results: for (id, quote) in results:
s = '#%s: "%s..."' % (id, quote[:30]) s = '#%s: "%s..."' % (id, quote[:30])
idsWithSnippets.append(s) idsWithSnippets.append(s)
irc.reply(msg, utils.commaAndify(idsWithSnippets)) irc.reply(utils.commaAndify(idsWithSnippets))
### FIXME: we need to remove those predicates from the database. ### FIXME: we need to remove those predicates from the database.
def random(self, irc, msg, args): def random(self, irc, msg, args):
@ -201,7 +201,7 @@ class Quotes(plugins.ChannelDBHandler, callbacks.Privmsg):
ORDER BY random() ORDER BY random()
LIMIT 1""") LIMIT 1""")
if cursor.rowcount != 1: if cursor.rowcount != 1:
irc.error(msg, 'It seems that quote database is empty.') irc.error('It seems that quote database is empty.')
return return
(id,) = cursor.fetchone() (id,) = cursor.fetchone()
self.get(irc, msg, [channel, '--id', str(id)]) self.get(irc, msg, [channel, '--id', str(id)])
@ -222,10 +222,10 @@ class Quotes(plugins.ChannelDBHandler, callbacks.Privmsg):
(id, added_by, added_at, quote) = cursor.fetchone() (id, added_by, added_at, quote) = cursor.fetchone()
timestamp = time.strftime(conf.humanTimestampFormat, timestamp = time.strftime(conf.humanTimestampFormat,
time.localtime(int(added_at))) time.localtime(int(added_at)))
irc.reply(msg, 'Quote %r added by %s at %s.' % \ irc.reply('Quote %r added by %s at %s.' % \
(quote, added_by, timestamp)) (quote, added_by, timestamp))
else: else:
irc.error(msg, 'There isn\'t a quote with that id.') irc.error('There isn\'t a quote with that id.')
def remove(self, irc, msg, args): def remove(self, irc, msg, args):
"""[<channel>] <id> """[<channel>] <id>
@ -241,11 +241,11 @@ class Quotes(plugins.ChannelDBHandler, callbacks.Privmsg):
if ircdb.checkCapability(msg.prefix, capability): if ircdb.checkCapability(msg.prefix, capability):
cursor.execute("""DELETE FROM quotes WHERE id=%s""", id) cursor.execute("""DELETE FROM quotes WHERE id=%s""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'There was no such quote.') irc.error('There was no such quote.')
else: else:
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, conf.replyNoCapability % capability) irc.error(conf.replyNoCapability % capability)
Class = Quotes Class = Quotes

View File

@ -165,7 +165,7 @@ class RSS(callbacks.Privmsg, configurable.Mixin):
name = callbacks.canonicalName(name) name = callbacks.canonicalName(name)
if hasattr(self, name): if hasattr(self, name):
s = 'I already have a command in this plugin named %s' % name s = 'I already have a command in this plugin named %s' % name
irc.error(msg, s) irc.error(s)
return return
def f(self, irc, msg, args): def f(self, irc, msg, args):
args.insert(0, url) args.insert(0, url)
@ -176,7 +176,7 @@ class RSS(callbacks.Privmsg, configurable.Mixin):
f.url = url # Used by __call__. f.url = url # Used by __call__.
self.feedNames.add(name) self.feedNames.add(name)
setattr(self.__class__, name, f) setattr(self.__class__, name, f)
irc.replySuccess(msg) irc.replySuccess()
def remove(self, irc, msg, args): def remove(self, irc, msg, args):
"""<name> """<name>
@ -187,10 +187,10 @@ class RSS(callbacks.Privmsg, configurable.Mixin):
name = privmsgs.getArgs(args) name = privmsgs.getArgs(args)
name = callbacks.canonicalName(name) name = callbacks.canonicalName(name)
if name not in self.feedNames: if name not in self.feedNames:
irc.error(msg, 'That\'s not a valid RSS feed command name.') irc.error('That\'s not a valid RSS feed command name.')
return return
delattr(self.__class__, name) delattr(self.__class__, name)
irc.replySuccess(msg) irc.replySuccess()
def rss(self, irc, msg, args): def rss(self, irc, msg, args):
"""<url> """<url>
@ -205,11 +205,11 @@ class RSS(callbacks.Privmsg, configurable.Mixin):
channel = None channel = None
headlines = self.getHeadlines(feed) headlines = self.getHeadlines(feed)
if not headlines: if not headlines:
irc.error(msg, 'Couldn\'t get RSS feed') irc.error('Couldn\'t get RSS feed')
return return
headlines = imap(utils.htmlToText, headlines) headlines = imap(utils.htmlToText, headlines)
sep = self.configurables.get('headline-separator', channel) sep = self.configurables.get('headline-separator', channel)
irc.reply(msg, sep.join(headlines)) irc.reply(sep.join(headlines))
def info(self, irc, msg, args): def info(self, irc, msg, args):
"""<url> """<url>
@ -221,7 +221,7 @@ class RSS(callbacks.Privmsg, configurable.Mixin):
feed = self.getFeed(url) feed = self.getFeed(url)
info = feed['channel'] info = feed['channel']
if not info: if not info:
irc.error(msg, 'I couldn\'t retrieve that RSS feed.') irc.error('I couldn\'t retrieve that RSS feed.')
return return
# check the 'modified' key, if it's there, convert it here first # check the 'modified' key, if it's there, convert it here first
if 'modified' in feed: if 'modified' in feed:
@ -237,7 +237,7 @@ class RSS(callbacks.Privmsg, configurable.Mixin):
info.get('link', 'unavailable').strip(), info.get('link', 'unavailable').strip(),
info.get('description', 'unavailable').strip(), info.get('description', 'unavailable').strip(),
when) when)
irc.reply(msg, ' '.join(response.split())) irc.reply(' '.join(response.split()))
Class = RSS Class = RSS

View File

@ -174,7 +174,7 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
self.ircstates[realIrc] = irclib.IrcState() self.ircstates[realIrc] = irclib.IrcState()
self.lastmsg[realIrc] = ircmsgs.ping('this is just a fake message') self.lastmsg[realIrc] = ircmsgs.ping('this is just a fake message')
self.started = True self.started = True
irc.replySuccess(msg) irc.replySuccess()
start = privmsgs.checkCapability(start, 'owner') start = privmsgs.checkCapability(start, 'owner')
def connect(self, irc, msg, args): def connect(self, irc, msg, args):
@ -185,7 +185,7 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
that network to other networks. that network to other networks.
""" """
if not self.started: if not self.started:
irc.error(msg, 'You must use the start command first.') irc.error('You must use the start command first.')
return return
abbreviation, server = privmsgs.getArgs(args, required=2) abbreviation, server = privmsgs.getArgs(args, required=2)
realIrc = self._getRealIrc(irc) realIrc = self._getRealIrc(irc)
@ -202,7 +202,7 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
self.abbreviations[newIrc] = abbreviation self.abbreviations[newIrc] = abbreviation
self.ircstates[newIrc] = irclib.IrcState() self.ircstates[newIrc] = irclib.IrcState()
self.lastmsg[newIrc] = ircmsgs.ping('this is just a fake message') self.lastmsg[newIrc] = ircmsgs.ping('this is just a fake message')
irc.replySuccess(msg) irc.replySuccess()
connect = privmsgs.checkCapability(connect, 'owner') connect = privmsgs.checkCapability(connect, 'owner')
def disconnect(self, irc, msg, args): def disconnect(self, irc, msg, args):
@ -212,7 +212,7 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
the network abbreviation <network>. the network abbreviation <network>.
""" """
if not self.started: if not self.started:
irc.error(msg, 'You must use the start command first.') irc.error('You must use the start command first.')
return return
network = privmsgs.getArgs(args) network = privmsgs.getArgs(args)
otherIrc = self.ircs[network] otherIrc = self.ircs[network]
@ -220,7 +220,7 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
world.ircs.remove(otherIrc) world.ircs.remove(otherIrc)
del self.ircs[network] del self.ircs[network]
del self.abbreviations[otherIrc] del self.abbreviations[otherIrc]
irc.replySuccess(msg) irc.replySuccess()
disconnect = privmsgs.checkCapability(disconnect, 'owner') disconnect = privmsgs.checkCapability(disconnect, 'owner')
def join(self, irc, msg, args): def join(self, irc, msg, args):
@ -233,17 +233,17 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
channels. channels.
""" """
if not self.started: if not self.started:
irc.error(msg, 'You must use the start command first.') irc.error('You must use the start command first.')
return return
channel = privmsgs.getArgs(args) channel = privmsgs.getArgs(args)
if not ircutils.isChannel(channel): if not ircutils.isChannel(channel):
irc.error(msg, '%r is not a valid channel.' % channel) irc.error('%r is not a valid channel.' % channel)
return return
self.channels.add(ircutils.toLower(channel)) self.channels.add(ircutils.toLower(channel))
for otherIrc in self.ircs.itervalues(): for otherIrc in self.ircs.itervalues():
if channel not in otherIrc.state.channels: if channel not in otherIrc.state.channels:
otherIrc.queueMsg(ircmsgs.join(channel)) otherIrc.queueMsg(ircmsgs.join(channel))
irc.replySuccess(msg) irc.replySuccess()
join = privmsgs.checkCapability(join, 'owner') join = privmsgs.checkCapability(join, 'owner')
def part(self, irc, msg, args): def part(self, irc, msg, args):
@ -254,17 +254,17 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
channel. channel.
""" """
if not self.started: if not self.started:
irc.error(msg, 'You must use the start command first.') irc.error('You must use the start command first.')
return return
channel = privmsgs.getArgs(args) channel = privmsgs.getArgs(args)
if not ircutils.isChannel(channel): if not ircutils.isChannel(channel):
irc.error(msg, '%r is not a valid channel.' % channel) irc.error('%r is not a valid channel.' % channel)
return return
self.channels.remove(ircutils.toLower(channel)) self.channels.remove(ircutils.toLower(channel))
for otherIrc in self.ircs.itervalues(): for otherIrc in self.ircs.itervalues():
if channel in otherIrc.state.channels: if channel in otherIrc.state.channels:
otherIrc.queueMsg(ircmsgs.part(channel)) otherIrc.queueMsg(ircmsgs.part(channel))
irc.replySuccess(msg) irc.replySuccess()
part = privmsgs.checkCapability(part, 'owner') part = privmsgs.checkCapability(part, 'owner')
def command(self, irc, msg, args): def command(self, irc, msg, args):
@ -273,7 +273,7 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
Gives the bot <command> (with its associated <arg>s) on <network>. Gives the bot <command> (with its associated <arg>s) on <network>.
""" """
if not self.started: if not self.started:
irc.error(msg, 'You must use the start command first.') irc.error('You must use the start command first.')
return return
if len(args) < 2: if len(args) < 2:
raise callbacks.ArgumentError raise callbacks.ArgumentError
@ -281,12 +281,12 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
try: try:
otherIrc = self.ircs[network] otherIrc = self.ircs[network]
except KeyError: except KeyError:
irc.error(msg, 'I\'m not currently on %s.' % network) irc.error('I\'m not currently on %s.' % network)
return return
Owner = irc.getCallback('Owner') Owner = irc.getCallback('Owner')
Owner.disambiguate(irc, args) Owner.disambiguate(irc, args)
self.Proxy(otherIrc, msg, args) self.Proxy(otherIrc, msg, args)
irc.replySuccess(msg) irc.replySuccess()
command = privmsgs.checkCapability(command, 'admin') command = privmsgs.checkCapability(command, 'admin')
def say(self, irc, msg, args): def say(self, irc, msg, args):
@ -296,7 +296,7 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
on <network>. on <network>.
""" """
if not self.started: if not self.started:
irc.error(msg, 'You must use the start command first.') irc.error('You must use the start command first.')
return return
if not args: if not args:
raise callbacks.ArgumentError raise callbacks.ArgumentError
@ -304,10 +304,10 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
channel = privmsgs.getChannel(msg, args) channel = privmsgs.getChannel(msg, args)
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
if network not in self.ircs: if network not in self.ircs:
irc.error(msg, 'I\'m not currently on %s.' % network) irc.error('I\'m not currently on %s.' % network)
return return
if channel not in self.channels: if channel not in self.channels:
irc.error(msg, 'I\'m not currently relaying to %s.' % channel) irc.error('I\'m not currently relaying to %s.' % channel)
return return
self.ircs[network].queueMsg(ircmsgs.privmsg(channel, text)) self.ircs[network].queueMsg(ircmsgs.privmsg(channel, text))
say = privmsgs.checkCapability(say, 'admin') say = privmsgs.checkCapability(say, 'admin')
@ -320,12 +320,12 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
the various networks the bot is connected to. the various networks the bot is connected to.
""" """
if not self.started: if not self.started:
irc.error(msg, 'You must use the start command first.') irc.error('You must use the start command first.')
return return
realIrc = self._getRealIrc(irc) realIrc = self._getRealIrc(irc)
channel = privmsgs.getChannel(msg, args) channel = privmsgs.getChannel(msg, args)
if channel not in self.channels: if channel not in self.channels:
irc.error(msg, 'I\'m not relaying %s.' % channel) irc.error('I\'m not relaying %s.' % channel)
return return
users = [] users = []
for (abbreviation, otherIrc) in self.ircs.iteritems(): for (abbreviation, otherIrc) in self.ircs.iteritems():
@ -338,7 +338,7 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
Channel = otherIrc.state.channels[channel] Channel = otherIrc.state.channels[channel]
except KeyError: except KeyError:
s = 'Somehow I\'m not in %s on %s.'% (channel,abbreviation) s = 'Somehow I\'m not in %s on %s.'% (channel,abbreviation)
irc.error(msg, s) irc.error(s)
return return
numUsers = 0 numUsers = 0
for s in Channel.users: for s in Channel.users:
@ -363,7 +363,7 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
users.append('%s (%s): %s' % users.append('%s (%s): %s' %
(ircutils.bold(abbreviation), numUsers, usersS)) (ircutils.bold(abbreviation), numUsers, usersS))
users.sort() users.sort()
irc.reply(msg, '; '.join(users)) irc.reply('; '.join(users))
def whois(self, irc, msg, args): def whois(self, irc, msg, args):
"""<nick>@<network> """<nick>@<network>
@ -371,14 +371,14 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
Returns the WHOIS response <network> gives for <nick>. Returns the WHOIS response <network> gives for <nick>.
""" """
if not self.started: if not self.started:
irc.error(msg, 'You must use the start command first.') irc.error('You must use the start command first.')
return return
nickAtNetwork = privmsgs.getArgs(args) nickAtNetwork = privmsgs.getArgs(args)
realIrc = self._getRealIrc(irc) realIrc = self._getRealIrc(irc)
try: try:
(nick, network) = nickAtNetwork.split('@', 1) (nick, network) = nickAtNetwork.split('@', 1)
if not ircutils.isNick(nick): if not ircutils.isNick(nick):
irc.error(msg, '%s is not an IRC nick.' % nick) irc.error('%s is not an IRC nick.' % nick)
return return
nick = ircutils.toLower(nick) nick = ircutils.toLower(nick)
except ValueError: except ValueError:
@ -392,7 +392,7 @@ class Relay(callbacks.Privmsg, configurable.Mixin):
else: else:
raise callbacks.ArgumentError raise callbacks.ArgumentError
if network not in self.ircs: if network not in self.ircs:
irc.error(msg, 'I\'m not on that network.') irc.error('I\'m not on that network.')
return return
otherIrc = self.ircs[network] otherIrc = self.ircs[network]
otherIrc.queueMsg(ircmsgs.whois(nick, nick)) otherIrc.queueMsg(ircmsgs.whois(nick, nick))

View File

@ -84,12 +84,12 @@ class Scheduler(callbacks.Privmsg):
try: try:
seconds = int(seconds) seconds = int(seconds)
except ValueError: except ValueError:
irc.error(msg, 'Invalid seconds value: %r' % seconds) irc.error('Invalid seconds value: %r' % seconds)
return return
f = self._makeCommandFunction(irc, msg, command) f = self._makeCommandFunction(irc, msg, command)
id = schedule.addEvent(f, time.time() + seconds) id = schedule.addEvent(f, time.time() + seconds)
self.events[str(id)] = command self.events[str(id)] = command
irc.reply(msg, '%s Event #%s added.' % (conf.replySuccess, id)) irc.reply('%s Event #%s added.' % (conf.replySuccess, id))
def remove(self, irc, msg, args): def remove(self, irc, msg, args):
"""<id> """<id>
@ -106,11 +106,11 @@ class Scheduler(callbacks.Privmsg):
pass pass
try: try:
schedule.removeEvent(id) schedule.removeEvent(id)
irc.reply(msg, conf.replySuccess) irc.reply(conf.replySuccess)
except KeyError: except KeyError:
irc.error(msg, 'Invalid event id.') irc.error('Invalid event id.')
else: else:
irc.error(msg, 'Invalid event id.') irc.error('Invalid event id.')
def repeat(self, irc, msg, args): def repeat(self, irc, msg, args):
"""<name> <seconds> <command> """<name> <seconds> <command>
@ -125,14 +125,14 @@ class Scheduler(callbacks.Privmsg):
try: try:
seconds = int(seconds) seconds = int(seconds)
except ValueError: except ValueError:
irc.error(msg, 'Invalid seconds: %r' % seconds) irc.error('Invalid seconds: %r' % seconds)
return return
self.events[name] = command self.events[name] = command
f = self._makeCommandFunction(irc, msg, command) f = self._makeCommandFunction(irc, msg, command)
id = schedule.addPeriodicEvent(f, seconds, name) id = schedule.addPeriodicEvent(f, seconds, name)
assert id == name assert id == name
# We don't reply because the command runs immediately. # We don't reply because the command runs immediately.
# irc.replySuccess(msg) # irc.replySuccess()
def list(self, irc, msg, args): def list(self, irc, msg, args):
"""takes no arguments. """takes no arguments.
@ -144,9 +144,9 @@ class Scheduler(callbacks.Privmsg):
L.sort() L.sort()
for (i, (name, command)) in enumerate(L): for (i, (name, command)) in enumerate(L):
L[i] = '%s: %s' % (name, utils.dqrepr(command)) L[i] = '%s: %s' % (name, utils.dqrepr(command))
irc.reply(msg, utils.commaAndify(L)) irc.reply(utils.commaAndify(L))
else: else:
irc.reply(msg, 'There are currently no scheduled commands.') irc.reply('There are currently no scheduled commands.')
Class = Scheduler Class = Scheduler

View File

@ -82,12 +82,12 @@ class Services(privmsgs.CapabilityCheckingPrivmsg):
ChanServ, respectively, They default to NickServ and ChanServ. ChanServ, respectively, They default to NickServ and ChanServ.
""" """
if ircutils.isChannel(msg.args[0]): if ircutils.isChannel(msg.args[0]):
irc.error(msg, conf.replyRequiresPrivacy) irc.error(conf.replyRequiresPrivacy)
return return
(self.nick, self.password, nickserv, chanserv) = \ (self.nick, self.password, nickserv, chanserv) = \
privmsgs.getArgs(args, required=2, optional=2) privmsgs.getArgs(args, required=2, optional=2)
if not self.nick: if not self.nick:
irc.error(msg, 'The registered nick cannot be blank.') irc.error('The registered nick cannot be blank.')
return return
self.nick = ircutils.IrcString(self.nick) self.nick = ircutils.IrcString(self.nick)
self.nickserv = ircutils.IrcString(nickserv or 'NickServ') self.nickserv = ircutils.IrcString(nickserv or 'NickServ')
@ -95,7 +95,7 @@ class Services(privmsgs.CapabilityCheckingPrivmsg):
self._ghosted = re.compile('(Ghost|%s).*killed' % self.nick, re.I) self._ghosted = re.compile('(Ghost|%s).*killed' % self.nick, re.I)
self.sentGhost = False self.sentGhost = False
self.log.info('Services started.') self.log.info('Services started.')
irc.replySuccess(msg) irc.replySuccess()
def _doIdentify(self, irc): def _doIdentify(self, irc):
assert self.nickserv, 'Nickserv must not be empty.' assert self.nickserv, 'Nickserv must not be empty.'
@ -173,11 +173,11 @@ class Services(privmsgs.CapabilityCheckingPrivmsg):
channel = privmsgs.getChannel(msg, args) channel = privmsgs.getChannel(msg, args)
try: try:
if irc.nick in irc.state.channels[channel].ops: if irc.nick in irc.state.channels[channel].ops:
irc.error(msg, 'I\'ve already got ops in %sx' % channel) irc.error('I\'ve already got ops in %sx' % channel)
else: else:
irc.sendMsg(ircmsgs.privmsg(self.chanserv, 'op %s' % channel)) irc.sendMsg(ircmsgs.privmsg(self.chanserv, 'op %s' % channel))
except KeyError: except KeyError:
irc.error(msg, 'I\'m not in %s.' % channel) irc.error('I\'m not in %s.' % channel)
def identify(self, irc, msg, args): def identify(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -186,10 +186,10 @@ class Services(privmsgs.CapabilityCheckingPrivmsg):
""" """
if self.nickserv: if self.nickserv:
self._doIdentify(irc) self._doIdentify(irc)
irc.replySuccess(msg) irc.replySuccess()
else: else:
s = 'This plugin must first be started via the start command.' s = 'This plugin must first be started via the start command.'
irc.error(msg, s) irc.error(s)

View File

@ -178,12 +178,12 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
head = '%s <http://sourceforge.net%s>' head = '%s <http://sourceforge.net%s>'
resp = [head % match for match in self._formatResp(text,num)] resp = [head % match for match in self._formatResp(text,num)]
if resp: if resp:
irc.reply(msg, resp[0]) irc.reply(resp[0])
return return
irc.error(msg, 'No Trackers were found. (%s)' % irc.error('No Trackers were found. (%s)' %
conf.replyPossibleBug) conf.replyPossibleBug)
except webutils.WebError, e: except webutils.WebError, e:
irc.error(msg, e.msg()) irc.error(e.msg())
_bugLink = re.compile(r'"([^"]+)">Bugs') _bugLink = re.compile(r'"([^"]+)">Bugs')
def bugs(self, irc, msg, args): def bugs(self, irc, msg, args):
@ -195,7 +195,7 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
project = privmsgs.getArgs(args, required=0, optional=1) project = privmsgs.getArgs(args, required=0, optional=1)
try: try:
int(project) int(project)
irc.error(msg, 'Use the bug command to get information about a '\ irc.error('Use the bug command to get information about a '\
'specific bug.') 'specific bug.')
return return
except ValueError: except ValueError:
@ -207,9 +207,9 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
try: try:
url = self._getTrackerURL(project, self._bugLink) url = self._getTrackerURL(project, self._bugLink)
except TrackerError, e: except TrackerError, e:
irc.error(msg, '%s. Can\'t find the Bugs link.' % e) irc.error('%s. Can\'t find the Bugs link.' % e)
return return
irc.reply(msg, self._getTrackerList(url)) irc.reply(self._getTrackerList(url))
def bug(self, irc, msg, args): def bug(self, irc, msg, args):
"""[<project>] <num> """[<project>] <num>
@ -223,7 +223,7 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
try: try:
int(project) int(project)
except ValueError: except ValueError:
irc.error(msg, '"%s" is not a proper bugnumber.' % project) irc.error('"%s" is not a proper bugnumber.' % project)
return return
bugnum = project bugnum = project
project = self.configurables.get('default-project', msg.args[0]) project = self.configurables.get('default-project', msg.args[0])
@ -232,7 +232,7 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
try: try:
url = self._getTrackerURL(project, self._bugLink) url = self._getTrackerURL(project, self._bugLink)
except TrackerError, e: except TrackerError, e:
irc.error(msg, '%s. Can\'t find the Bugs link.' % e) irc.error('%s. Can\'t find the Bugs link.' % e)
return return
self._getTrackerInfo(irc, msg, url, bugnum) self._getTrackerInfo(irc, msg, url, bugnum)
@ -246,7 +246,7 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
project = privmsgs.getArgs(args, required=0, optional=1) project = privmsgs.getArgs(args, required=0, optional=1)
try: try:
int(project) int(project)
irc.error(msg, 'Use the rfe command to get information about a '\ irc.error('Use the rfe command to get information about a '\
'specific rfe.') 'specific rfe.')
return return
except ValueError: except ValueError:
@ -258,9 +258,9 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
try: try:
url = self._getTrackerURL(project, self._rfeLink) url = self._getTrackerURL(project, self._rfeLink)
except TrackerError, e: except TrackerError, e:
irc.error(msg, '%s. Can\'t find the RFEs link.' % e) irc.error('%s. Can\'t find the RFEs link.' % e)
return return
irc.reply(msg, self._getTrackerList(url)) irc.reply(self._getTrackerList(url))
def rfe(self, irc, msg, args): def rfe(self, irc, msg, args):
"""[<project>] <num> """[<project>] <num>
@ -274,7 +274,7 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
try: try:
int(project) int(project)
except ValueError: except ValueError:
irc.error(msg, '"%s" is not a proper rfenumber.' % project) irc.error('"%s" is not a proper rfenumber.' % project)
return return
rfenum = project rfenum = project
project = self.configurables.get('default-project', msg.args[0]) project = self.configurables.get('default-project', msg.args[0])
@ -283,7 +283,7 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
try: try:
url = self._getTrackerURL(project, self._rfeLink) url = self._getTrackerURL(project, self._rfeLink)
except TrackerError, e: except TrackerError, e:
irc.error(msg, '%s. Can\'t find the RFEs link.' % e) irc.error('%s. Can\'t find the RFEs link.' % e)
return return
self._getTrackerInfo(irc, msg, url, rfenum) self._getTrackerInfo(irc, msg, url, rfenum)
@ -316,7 +316,7 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, configurable.Mixin):
m = r.search(s) m = r.search(s)
if m: if m:
resp.append('%s: %s' % self._bold(m.groups())) resp.append('%s: %s' % self._bold(m.groups()))
irc.reply(msg, '%s #%s: %s' % (ircutils.bold(linktype), irc.reply('%s #%s: %s' % (ircutils.bold(linktype),
ircutils.bold(num), '; '.join(resp)), prefixName = False) ircutils.bold(num), '; '.join(resp)), prefixName = False)
except webutils.WebError, e: except webutils.WebError, e:
self.log.warning(str(e)) self.log.warning(str(e))

View File

@ -133,7 +133,7 @@ class Status(callbacks.Privmsg):
""" """
L = self.uptimes.top() L = self.uptimes.top()
if not L: if not L:
irc.error(msg, 'I don\'t have enough data to answer that.') irc.error('I don\'t have enough data to answer that.')
return return
def format((started, ended)): def format((started, ended)):
return '%s until %s; up for %s' % \ return '%s until %s; up for %s' % \
@ -142,18 +142,17 @@ class Status(callbacks.Privmsg):
time.strftime(conf.humanTimestampFormat, time.strftime(conf.humanTimestampFormat,
time.localtime(ended)), time.localtime(ended)),
utils.timeElapsed(ended-started)) utils.timeElapsed(ended-started))
irc.reply(msg, utils.commaAndify(imap(format, L))) irc.reply(utils.commaAndify(imap(format, L)))
def net(self, irc, msg, args): def net(self, irc, msg, args):
"""takes no arguments """takes no arguments
Returns some interesting network-related statistics. Returns some interesting network-related statistics.
""" """
irc.reply(msg, irc.reply('I have received %s messages for a total of %s bytes. '
'I have received %s messages for a total of %s bytes. '\ 'I have sent %s messages for a total of %s bytes.' %
'I have sent %s messages for a total of %s bytes.' %\ (self.recvdMsgs, self.recvdBytes,
(self.recvdMsgs, self.recvdBytes, self.sentMsgs, self.sentBytes))
self.sentMsgs, self.sentBytes))
def cpu(self, irc, msg, args): def cpu(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -195,7 +194,7 @@ class Status(callbacks.Privmsg):
response += ' I\'m taking up %s kB of memory.' % mem response += ' I\'m taking up %s kB of memory.' % mem
except Exception: except Exception:
self.log.exception('Uncaught exception in cpu:') self.log.exception('Uncaught exception in cpu:')
irc.reply(msg, response) irc.reply(response)
def cmd(self, irc, msg, args): def cmd(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -216,7 +215,7 @@ class Status(callbacks.Privmsg):
(utils.nItems('command', commands), (utils.nItems('command', commands),
utils.nItems('plugin', callbacksPrivmsg, 'command-based'), utils.nItems('plugin', callbacksPrivmsg, 'command-based'),
utils.nItems('command', world.commandsProcessed)) utils.nItems('command', world.commandsProcessed))
irc.reply(msg, s) irc.reply(s)
def commands(self, irc, msg, args): def commands(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -233,7 +232,7 @@ class Status(callbacks.Privmsg):
commands.add(attr) commands.add(attr)
commands = list(commands) commands = list(commands)
commands.sort() commands.sort()
irc.reply(msg, utils.commaAndify(commands)) irc.reply(utils.commaAndify(commands))
def uptime(self, irc, msg, args): def uptime(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -242,14 +241,14 @@ class Status(callbacks.Privmsg):
""" """
response = 'I have been running for %s.' % \ response = 'I have been running for %s.' % \
utils.timeElapsed(time.time() - world.startedAt) utils.timeElapsed(time.time() - world.startedAt)
irc.reply(msg, response) irc.reply(response)
def server(self, irc, msg, args): def server(self, irc, msg, args):
"""takes no arguments """takes no arguments
Returns the server the bot is on. Returns the server the bot is on.
""" """
irc.reply(msg, irc.server) irc.reply(irc.server)
Class = Status Class = Status

View File

@ -116,7 +116,7 @@ class Todo(callbacks.Privmsg):
try: try:
userid = ircdb.users.getUserId(arg) userid = ircdb.users.getUserId(arg)
except KeyError: except KeyError:
irc.error(msg, irc.error(
'%r is not a valid task id or username' % arg) '%r is not a valid task id or username' % arg)
return return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
@ -125,24 +125,24 @@ class Todo(callbacks.Privmsg):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
cursor.execute("""SELECT id, task FROM todo cursor.execute("""SELECT id, task FROM todo
WHERE userid = %s AND active = 1 WHERE userid = %s AND active = 1
ORDER BY priority, id""", id) ORDER BY priority, id""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'You have no tasks in your todo list.') irc.reply('You have no tasks in your todo list.')
else: else:
L = ['#%s: %s' % (item[0], self._shrink(item[1])) L = ['#%s: %s' % (item[0], self._shrink(item[1]))
for item in cursor.fetchall()] for item in cursor.fetchall()]
irc.reply(msg, utils.commaAndify(L)) irc.reply(utils.commaAndify(L))
else: else:
if userid: if userid:
cursor.execute("""SELECT id, task FROM todo cursor.execute("""SELECT id, task FROM todo
WHERE userid = %s AND active = 1 WHERE userid = %s AND active = 1
ORDER BY priority, id""", userid) ORDER BY priority, id""", userid)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'That user has no todos.') irc.reply('That user has no todos.')
return return
L = ['#%s: %s' % (item[0], self._shrink(item[1])) L = ['#%s: %s' % (item[0], self._shrink(item[1]))
for item in cursor.fetchall()] for item in cursor.fetchall()]
@ -150,12 +150,12 @@ class Todo(callbacks.Privmsg):
s = 'Todo for %s: %s' % (arg, L[0]) s = 'Todo for %s: %s' % (arg, L[0])
else: else:
s = 'Todos for %s: %s' % (arg, utils.commaAndify(L)) s = 'Todos for %s: %s' % (arg, utils.commaAndify(L))
irc.reply(msg, s) irc.reply(s)
else: else:
cursor.execute("""SELECT userid,priority,added_at,task,active cursor.execute("""SELECT userid,priority,added_at,task,active
FROM todo WHERE id = %s""", taskid) FROM todo WHERE id = %s""", taskid)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, '%r is not a valid task id' % taskid) irc.error('%r is not a valid task id' % taskid)
return return
(userid, pri, added_at, task, active) = cursor.fetchone() (userid, pri, added_at, task, active) = cursor.fetchone()
# Construct and return the reply # Construct and return the reply
@ -174,7 +174,7 @@ class Todo(callbacks.Privmsg):
time.localtime(int(added_at))) time.localtime(int(added_at)))
s = "%s todo for %s: %s (Added at %s)" % \ s = "%s todo for %s: %s (Added at %s)" % \
(active, name, task, added_at) (active, name, task, added_at)
irc.reply(msg, s) irc.reply(s)
def add(self, irc, msg, args): def add(self, irc, msg, args):
"""[--priority=<num>] <text> """[--priority=<num>] <text>
@ -186,7 +186,7 @@ class Todo(callbacks.Privmsg):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
(optlist, rest) = getopt.getopt(args, '', ['priority=']) (optlist, rest) = getopt.getopt(args, '', ['priority='])
priority = 0 priority = 0
@ -195,7 +195,7 @@ class Todo(callbacks.Privmsg):
try: try:
priority = int(arg) priority = int(arg)
except ValueError, e: except ValueError, e:
irc.error(msg, '%r is an invalid priority' % arg) irc.error('%r is an invalid priority' % arg)
return return
text = privmsgs.getArgs(rest) text = privmsgs.getArgs(rest)
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
@ -208,7 +208,7 @@ class Todo(callbacks.Privmsg):
cursor.execute("""SELECT id FROM todo cursor.execute("""SELECT id FROM todo
WHERE added_at=%s AND userid=%s""", now, id) WHERE added_at=%s AND userid=%s""", now, id)
todoId = cursor.fetchone()[0] todoId = cursor.fetchone()[0]
irc.reply(msg, '%s (Todo #%s added)' % (conf.replySuccess, todoId)) irc.reply('%s (Todo #%s added)' % (conf.replySuccess, todoId))
def remove(self, irc, msg, args): def remove(self, irc, msg, args):
"""<task id> [<task id> ...] """<task id> [<task id> ...]
@ -218,7 +218,7 @@ class Todo(callbacks.Privmsg):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
taskids = privmsgs.getArgs(args) taskids = privmsgs.getArgs(args)
tasks = taskids.split() tasks = taskids.split()
@ -235,7 +235,7 @@ class Todo(callbacks.Privmsg):
invalid.append(taskid) invalid.append(taskid)
#print 'Invalid tasks: %s' % repr(invalid) #print 'Invalid tasks: %s' % repr(invalid)
if invalid: if invalid:
irc.error(msg, 'No tasks were removed because the following '\ irc.error('No tasks were removed because the following '\
'tasks could not be removed: %s' % \ 'tasks could not be removed: %s' % \
utils.commaAndify(invalid)) utils.commaAndify(invalid))
else: else:
@ -243,7 +243,7 @@ class Todo(callbacks.Privmsg):
cursor.execute("""UPDATE todo SET active = 0 WHERE id = %s""", cursor.execute("""UPDATE todo SET active = 0 WHERE id = %s""",
taskid) taskid)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
_sqlTrans = string.maketrans('*?', '%_') _sqlTrans = string.maketrans('*?', '%_')
def search(self, irc, msg, args): def search(self, irc, msg, args):
@ -256,7 +256,7 @@ class Todo(callbacks.Privmsg):
try: try:
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
(optlist, rest) = getopt.getopt(args, '', ['regexp=']) (optlist, rest) = getopt.getopt(args, '', ['regexp='])
if not optlist and not rest: if not optlist and not rest:
@ -271,7 +271,7 @@ class Todo(callbacks.Privmsg):
try: try:
r = utils.perlReToPythonRe(arg) r = utils.perlReToPythonRe(arg)
except ValueError, e: except ValueError, e:
irc.error(msg, '%r is not a valid regular expression' % irc.error('%r is not a valid regular expression' %
arg) arg)
return return
def p(s, r=r): def p(s, r=r):
@ -287,11 +287,11 @@ class Todo(callbacks.Privmsg):
sql = """SELECT id, task FROM todo WHERE %s""" % ' AND '.join(criteria) sql = """SELECT id, task FROM todo WHERE %s""" % ' AND '.join(criteria)
cursor.execute(sql, formats) cursor.execute(sql, formats)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'No tasks matched that query.') irc.reply('No tasks matched that query.')
else: else:
tasks = ['#%s: %s' % (item[0], self._shrink(item[1])) tasks = ['#%s: %s' % (item[0], self._shrink(item[1]))
for item in cursor.fetchall()] for item in cursor.fetchall()]
irc.reply(msg, utils.commaAndify(tasks)) irc.reply(utils.commaAndify(tasks))
def setpriority(self, irc, msg, args): def setpriority(self, irc, msg, args):
"""<id> <priority> """<id> <priority>
@ -301,7 +301,7 @@ class Todo(callbacks.Privmsg):
try: try:
user_id = ircdb.users.getUserId(msg.prefix) user_id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
(id, priority) = privmsgs.getArgs(args, required=2) (id, priority) = privmsgs.getArgs(args, required=2)
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
@ -309,17 +309,17 @@ class Todo(callbacks.Privmsg):
cursor.execute("""SELECT userid, priority FROM todo cursor.execute("""SELECT userid, priority FROM todo
WHERE id = %s AND active = 1""", id) WHERE id = %s AND active = 1""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, 'No note with id %s' % id) irc.error('No note with id %s' % id)
return return
(userid, oldpriority) = cursor.fetchone() (userid, oldpriority) = cursor.fetchone()
if userid != user_id: if userid != user_id:
irc.error(msg, 'Todo #%s does not belong to you.' % id) irc.error('Todo #%s does not belong to you.' % id)
return return
# If we make it here, we're okay # If we make it here, we're okay
cursor.execute("""UPDATE todo SET priority = %s cursor.execute("""UPDATE todo SET priority = %s
WHERE id = %s""", priority, id) WHERE id = %s""", priority, id)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
def change(self, irc, msg, args): def change(self, irc, msg, args):
"""<task id> <regexp> """<task id> <regexp>
@ -329,14 +329,14 @@ class Todo(callbacks.Privmsg):
try: try:
userid = ircdb.users.getUserId(msg.prefix) userid = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
taskid, regexp = privmsgs.getArgs(args, required=2) taskid, regexp = privmsgs.getArgs(args, required=2)
# Check the regexp first, it's easier and doesn't require a db query # Check the regexp first, it's easier and doesn't require a db query
try: try:
replacer = utils.perlReToReplacer(regexp) replacer = utils.perlReToReplacer(regexp)
except ValueError: except ValueError:
irc.error(msg, '%r is not a valid regexp' % regexp) irc.error('%r is not a valid regexp' % regexp)
return return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
@ -344,13 +344,13 @@ class Todo(callbacks.Privmsg):
WHERE userid = %s AND id = %s WHERE userid = %s AND id = %s
AND active = 1""", userid, taskid) AND active = 1""", userid, taskid)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error(msg, '%r is not a valid task id' % taskid) irc.error('%r is not a valid task id' % taskid)
return return
newtext = replacer(cursor.fetchone()[0]) newtext = replacer(cursor.fetchone()[0])
cursor.execute("""UPDATE todo SET task = %s cursor.execute("""UPDATE todo SET task = %s
WHERE id = %s""", newtext, taskid) WHERE id = %s""", newtext, taskid)
db.commit() db.commit()
irc.replySuccess(msg) irc.replySuccess()
Class = Todo Class = Todo

View File

@ -85,7 +85,7 @@ class Topic(callbacks.Privmsg, configurable.Mixin):
separator = self.configurables.get('separator', channel) separator = self.configurables.get('separator', channel)
if separator in topic: if separator in topic:
s = 'You can\'t have %s in your topic' % separator s = 'You can\'t have %s in your topic' % separator
irc.error(msg, s) irc.error(s)
return return
currentTopic = irc.state.getTopic(channel) currentTopic = irc.state.getTopic(channel)
try: try:
@ -109,7 +109,7 @@ class Topic(callbacks.Privmsg, configurable.Mixin):
newtopic = irc.state.getTopic(channel) newtopic = irc.state.getTopic(channel)
topics = self._splitTopic(irc.state.getTopic(channel), channel) topics = self._splitTopic(irc.state.getTopic(channel), channel)
if len(topics) == 0 or len(topics) == 1: if len(topics) == 0 or len(topics) == 1:
irc.error(msg, 'I can\'t shuffle 1 or fewer topics.') irc.error('I can\'t shuffle 1 or fewer topics.')
return return
elif len(topics) == 2: elif len(topics) == 2:
topics.reverse() topics.reverse()
@ -134,10 +134,10 @@ class Topic(callbacks.Privmsg, configurable.Mixin):
topics = self._splitTopic(irc.state.getTopic(channel), channel) topics = self._splitTopic(irc.state.getTopic(channel), channel)
num = len(topics) num = len(topics)
if num == 0 or num == 1: if num == 0 or num == 1:
irc.error(msg, 'I cannot reorder 1 or fewer topics.') irc.error('I cannot reorder 1 or fewer topics.')
return return
if len(args) != num: if len(args) != num:
irc.error(msg, 'All topic numbers must be specified.') irc.error('All topic numbers must be specified.')
return return
order = privmsgs.getArgs(args, required=num) order = privmsgs.getArgs(args, required=num)
if topics: if topics:
@ -147,24 +147,24 @@ class Topic(callbacks.Privmsg, configurable.Mixin):
if p > 0: if p > 0:
order[i] = p - 1 order[i] = p - 1
elif p == 0: elif p == 0:
irc.error(msg, '0 is not a valid topic number.') irc.error('0 is not a valid topic number.')
return return
else: else:
order[i] = num + p order[i] = num + p
except ValueError: except ValueError:
irc.error(msg, 'The positions must be valid integers.') irc.error('The positions must be valid integers.')
return return
if utils.sorted(order) != range(num): if utils.sorted(order) != range(num):
irc.error(msg, 'Duplicate topic numbers cannot be specified.') irc.error('Duplicate topic numbers cannot be specified.')
return return
try: try:
newtopics = [topics[i] for i in order] newtopics = [topics[i] for i in order]
newtopic = self._joinTopic(newtopics, channel) newtopic = self._joinTopic(newtopics, channel)
irc.queueMsg(ircmsgs.topic(channel, newtopic)) irc.queueMsg(ircmsgs.topic(channel, newtopic))
except IndexError: except IndexError:
irc.error(msg, 'An invalid topic number was specified.') irc.error('An invalid topic number was specified.')
else: else:
irc.error(msg, 'There are no topics to reorder.') irc.error('There are no topics to reorder.')
reorder = privmsgs.checkChannelCapability(reorder, 'topic') reorder = privmsgs.checkChannelCapability(reorder, 'topic')
def list(self, irc, msg, args, channel): def list(self, irc, msg, args, channel):
@ -180,7 +180,7 @@ class Topic(callbacks.Privmsg, configurable.Mixin):
(t, _) = self._unformatTopic(t, channel) (t, _) = self._unformatTopic(t, channel)
L.append('%s: %s' % (i+1, utils.ellipsisify(t, 30))) L.append('%s: %s' % (i+1, utils.ellipsisify(t, 30)))
s = utils.commaAndify(L) s = utils.commaAndify(L)
irc.reply(msg, s) irc.reply(s)
list = privmsgs.channel(list) list = privmsgs.channel(list)
def get(self, irc, msg, args, channel): def get(self, irc, msg, args, channel):
@ -196,19 +196,19 @@ class Topic(callbacks.Privmsg, configurable.Mixin):
if number > 0: if number > 0:
number -= 1 number -= 1
elif number == 0: elif number == 0:
irc.error(msg, 'That\'s not a valid topic number.') irc.error('That\'s not a valid topic number.')
return return
except ValueError: except ValueError:
irc.error(msg, 'The argument must be a valid integer.') irc.error('The argument must be a valid integer.')
return return
topics = self._splitTopic(irc.state.getTopic(channel), channel) topics = self._splitTopic(irc.state.getTopic(channel), channel)
if topics: if topics:
try: try:
irc.reply(msg, self._unformatTopic(topics[number], channel)[0]) irc.reply(self._unformatTopic(topics[number], channel)[0])
except IndexError: except IndexError:
irc.error(msg, 'That\'s not a valid topic.') irc.error('That\'s not a valid topic.')
else: else:
irc.error(msg, 'There are no topics to get.') irc.error('There are no topics to get.')
get = privmsgs.channel(get) get = privmsgs.channel(get)
def change(self, irc, msg, args, channel): def change(self, irc, msg, args, channel):
@ -226,33 +226,33 @@ class Topic(callbacks.Privmsg, configurable.Mixin):
if number > 0: if number > 0:
number -= 1 number -= 1
elif number == 0: elif number == 0:
irc.error(msg, 'That\'s not a valid topic number.') irc.error('That\'s not a valid topic number.')
return return
except ValueError: except ValueError:
irc.error(msg, 'The <number> argument must be a number.') irc.error('The <number> argument must be a number.')
return return
try: try:
replacer = utils.perlReToReplacer(regexp) replacer = utils.perlReToReplacer(regexp)
except ValueError, e: except ValueError, e:
irc.error(msg, 'The regexp wasn\'t valid: %s' % e.args[0]) irc.error('The regexp wasn\'t valid: %s' % e.args[0])
return return
except re.error, e: except re.error, e:
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
return return
topics = self._splitTopic(irc.state.getTopic(channel), channel) topics = self._splitTopic(irc.state.getTopic(channel), channel)
if not topics: if not topics:
irc.error(msg, 'There are no topics to change.') irc.error('There are no topics to change.')
return return
topic = topics.pop(number) topic = topics.pop(number)
(topic, name) = self._unformatTopic(topic, channel) (topic, name) = self._unformatTopic(topic, channel)
try: try:
senderName = ircdb.users.getUser(msg.prefix).name senderName = ircdb.users.getUser(msg.prefix).name
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
if name and name != senderName and \ if name and name != senderName and \
not ircdb.checkCapabilities(msg.prefix, ('op', 'admin')): not ircdb.checkCapabilities(msg.prefix, ('op', 'admin')):
irc.error(msg, 'You can only modify your own topics.') irc.error('You can only modify your own topics.')
return return
newTopic = self.topicFormatter % (replacer(topic), name) newTopic = self.topicFormatter % (replacer(topic), name)
if number < 0: if number < 0:
@ -275,16 +275,16 @@ class Topic(callbacks.Privmsg, configurable.Mixin):
if number > 0: if number > 0:
number -= 1 number -= 1
elif number == 0: elif number == 0:
irc.error(msg, 'That\'s not a valid topic number.') irc.error('That\'s not a valid topic number.')
return return
except ValueError: except ValueError:
irc.error(msg, 'The argument must be a number.') irc.error('The argument must be a number.')
return return
topics = self._splitTopic(irc.state.getTopic(channel), channel) topics = self._splitTopic(irc.state.getTopic(channel), channel)
try: try:
topic = topics.pop(number) topic = topics.pop(number)
except IndexError: except IndexError:
irc.error(msg, 'That\'s not a valid topic number.') irc.error('That\'s not a valid topic number.')
return return
(topic, name) = self._unformatTopic(topic, channel) (topic, name) = self._unformatTopic(topic, channel)
try: try:
@ -293,7 +293,7 @@ class Topic(callbacks.Privmsg, configurable.Mixin):
username = msg.nick username = msg.nick
if name and name != username and \ if name and name != username and \
not ircdb.checkCapabilities(msg.prefix, ('op', 'admin')): not ircdb.checkCapabilities(msg.prefix, ('op', 'admin')):
irc.error(msg, 'You can only remove your own topics.') irc.error('You can only remove your own topics.')
return return
newTopic = self._joinTopic(topics, channel) newTopic = self._joinTopic(topics, channel)
irc.queueMsg(ircmsgs.topic(channel, newTopic)) irc.queueMsg(ircmsgs.topic(channel, newTopic))

View File

@ -200,7 +200,7 @@ class URL(callbacks.PrivmsgCommandAndRegexp,
elif updateDb: elif updateDb:
self._updateTinyDb(url, tinyurl, channel) self._updateTinyDb(url, tinyurl, channel)
s = '%s (was <%s>)' % (ircutils.bold(tinyurl), url) s = '%s (was <%s>)' % (ircutils.bold(tinyurl), url)
irc.reply(msg, s, prefixName=False) irc.reply(s, prefixName=False)
tinyurlSnarfer = privmsgs.urlSnarfer(tinyurlSnarfer) tinyurlSnarfer = privmsgs.urlSnarfer(tinyurlSnarfer)
def titleSnarfer(self, irc, msg, match): def titleSnarfer(self, irc, msg, match):
@ -216,7 +216,7 @@ class URL(callbacks.PrivmsgCommandAndRegexp,
s = 'Title: %s' % utils.htmlToText(m.group(1).strip()) s = 'Title: %s' % utils.htmlToText(m.group(1).strip())
if self.configurables.get('titlesnarferincludesurl', channel): if self.configurables.get('titlesnarferincludesurl', channel):
s += ' (<%s>)' % url s += ' (<%s>)' % url
irc.reply(msg, s, prefixName=False) irc.reply(s, prefixName=False)
titleSnarfer = privmsgs.urlSnarfer(titleSnarfer) titleSnarfer = privmsgs.urlSnarfer(titleSnarfer)
def _updateTinyDb(self, url, tinyurl, channel): def _updateTinyDb(self, url, tinyurl, channel):
@ -278,9 +278,9 @@ class URL(callbacks.PrivmsgCommandAndRegexp,
ORDER BY random() ORDER BY random()
LIMIT 1""") LIMIT 1""")
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'I have no URLs in my database for %s' % channel) irc.reply('I have no URLs in my database for %s' % channel)
else: else:
irc.reply(msg, self._formatUrl(*cursor.fetchone())) irc.reply(self._formatUrl(*cursor.fetchone()))
def tiny(self, irc, msg, args): def tiny(self, irc, msg, args):
"""<url> """<url>
@ -289,7 +289,7 @@ class URL(callbacks.PrivmsgCommandAndRegexp,
""" """
url = privmsgs.getArgs(args) url = privmsgs.getArgs(args)
if len(url) < 23: if len(url) < 23:
irc.error(msg, irc.error(
'Stop being a lazy-biotch and type the URL yourself.') 'Stop being a lazy-biotch and type the URL yourself.')
return return
channel = msg.args[0] channel = msg.args[0]
@ -302,11 +302,11 @@ class URL(callbacks.PrivmsgCommandAndRegexp,
if tinyurl: if tinyurl:
if updateDb: if updateDb:
self._updateTinyDb(url, tinyurl, channel) self._updateTinyDb(url, tinyurl, channel)
irc.reply(msg, tinyurl) irc.reply(tinyurl)
else: else:
s = 'Could not parse the TinyURL.com results page. (%s)' % \ s = 'Could not parse the TinyURL.com results page. (%s)' % \
conf.replyPossibleBug conf.replyPossibleBug
irc.error(msg, s) irc.error(s)
tiny = privmsgs.thread(tiny) tiny = privmsgs.thread(tiny)
def num(self, irc, msg, args): def num(self, irc, msg, args):
@ -320,7 +320,7 @@ class URL(callbacks.PrivmsgCommandAndRegexp,
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT COUNT(*) FROM urls""") cursor.execute("""SELECT COUNT(*) FROM urls""")
(count,) = cursor.fetchone() (count,) = cursor.fetchone()
irc.reply(msg, 'I have %s %s in my database.' % \ irc.reply('I have %s %s in my database.' % \
(count, int(count) == 1 and 'URL' or 'URLs')) (count, int(count) == 1 and 'URL' or 'URLs'))
def last(self, irc, msg, args): def last(self, irc, msg, args):
@ -382,7 +382,7 @@ class URL(callbacks.PrivmsgCommandAndRegexp,
LIMIT 100""" % criterion LIMIT 100""" % criterion
cursor.execute(sql, *formats) cursor.execute(sql, *formats)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'No URLs matched that criteria.') irc.reply('No URLs matched that criteria.')
else: else:
if nolimit: if nolimit:
urls = ['<%s>' % t[1] for t in cursor.fetchall()] urls = ['<%s>' % t[1] for t in cursor.fetchall()]
@ -395,7 +395,7 @@ class URL(callbacks.PrivmsgCommandAndRegexp,
time.localtime(int(added))) time.localtime(int(added)))
s = '#%s: <%s>, added by %s at %s.' % \ s = '#%s: <%s>, added by %s at %s.' % \
(id, url, added_by, timestamp) (id, url, added_by, timestamp)
irc.reply(msg, s) irc.reply(s)
Class = URL Class = URL

View File

@ -134,18 +134,18 @@ class Unix(callbacks.Privmsg):
try: try:
i = getattr(errno, name) i = getattr(errno, name)
except AttributeError: except AttributeError:
irc.reply(msg, 'I can\'t find the errno number for that code.') irc.reply('I can\'t find the errno number for that code.')
return return
except KeyError: except KeyError:
name = '(unknown)' name = '(unknown)'
irc.reply(msg, '%s (#%s): %s' % (name, i, os.strerror(i))) irc.reply('%s (#%s): %s' % (name, i, os.strerror(i)))
def progstats(self, irc, msg, args): def progstats(self, irc, msg, args):
"""takes no arguments """takes no arguments
Returns various unix-y information on the running supybot process. Returns various unix-y information on the running supybot process.
""" """
irc.reply(msg, progstats()) irc.reply(progstats())
_cryptre = re.compile(r'[./0-9A-Za-z]') _cryptre = re.compile(r'[./0-9A-Za-z]')
def crypt(self, irc, msg, args): def crypt(self, irc, msg, args):
@ -164,7 +164,7 @@ class Unix(callbacks.Privmsg):
(password, salt) = privmsgs.getArgs(args, optional=1) (password, salt) = privmsgs.getArgs(args, optional=1)
if salt == '': if salt == '':
salt = makeSalt() salt = makeSalt()
irc.reply(msg, crypt.crypt(password, salt)) irc.reply(crypt.crypt(password, salt))
def spell(self, irc, msg, args): def spell(self, irc, msg, args):
"""<word> """<word>
@ -175,21 +175,21 @@ class Unix(callbacks.Privmsg):
""" """
# We are only checking the first word # We are only checking the first word
if not self.spellCmd: if not self.spellCmd:
irc.error(msg, 'A spell checking command doesn\'t seem to be ' irc.error('A spell checking command doesn\'t seem to be '
'installed on this computer.') 'installed on this computer.')
return return
word = privmsgs.getArgs(args) word = privmsgs.getArgs(args)
if word and not word[0].isalpha(): if word and not word[0].isalpha():
irc.error(msg, '<word> must begin with an alphabet character.') irc.error('<word> must begin with an alphabet character.')
return return
if ' ' in word: if ' ' in word:
irc.error(msg, 'Spaces aren\'t allowed in the word.') irc.error('Spaces aren\'t allowed in the word.')
return return
try: try:
(r, w) = popen2.popen4([self.spellCmd, '-a']) (r, w) = popen2.popen4([self.spellCmd, '-a'])
s = r.readline() # Banner, hopefully. s = r.readline() # Banner, hopefully.
if 'sorry' in s.lower(): if 'sorry' in s.lower():
irc.error(msg, s) irc.error(s)
return return
w.write(word) w.write(word)
w.write('\n') w.write('\n')
@ -200,7 +200,7 @@ class Unix(callbacks.Privmsg):
while not line.strip('\r\n'): while not line.strip('\r\n'):
line = pipeReadline(r) line = pipeReadline(r)
except TimeoutError: except TimeoutError:
irc.error(msg, 'The spell command timed out.') irc.error('The spell command timed out.')
return return
finally: finally:
r.close() r.close()
@ -216,7 +216,7 @@ class Unix(callbacks.Privmsg):
(word, utils.commaAndify(matches.split(', '))) (word, utils.commaAndify(matches.split(', ')))
else: else:
resp = 'Something unexpected was seen in the [ai]spell output.' resp = 'Something unexpected was seen in the [ai]spell output.'
irc.reply(msg, resp) irc.reply(resp)
def fortune(self, irc, msg, args): def fortune(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -228,9 +228,9 @@ class Unix(callbacks.Privmsg):
s = r.read() s = r.read()
w.close() w.close()
r.close() r.close()
irc.reply(msg, ' '.join(s.split())) irc.reply(' '.join(s.split()))
else: else:
irc.error(msg, 'I couldn\'t find the fortune command.') irc.error('I couldn\'t find the fortune command.')
def wtf(self, irc, msg, args): def wtf(self, irc, msg, args):
"""[is] <something> """[is] <something>
@ -246,11 +246,11 @@ class Unix(callbacks.Privmsg):
something = something.rstrip('?') something = something.rstrip('?')
(r, w) = popen2.popen4([self.wtfCmd, something]) (r, w) = popen2.popen4([self.wtfCmd, something])
response = utils.normalizeWhitespace(r.readline().strip()) response = utils.normalizeWhitespace(r.readline().strip())
irc.reply(msg, response) irc.reply(response)
r.close() r.close()
w.close() w.close()
else: else:
irc.error(msg, 'I couldn\'t find the wtf command.') irc.error('I couldn\'t find the wtf command.')
Class = Unix Class = Unix

View File

@ -64,7 +64,7 @@ class Utilities(callbacks.Privmsg):
Joins all the arguments together with <separator>. Joins all the arguments together with <separator>.
""" """
sep = args.pop(0) sep = args.pop(0)
irc.reply(msg, sep.join(args)) irc.reply(sep.join(args))
def strtranslate(self, irc, msg, args): def strtranslate(self, irc, msg, args):
"""<chars to translate> <chars to replace those with> <text> """<chars to translate> <chars to replace those with> <text>
@ -74,21 +74,21 @@ class Utilities(callbacks.Privmsg):
length. length.
""" """
(bad, good, text) = privmsgs.getArgs(args, required=3) (bad, good, text) = privmsgs.getArgs(args, required=3)
irc.reply(msg, text.translate(string.maketrans(bad, good))) irc.reply(text.translate(string.maketrans(bad, good)))
def strupper(self, irc, msg, args): def strupper(self, irc, msg, args):
"""<text> """<text>
Returns <text> uppercased. Returns <text> uppercased.
""" """
irc.reply(msg, privmsgs.getArgs(args).upper()) irc.reply(privmsgs.getArgs(args).upper())
def strlower(self, irc, msg, args): def strlower(self, irc, msg, args):
"""<text> """<text>
Returns <text> lowercased. Returns <text> lowercased.
""" """
irc.reply(msg, privmsgs.getArgs(args).lower()) irc.reply(privmsgs.getArgs(args).lower())
def strlen(self, irc, msg, args): def strlen(self, irc, msg, args):
"""<text> """<text>
@ -99,7 +99,7 @@ class Utilities(callbacks.Privmsg):
for arg in args: for arg in args:
total += len(arg) total += len(arg)
total += len(args)-1 # spaces between the arguments. total += len(args)-1 # spaces between the arguments.
irc.reply(msg, str(total)) irc.reply(str(total))
def repr(self, irc, msg, args): def repr(self, irc, msg, args):
"""<text> """<text>
@ -107,7 +107,7 @@ class Utilities(callbacks.Privmsg):
Returns the text surrounded by double quotes. Returns the text surrounded by double quotes.
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
irc.reply(msg, utils.dqrepr(text)) irc.reply(utils.dqrepr(text))
def strconcat(self, irc, msg, args): def strconcat(self, irc, msg, args):
"""<string 1> <string 2> """<string 1> <string 2>
@ -117,7 +117,7 @@ class Utilities(callbacks.Privmsg):
removed by strconcat. removed by strconcat.
""" """
(first, second) = privmsgs.getArgs(args, required=2) (first, second) = privmsgs.getArgs(args, required=2)
irc.reply(msg, first+second) irc.reply(first+second)
def echo(self, irc, msg, args): def echo(self, irc, msg, args):
"""takes any number of arguments """takes any number of arguments
@ -126,7 +126,7 @@ class Utilities(callbacks.Privmsg):
""" """
if not args: if not args:
raise callbacks.ArgumentError raise callbacks.ArgumentError
irc.reply(msg, ' '.join(args), prefixName=False) irc.reply(' '.join(args), prefixName=False)
def re(self, irc, msg, args): def re(self, irc, msg, args):
"""<regexp> <text> """<regexp> <text>
@ -140,7 +140,7 @@ class Utilities(callbacks.Privmsg):
self.log.info('re command called with regexp %r from %s' % self.log.info('re command called with regexp %r from %s' %
(regexp, msg.prefix)) (regexp, msg.prefix))
if len(regexp) > 512: if len(regexp) > 512:
irc.error(msg, 'Your regexp is just plain too long.') irc.error('Your regexp is just plain too long.')
return return
f = None f = None
try: try:
@ -150,16 +150,16 @@ class Utilities(callbacks.Privmsg):
try: try:
f = utils.perlReToReplacer(regexp) f = utils.perlReToReplacer(regexp)
except ValueError, e: except ValueError, e:
irc.error(msg, 'Invalid regexp: %s' % e.args[0]) irc.error('Invalid regexp: %s' % e.args[0])
return return
if f is None: if f is None:
irc.error(msg, 'Invalid regexp: %s' % e.args[0]) irc.error('Invalid regexp: %s' % e.args[0])
return return
if f('') and len(f(' ')) > len(f(''))+1: # Matches the empty string. if f('') and len(f(' ')) > len(f(''))+1: # Matches the empty string.
s = 'You probably don\'t want to match the empty string.' s = 'You probably don\'t want to match the empty string.'
irc.error(msg, s) irc.error(s)
else: else:
irc.reply(msg, f(text)) irc.reply(f(text))
re = privmsgs.checkCapability(re, 'trusted') re = privmsgs.checkCapability(re, 'trusted')

View File

@ -59,7 +59,7 @@ class Weather(callbacks.Privmsg):
try: try:
callbacks.Privmsg.callCommand(self, method, irc, msg, *L) callbacks.Privmsg.callCommand(self, method, irc, msg, *L)
except webutils.WebError, e: except webutils.WebError, e:
irc.error(msg, str(e)) irc.error(str(e))
_cityregex = re.compile( _cityregex = re.compile(
r'<td><font size="4" face="arial"><b>'\ r'<td><font size="4" face="arial"><b>'\
@ -136,7 +136,7 @@ class Weather(callbacks.Privmsg):
(city, state) (city, state)
html = webutils.getUrl(url) html = webutils.getUrl(url)
if 'was not found' in html: if 'was not found' in html:
irc.error(msg, 'No such location could be found.') irc.error('No such location could be found.')
return return
#We received a single argument. Zipcode or station id. #We received a single argument. Zipcode or station id.
@ -148,7 +148,7 @@ class Weather(callbacks.Privmsg):
'config=&forecast=zandh&pands=%s&Submit=GO' % args[0] 'config=&forecast=zandh&pands=%s&Submit=GO' % args[0]
html = webutils.getUrl(url) html = webutils.getUrl(url)
if 'was not found' in html: if 'was not found' in html:
irc.error(msg, 'No such location could be found.') irc.error('No such location could be found.')
return return
headData = self._cityregex.search(html) headData = self._cityregex.search(html)
@ -159,7 +159,7 @@ class Weather(callbacks.Privmsg):
if headData: if headData:
(city, state) = headData.groups() (city, state) = headData.groups()
else: else:
irc.error(msg, 'No such location could be found.') irc.error('No such location could be found.')
return return
city = city.strip() city = city.strip()
@ -188,9 +188,9 @@ class Weather(callbacks.Privmsg):
conds = conds.replace('Tsra', 'Thunder Storms') conds = conds.replace('Tsra', 'Thunder Storms')
s = 'The current temperature in %s, %s is %s%s. Conditions: %s' % \ s = 'The current temperature in %s, %s is %s%s. Conditions: %s' % \
(city, state, temp, index, conds) (city, state, temp, index, conds)
irc.reply(msg, s) irc.reply(s)
else: else:
irc.error(msg, 'The format of the page was odd.') irc.error('The format of the page was odd.')
Class = Weather Class = Weather

View File

@ -121,11 +121,11 @@ class Words(callbacks.Privmsg, configurable.Mixin):
raise callbacks.ArgumentError raise callbacks.ArgumentError
for word in args: for word in args:
if word.translate(string.ascii, string.ascii_letters): if word.translate(string.ascii, string.ascii_letters):
irc.error(msg, 'Word must contain only letters.') irc.error('Word must contain only letters.')
return return
else: else:
addWord(self.dbHandler.getDb(), word, commit=True) addWord(self.dbHandler.getDb(), word, commit=True)
irc.replySuccess(msg) irc.replySuccess()
def crossword(self, irc, msg, args): def crossword(self, irc, msg, args):
"""<word> """<word>
@ -137,16 +137,16 @@ class Words(callbacks.Privmsg, configurable.Mixin):
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
if '%' in word: if '%' in word:
irc.error(msg, '"%" isn\'t allowed in the word.') irc.error('"%" isn\'t allowed in the word.')
return return
cursor.execute("""SELECT word FROM words cursor.execute("""SELECT word FROM words
WHERE word LIKE %s WHERE word LIKE %s
ORDER BY word""", word) ORDER BY word""", word)
words = [t[0] for t in cursor.fetchall()] words = [t[0] for t in cursor.fetchall()]
if words: if words:
irc.reply(msg, utils.commaAndify(words)) irc.reply(utils.commaAndify(words))
else: else:
irc.reply(msg, 'No matching words were found.') irc.reply('No matching words were found.')
def anagram(self, irc, msg, args): def anagram(self, irc, msg, args):
"""<word> """<word>
@ -161,16 +161,16 @@ class Words(callbacks.Privmsg, configurable.Mixin):
sorted = ''.join(L) sorted = ''.join(L)
cursor.execute("""SELECT id FROM sorted_words WHERE word=%s""", sorted) cursor.execute("""SELECT id FROM sorted_words WHERE word=%s""", sorted)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply(msg, 'That word has no anagrams I could find.') irc.reply('That word has no anagrams I could find.')
else: else:
id = cursor.fetchone()[0] id = cursor.fetchone()[0]
cursor.execute("""SELECT words.word FROM words cursor.execute("""SELECT words.word FROM words
WHERE sorted_word_id=%s""", id) WHERE sorted_word_id=%s""", id)
if cursor.rowcount > 1: if cursor.rowcount > 1:
words = [t[0] for t in cursor.fetchall()] words = [t[0] for t in cursor.fetchall()]
irc.reply(msg, utils.commaAndify(words)) irc.reply(utils.commaAndify(words))
else: else:
irc.reply(msg, 'That word has no anagrams I could find.') irc.reply('That word has no anagrams I could find.')
### ###
# HANGMAN # HANGMAN
@ -234,7 +234,7 @@ class Words(callbacks.Privmsg, configurable.Mixin):
""" """
channel = msg.args[0] channel = msg.args[0]
game = self.games[channel] game = self.games[channel]
irc.reply(msg, '%s %s' % (game['prefix'], ' '.join(game['unused']))) irc.reply('%s %s' % (game['prefix'], ' '.join(game['unused'])))
def newhangman(self, irc, msg, args): def newhangman(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -242,7 +242,7 @@ class Words(callbacks.Privmsg, configurable.Mixin):
Creates a new game of hangman Creates a new game of hangman
""" """
if not self.gotDictFile: if not self.gotDictFile:
irc.error(msg, 'You do not currently have a dict file, you can get' irc.error('You do not currently have a dict file, you can get'
' one at: %s' % self.dicturl) ' one at: %s' % self.dicturl)
return return
channel = msg.args[0] channel = msg.args[0]
@ -261,7 +261,7 @@ class Words(callbacks.Privmsg, configurable.Mixin):
game['unused'] = copy.copy(self.validLetters) game['unused'] = copy.copy(self.validLetters)
game['hidden'] = random.choice(self.wordList).lower().strip() game['hidden'] = random.choice(self.wordList).lower().strip()
game['guess'] = '_' * len(game['hidden']) game['guess'] = '_' * len(game['hidden'])
irc.reply(msg, '%sOkay ladies and gentlemen, you have ' irc.reply('%sOkay ladies and gentlemen, you have '
'a %s-letter word to find, you have %s!' % 'a %s-letter word to find, you have %s!' %
(game['prefix'], len(game['hidden']), (game['prefix'], len(game['hidden']),
self.triesLeft(game['tries'])), prefixName=False) self.triesLeft(game['tries'])), prefixName=False)
@ -273,7 +273,7 @@ class Words(callbacks.Privmsg, configurable.Mixin):
self.endGame(channel) self.endGame(channel)
self.newhangman(irc, msg, args) self.newhangman(irc, msg, args)
else: else:
irc.error(msg, 'Sorry, there is already a game going on. ' irc.error('Sorry, there is already a game going on. '
'%s left before timeout.' % utils.nItems('seconds', '%s left before timeout.' % utils.nItems('seconds',
int(game['timeout'] - secondsEllapsed))) int(game['timeout'] - secondsEllapsed)))
@ -286,7 +286,7 @@ class Words(callbacks.Privmsg, configurable.Mixin):
channel = msg.args[0] channel = msg.args[0]
game = self.games[channel] game = self.games[channel]
if not game['gameon']: if not game['gameon']:
irc.error(msg, 'There is no hangman game going on right now.') irc.error('There is no hangman game going on right now.')
return return
letter = privmsgs.getArgs(args) letter = privmsgs.getArgs(args)
game['timeguess'] = time.time() game['timeguess'] = time.time()
@ -294,46 +294,48 @@ class Words(callbacks.Privmsg, configurable.Mixin):
if letter in game['unused']: if letter in game['unused']:
del game['unused'][game['unused'].index(letter)] del game['unused'][game['unused'].index(letter)]
if letter in game['hidden']: if letter in game['hidden']:
irc.reply(msg, '%sYes, there is %s %s' % (game['prefix'], irc.reply('%sYes, there is %s %s' % (game['prefix'],
self.letterArticle(letter), `letter`), prefixName=False) self.letterArticle(letter), `letter`), prefixName=False)
game['guess'] = self.addLetter(letter, game['guess'], game['guess'] = self.addLetter(letter, game['guess'],
self.letterPositions(letter, game['hidden'])) self.letterPositions(letter, game['hidden']))
if game['guess'] == game['hidden']: if game['guess'] == game['hidden']:
game['guessed'] = True game['guessed'] = True
else: else:
irc.reply(msg,'%sNo, there is no %s' % (game['prefix'],`letter`), irc.reply('%sNo, there is no %s' % (game['prefix'],`letter`),
prefixName=False) prefixName=False)
game['tries'] -= 1 game['tries'] -= 1
irc.reply(msg, '%s%s (%s left)' % (game['prefix'], game['guess'], irc.reply('%s%s (%s left)' % (game['prefix'], game['guess'],
self.triesLeft(game['tries'])), prefixName=False) self.triesLeft(game['tries'])), prefixName=False)
# User input a valid character that has already been tried # User input a valid character that has already been tried
elif letter in self.validLetters: elif letter in self.validLetters:
irc.error(msg, 'That letter has already been tried.') irc.error('That letter has already been tried.')
# User tries to guess the whole word or entered an invalid input # User tries to guess the whole word or entered an invalid input
else: else:
# The length of the word tried by the user and that of the hidden # The length of the word tried by the user and that of the hidden
# word are same, so we assume the user wants to guess the whole word # word are same, so we assume the user wants to guess the whole
# word
if len(letter) == len(game['hidden']): if len(letter) == len(game['hidden']):
if letter == game['hidden']: if letter == game['hidden']:
game['guessed'] = True game['guessed'] = True
else: else:
irc.reply(msg, '%syou did not guess the correct word ' irc.reply('%syou did not guess the correct word '
'and you lose a try' % game['prefix'], prefixName=False) 'and you lose a try' % game['prefix'],
prefixName=False)
game['tries'] -= 1 game['tries'] -= 1
else: else:
# User input an invalid character # User input an invalid character
if len(letter) == 1: if len(letter) == 1:
irc.error(msg, 'That is not a valid character.') irc.error('That is not a valid character.')
# User input an invalid word (different length from hidden word) # User input an invalid word (different length from hidden word)
else: else:
irc.error(msg, 'That is not a valid word guess.') irc.error('That is not a valid word guess.')
# Verify if the user won or lost # Verify if the user won or lost
if game['guessed'] and game['tries'] > 0: if game['guessed'] and game['tries'] > 0:
irc.reply(msg, '%sYou win! The word was indeed %s' % irc.reply('%sYou win! The word was indeed %s' %
(game['prefix'], game['hidden']), prefixName=False) (game['prefix'], game['hidden']), prefixName=False)
self.endGame(channel) self.endGame(channel)
elif not game['guessed'] and game['tries'] == 0: elif not game['guessed'] and game['tries'] == 0:
irc.reply(msg, '%sYou lose! The word was %s' % irc.reply('%sYou lose! The word was %s' %
(game['prefix'], game['hidden']), prefixName=False) (game['prefix'], game['hidden']), prefixName=False)
self.endGame(channel) self.endGame(channel)
### ###

View File

@ -64,7 +64,7 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
channel = msg.args[1] channel = msg.args[1]
(irc, msg) = self.joins[channel] (irc, msg) = self.joins[channel]
del self.joins[channel] del self.joins[channel]
irc.error(msg, 'Cannot join %s, it\'s full.' % channel) irc.error('Cannot join %s, it\'s full.' % channel)
except KeyError: except KeyError:
self.log.debug('Got 471 without Admin.join being called.') self.log.debug('Got 471 without Admin.join being called.')
@ -73,7 +73,7 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
channel = msg.args[1] channel = msg.args[1]
(irc, msg) = self.joins[channel] (irc, msg) = self.joins[channel]
del self.joins[channel] del self.joins[channel]
irc.error(msg, 'Cannot join %s, I was not invited.' % channel) irc.error('Cannot join %s, I was not invited.' % channel)
except KeyError: except KeyError:
self.log.debug('Got 473 without Admin.join being called.') self.log.debug('Got 473 without Admin.join being called.')
@ -82,7 +82,7 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
channel = msg.args[1] channel = msg.args[1]
(irc, msg) = self.joins[channel] (irc, msg) = self.joins[channel]
del self.joins[channel] del self.joins[channel]
irc.error(msg, 'Cannot join %s, it\'s banned me.' % channel) irc.error('Cannot join %s, it\'s banned me.' % channel)
except KeyError: except KeyError:
self.log.debug('Got 474 without Admin.join being called.') self.log.debug('Got 474 without Admin.join being called.')
@ -91,7 +91,7 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
channel = msg.args[1] channel = msg.args[1]
(irc, msg) = self.joins[channel] (irc, msg) = self.joins[channel]
del self.joins[channel] del self.joins[channel]
irc.error(msg, 'Cannot join %s, my keyword was wrong.' % channel) irc.error('Cannot join %s, my keyword was wrong.' % channel)
except KeyError: except KeyError:
self.log.debug('Got 475 without Admin.join being called.') self.log.debug('Got 475 without Admin.join being called.')
@ -141,14 +141,14 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
to protect the secrecy of secret channels. to protect the secrecy of secret channels.
""" """
if ircutils.isChannel(msg.args[0]): if ircutils.isChannel(msg.args[0]):
irc.error(msg, conf.replyRequiresPrivacy) irc.error(conf.replyRequiresPrivacy)
return return
L = irc.state.channels.keys() L = irc.state.channels.keys()
if L: if L:
utils.sortBy(ircutils.toLower, L) utils.sortBy(ircutils.toLower, L)
irc.reply(msg, utils.commaAndify(L)) irc.reply(utils.commaAndify(L))
else: else:
irc.reply(msg, 'I\'m not currently in any channels.') irc.reply('I\'m not currently in any channels.')
def nick(self, irc, msg, args): def nick(self, irc, msg, args):
"""<nick> """<nick>
@ -167,7 +167,7 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
args.append(msg.args[0]) args.append(msg.args[0])
for arg in args: for arg in args:
if arg not in irc.state.channels: if arg not in irc.state.channels:
irc.error(msg, 'I\'m not currently in %s' % arg) irc.error('I\'m not currently in %s' % arg)
return return
irc.queueMsg(ircmsgs.parts(args, msg.nick)) irc.queueMsg(ircmsgs.parts(args, msg.nick))
@ -178,19 +178,19 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
""" """
command = privmsgs.getArgs(args) command = privmsgs.getArgs(args)
if command in ('enable', 'identify'): if command in ('enable', 'identify'):
irc.error(msg, 'You can\'t disable %s!' % command) irc.error('You can\'t disable %s!' % command)
else: else:
# This has to know that defaultCapabilties gets turned into a # This has to know that defaultCapabilties gets turned into a
# dictionary. # dictionary.
try: try:
capability = ircdb.makeAntiCapability(command) capability = ircdb.makeAntiCapability(command)
except ValueError: except ValueError:
irc.error(msg, '%r is not a valid command.' % command) irc.error('%r is not a valid command.' % command)
return return
if command in conf.defaultCapabilities: if command in conf.defaultCapabilities:
conf.defaultCapabilities.remove(command) conf.defaultCapabilities.remove(command)
conf.defaultCapabilities.add(capability) conf.defaultCapabilities.add(capability)
irc.replySuccess(msg) irc.replySuccess()
def enable(self, irc, msg, args): def enable(self, irc, msg, args):
"""<command> """<command>
@ -201,13 +201,13 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
try: try:
anticapability = ircdb.makeAntiCapability(command) anticapability = ircdb.makeAntiCapability(command)
except ValueError: except ValueError:
irc.error(msg, '%r is not a valid command.' % command) irc.error('%r is not a valid command.' % command)
return return
if anticapability in conf.defaultCapabilities: if anticapability in conf.defaultCapabilities:
conf.defaultCapabilities.remove(anticapability) conf.defaultCapabilities.remove(anticapability)
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, 'That command wasn\'t disabled.') irc.error('That command wasn\'t disabled.')
def addcapability(self, irc, msg, args): def addcapability(self, irc, msg, args):
"""<name|hostmask> <capability> """<name|hostmask> <capability>
@ -230,7 +230,7 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
# generally means they can't mess with channel capabilities. # generally means they can't mess with channel capabilities.
(name, capability) = privmsgs.getArgs(args, required=2) (name, capability) = privmsgs.getArgs(args, required=2)
if capability == 'owner': if capability == 'owner':
irc.error(msg, 'The "owner" capability can\'t be added in the bot.' irc.error('The "owner" capability can\'t be added in the bot.'
' Use the supybot-adduser program (or edit the ' ' Use the supybot-adduser program (or edit the '
'users.conf file yourself) to add an owner ' 'users.conf file yourself) to add an owner '
'capability.') 'capability.')
@ -242,12 +242,12 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
user.addCapability(capability) user.addCapability(capability)
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.replySuccess(msg) irc.replySuccess()
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
else: else:
s = 'You can\'t add capabilities you don\'t have.' s = 'You can\'t add capabilities you don\'t have.'
irc.error(msg, s) irc.error(s)
def removecapability(self, irc, msg, args): def removecapability(self, irc, msg, args):
"""<name|hostmask> <capability> """<name|hostmask> <capability>
@ -262,18 +262,18 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
id = ircdb.users.getUserId(name) id = ircdb.users.getUserId(name)
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
try: try:
user.removeCapability(capability) user.removeCapability(capability)
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.replySuccess(msg) irc.replySuccess()
except KeyError: except KeyError:
irc.error(msg, 'That user doesn\'t have that capability.') irc.error('That user doesn\'t have that capability.')
return return
else: else:
s = 'You can\'t remove capabilities you don\'t have.' s = 'You can\'t remove capabilities you don\'t have.'
irc.error(msg, s) irc.error(s)
def ignore(self, irc, msg, args): def ignore(self, irc, msg, args):
"""<hostmask|nick> """<hostmask|nick>
@ -288,10 +288,10 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
try: try:
hostmask = irc.state.nickToHostmask(arg) hostmask = irc.state.nickToHostmask(arg)
except KeyError: except KeyError:
irc.error(msg, 'I can\'t find a hostmask for %s' % arg) irc.error('I can\'t find a hostmask for %s' % arg)
return return
conf.ignores.append(hostmask) conf.ignores.append(hostmask)
irc.replySuccess(msg) irc.replySuccess()
def unignore(self, irc, msg, args): def unignore(self, irc, msg, args):
"""<hostmask|nick> """<hostmask|nick>
@ -306,15 +306,15 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
try: try:
hostmask = irc.state.nickToHostmask(arg) hostmask = irc.state.nickToHostmask(arg)
except KeyError: except KeyError:
irc.error(msg, 'I can\'t find a hostmask for %s' % arg) irc.error('I can\'t find a hostmask for %s' % arg)
return return
try: try:
conf.ignores.remove(hostmask) conf.ignores.remove(hostmask)
while hostmask in conf.ignores: while hostmask in conf.ignores:
conf.ignores.remove(hostmask) conf.ignores.remove(hostmask)
irc.replySuccess(msg) irc.replySuccess()
except ValueError: except ValueError:
irc.error(msg, '%s wasn\'t in conf.ignores.' % hostmask) irc.error('%s wasn\'t in conf.ignores.' % hostmask)
def ignores(self, irc, msg, args): def ignores(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -322,9 +322,9 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
Returns the hostmasks currently being globally ignored. Returns the hostmasks currently being globally ignored.
""" """
if conf.ignores: if conf.ignores:
irc.reply(msg, utils.commaAndify(imap(repr, conf.ignores))) irc.reply(utils.commaAndify(imap(repr, conf.ignores)))
else: else:
irc.reply(msg, 'I\'m not currently globally ignoring anyone.') irc.reply('I\'m not currently globally ignoring anyone.')
def setprefixchar(self, irc, msg, args): def setprefixchar(self, irc, msg, args):
"""<prefixchars> """<prefixchars>
@ -335,11 +335,11 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
for c in s: for c in s:
if c not in conf.validPrefixChars: if c not in conf.validPrefixChars:
s = 'PrefixChars must be something in %r'%conf.validPrefixChars s = 'PrefixChars must be something in %r'%conf.validPrefixChars
irc.error(msg, s) irc.error(s)
return return
else: else:
conf.prefixChars = s conf.prefixChars = s
irc.replySuccess(msg) irc.replySuccess()
def reportbug(self, irc, msg, args): def reportbug(self, irc, msg, args):
"""<description> """<description>
@ -366,7 +366,7 @@ class Admin(privmsgs.CapabilityCheckingPrivmsg):
['supybot-bugs@lists.sourceforge.net'], ['supybot-bugs@lists.sourceforge.net'],
email) email)
smtp.quit() smtp.quit()
irc.replySuccess(msg) irc.replySuccess()
reportbug = privmsgs.thread(reportbug) reportbug = privmsgs.thread(reportbug)

View File

@ -62,7 +62,7 @@ class Channel(callbacks.Privmsg):
if irc.nick in irc.state.channels[channel].ops: if irc.nick in irc.state.channels[channel].ops:
irc.queueMsg(ircmsgs.op(channel, msg.nick)) irc.queueMsg(ircmsgs.op(channel, msg.nick))
else: else:
irc.error(msg, 'How can I op you? I\'m not opped!') irc.error('How can I op you? I\'m not opped!')
op = privmsgs.checkChannelCapability(op, 'op') op = privmsgs.checkChannelCapability(op, 'op')
def halfop(self, irc, msg, args, channel): def halfop(self, irc, msg, args, channel):
@ -75,7 +75,7 @@ class Channel(callbacks.Privmsg):
if irc.nick in irc.state.channels[channel].ops: if irc.nick in irc.state.channels[channel].ops:
irc.queueMsg(ircmsgs.halfop(channel, msg.nick)) irc.queueMsg(ircmsgs.halfop(channel, msg.nick))
else: else:
irc.error(msg, 'How can I halfop you? I\'m not opped!') irc.error('How can I halfop you? I\'m not opped!')
halfop = privmsgs.checkChannelCapability(halfop, 'halfop') halfop = privmsgs.checkChannelCapability(halfop, 'halfop')
def voice(self, irc, msg, args, channel): def voice(self, irc, msg, args, channel):
@ -88,7 +88,7 @@ class Channel(callbacks.Privmsg):
if irc.nick in irc.state.channels[channel].ops: if irc.nick in irc.state.channels[channel].ops:
irc.queueMsg(ircmsgs.voice(channel, msg.nick)) irc.queueMsg(ircmsgs.voice(channel, msg.nick))
else: else:
irc.error(msg, 'How can I voice you? I\'m not opped!') irc.error('How can I voice you? I\'m not opped!')
voice = privmsgs.checkChannelCapability(voice, 'voice') voice = privmsgs.checkChannelCapability(voice, 'voice')
def deop(self, irc, msg, args, channel): def deop(self, irc, msg, args, channel):
@ -103,7 +103,7 @@ class Channel(callbacks.Privmsg):
if irc.nick in irc.state.channels[channel].ops: if irc.nick in irc.state.channels[channel].ops:
irc.queueMsg(ircmsgs.deops(channel, args)) irc.queueMsg(ircmsgs.deops(channel, args))
else: else:
irc.error(msg, 'How can I deop someone? I\'m not opped!') irc.error('How can I deop someone? I\'m not opped!')
deop = privmsgs.checkChannelCapability(deop, 'op') deop = privmsgs.checkChannelCapability(deop, 'op')
def dehalfop(self, irc, msg, args, channel): def dehalfop(self, irc, msg, args, channel):
@ -118,7 +118,7 @@ class Channel(callbacks.Privmsg):
if irc.nick in irc.state.channels[channel].ops: if irc.nick in irc.state.channels[channel].ops:
irc.queueMsg(ircmsgs.dehalfops(channel, args)) irc.queueMsg(ircmsgs.dehalfops(channel, args))
else: else:
irc.error(msg, 'How can I dehalfop someone? I\'m not opped!') irc.error('How can I dehalfop someone? I\'m not opped!')
dehalfop = privmsgs.checkChannelCapability(dehalfop, 'op') dehalfop = privmsgs.checkChannelCapability(dehalfop, 'op')
def devoice(self, irc, msg, args, channel): def devoice(self, irc, msg, args, channel):
@ -133,7 +133,7 @@ class Channel(callbacks.Privmsg):
if irc.nick in irc.state.channels[channel].ops: if irc.nick in irc.state.channels[channel].ops:
irc.queueMsg(ircmsgs.devoices(channel, args)) irc.queueMsg(ircmsgs.devoices(channel, args))
else: else:
irc.error(msg, 'How can I devoice someone? I\'m not opped!') irc.error('How can I devoice someone? I\'m not opped!')
devoice = privmsgs.checkChannelCapability(devoice, 'op') devoice = privmsgs.checkChannelCapability(devoice, 'op')
def cycle(self, irc, msg, args, channel): def cycle(self, irc, msg, args, channel):
@ -165,7 +165,7 @@ class Channel(callbacks.Privmsg):
reason = msg.nick reason = msg.nick
irc.queueMsg(ircmsgs.kick(channel, nick, reason)) irc.queueMsg(ircmsgs.kick(channel, nick, reason))
else: else:
irc.error(msg, 'How can I kick someone? I\'m not opped!') irc.error('How can I kick someone? I\'m not opped!')
kick = privmsgs.checkChannelCapability(kick, 'op') kick = privmsgs.checkChannelCapability(kick, 'op')
def kban(self, irc, msg, args): def kban(self, irc, msg, args):
@ -191,17 +191,17 @@ class Channel(callbacks.Privmsg):
raise callbacks.ArgumentError raise callbacks.ArgumentError
elif bannedNick == irc.nick: elif bannedNick == irc.nick:
self.log.warning('%r tried to make me kban myself.', msg.prefix) self.log.warning('%r tried to make me kban myself.', msg.prefix)
irc.error(msg, 'I cowardly refuse to kickban myself.') irc.error('I cowardly refuse to kickban myself.')
return return
try: try:
length = int(length or 0) length = int(length or 0)
except ValueError: except ValueError:
irc.error(msg, 'Ban length must be a valid integer.') irc.error('Ban length must be a valid integer.')
return return
try: try:
bannedHostmask = irc.state.nickToHostmask(bannedNick) bannedHostmask = irc.state.nickToHostmask(bannedNick)
except KeyError: except KeyError:
irc.error(msg, 'I haven\'t seen %s.' % bannedNick) irc.error('I haven\'t seen %s.' % bannedNick)
return return
capability = ircdb.makeChannelCapability(channel, 'op') capability = ircdb.makeChannelCapability(channel, 'op')
if optlist: if optlist:
@ -226,13 +226,13 @@ class Channel(callbacks.Privmsg):
if ircutils.hostmaskPatternEqual(banmask, irc.prefix): if ircutils.hostmaskPatternEqual(banmask, irc.prefix):
if ircutils.hostmaskPatternEqual(banmask, irc.prefix): if ircutils.hostmaskPatternEqual(banmask, irc.prefix):
self.log.warning('%r tried to make me kban myself.',msg.prefix) self.log.warning('%r tried to make me kban myself.',msg.prefix)
irc.error(msg, 'I cowardly refuse to ban myself.') irc.error('I cowardly refuse to ban myself.')
return return
else: else:
banmask = bannedHostmask banmask = bannedHostmask
# Check that we have ops. # Check that we have ops.
if irc.nick not in irc.state.channels[channel].ops: if irc.nick not in irc.state.channels[channel].ops:
irc.error(msg, 'How can I kick or ban someone? I\'m not opped.') irc.error('How can I kick or ban someone? I\'m not opped.')
return return
# Now, let's actually get to it. Check to make sure they have # Now, let's actually get to it. Check to make sure they have
# #channel.op and the bannee doesn't have #channel.op; or that the # #channel.op and the bannee doesn't have #channel.op; or that the
@ -250,14 +250,14 @@ class Channel(callbacks.Privmsg):
if ircdb.checkCapability(bannedHostmask, capability): if ircdb.checkCapability(bannedHostmask, capability):
self.log.warning('%r tried to ban %r, but both have %s', self.log.warning('%r tried to ban %r, but both have %s',
msg.prefix, bannedHostmask, capability) msg.prefix, bannedHostmask, capability)
irc.error(msg, '%s has %s too, you can\'t ban him/her/it.' % irc.error('%s has %s too, you can\'t ban him/her/it.' %
bannedNick, capability) bannedNick, capability)
else: else:
doBan() doBan()
else: else:
self.log.warning('%r attempted kban without %s', self.log.warning('%r attempted kban without %s',
msg.prefix, capability) msg.prefix, capability)
irc.error(msg, conf.replyNoCapability % capability) irc.error(conf.replyNoCapability % capability)
def unban(self, irc, msg, args, channel): def unban(self, irc, msg, args, channel):
"""[<channel>] <hostmask> """[<channel>] <hostmask>
@ -271,7 +271,7 @@ class Channel(callbacks.Privmsg):
if irc.nick in irc.state.channels[channel].ops: if irc.nick in irc.state.channels[channel].ops:
irc.queueMsg(ircmsgs.unban(channel, hostmask)) irc.queueMsg(ircmsgs.unban(channel, hostmask))
else: else:
irc.error(msg, 'How can I unban someone? I\'m not opped.') irc.error('How can I unban someone? I\'m not opped.')
unban = privmsgs.checkChannelCapability(unban, 'op') unban = privmsgs.checkChannelCapability(unban, 'op')
def lobotomize(self, irc, msg, args, channel): def lobotomize(self, irc, msg, args, channel):
@ -285,7 +285,7 @@ class Channel(callbacks.Privmsg):
c = ircdb.channels.getChannel(channel) c = ircdb.channels.getChannel(channel)
c.lobotomized = True c.lobotomized = True
ircdb.channels.setChannel(channel, c) ircdb.channels.setChannel(channel, c)
irc.replySuccess(msg) irc.replySuccess()
lobotomize = privmsgs.checkChannelCapability(lobotomize, 'op') lobotomize = privmsgs.checkChannelCapability(lobotomize, 'op')
def unlobotomize(self, irc, msg, args, channel): def unlobotomize(self, irc, msg, args, channel):
@ -299,7 +299,7 @@ class Channel(callbacks.Privmsg):
c = ircdb.channels.getChannel(channel) c = ircdb.channels.getChannel(channel)
c.lobotomized = False c.lobotomized = False
ircdb.channels.setChannel(channel, c) ircdb.channels.setChannel(channel, c)
irc.replySuccess(msg) irc.replySuccess()
unlobotomize = privmsgs.checkChannelCapability(unlobotomize, 'op') unlobotomize = privmsgs.checkChannelCapability(unlobotomize, 'op')
def permban(self, irc, msg, args, channel): def permban(self, irc, msg, args, channel):
@ -316,12 +316,12 @@ class Channel(callbacks.Privmsg):
elif ircutils.isUserHostmask(arg): elif ircutils.isUserHostmask(arg):
banmask = arg banmask = arg
else: else:
irc.error(msg, 'That\'s not a valid nick or hostmask.') irc.error('That\'s not a valid nick or hostmask.')
return return
c = ircdb.channels.getChannel(channel) c = ircdb.channels.getChannel(channel)
c.addBan(banmask) c.addBan(banmask)
ircdb.channels.setChannel(channel, c) ircdb.channels.setChannel(channel, c)
irc.replySuccess(msg) irc.replySuccess()
permban = privmsgs.checkChannelCapability(permban, 'op') permban = privmsgs.checkChannelCapability(permban, 'op')
def unpermban(self, irc, msg, args, channel): def unpermban(self, irc, msg, args, channel):
@ -335,7 +335,7 @@ class Channel(callbacks.Privmsg):
c = ircdb.channels.getChannel(channel) c = ircdb.channels.getChannel(channel)
c.removeBan(banmask) c.removeBan(banmask)
ircdb.channels.setChannel(channel, c) ircdb.channels.setChannel(channel, c)
irc.replySuccess(msg) irc.replySuccess()
unpermban = privmsgs.checkChannelCapability(unpermban, 'op') unpermban = privmsgs.checkChannelCapability(unpermban, 'op')
def ignore(self, irc, msg, args, channel): def ignore(self, irc, msg, args, channel):
@ -352,12 +352,12 @@ class Channel(callbacks.Privmsg):
elif ircutils.isUserHostmask(arg): elif ircutils.isUserHostmask(arg):
banmask = arg banmask = arg
else: else:
irc.error(msg, 'That\'s not a valid nick or hostmask.') irc.error('That\'s not a valid nick or hostmask.')
return return
c = ircdb.channels.getChannel(channel) c = ircdb.channels.getChannel(channel)
c.addIgnore(banmask) c.addIgnore(banmask)
ircdb.channels.setChannel(channel, c) ircdb.channels.setChannel(channel, c)
irc.replySuccess(msg) irc.replySuccess()
ignore = privmsgs.checkChannelCapability(ignore, 'op') ignore = privmsgs.checkChannelCapability(ignore, 'op')
def unignore(self, irc, msg, args, channel): def unignore(self, irc, msg, args, channel):
@ -371,7 +371,7 @@ class Channel(callbacks.Privmsg):
c = ircdb.channels.getChannel(channel) c = ircdb.channels.getChannel(channel)
c.removeIgnore(banmask) c.removeIgnore(banmask)
ircdb.channels.setChannel(channel, c) ircdb.channels.setChannel(channel, c)
irc.replySuccess(msg) irc.replySuccess()
unignore = privmsgs.checkChannelCapability(unignore, 'op') unignore = privmsgs.checkChannelCapability(unignore, 'op')
def ignores(self, irc, msg, args, channel): def ignores(self, irc, msg, args, channel):
@ -386,11 +386,11 @@ class Channel(callbacks.Privmsg):
c = ircdb.channels.getChannel(channel) c = ircdb.channels.getChannel(channel)
if len(c.ignores) == 0: if len(c.ignores) == 0:
s = 'I\'m not currently ignoring any hostmasks in %r' % channel s = 'I\'m not currently ignoring any hostmasks in %r' % channel
irc.reply(msg, s) irc.reply(s)
else: else:
L = c.ignores[:] L = c.ignores[:]
L.sort() L.sort()
irc.reply(msg, utils.commaAndify(imap(repr, L))) irc.reply(utils.commaAndify(imap(repr, L)))
ignores = privmsgs.checkChannelCapability(ignores, 'op') ignores = privmsgs.checkChannelCapability(ignores, 'op')
@ -409,9 +409,9 @@ class Channel(callbacks.Privmsg):
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
user.addCapability(capability) user.addCapability(capability)
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.replySuccess(msg) irc.replySuccess()
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
addcapability = privmsgs.checkChannelCapability(addcapability,'op') addcapability = privmsgs.checkChannelCapability(addcapability,'op')
def removecapability(self, irc, msg, args, channel): def removecapability(self, irc, msg, args, channel):
@ -429,9 +429,9 @@ class Channel(callbacks.Privmsg):
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
user.removeCapability(capability) user.removeCapability(capability)
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.replySuccess(msg) irc.replySuccess()
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
removecapability = privmsgs.checkChannelCapability(removecapability, 'op') removecapability = privmsgs.checkChannelCapability(removecapability, 'op')
def setdefaultcapability(self, irc, msg, args, channel): def setdefaultcapability(self, irc, msg, args, channel):
@ -451,10 +451,10 @@ class Channel(callbacks.Privmsg):
c.setDefaultCapability(False) c.setDefaultCapability(False)
else: else:
s = 'The default value must be either True or False.' s = 'The default value must be either True or False.'
irc.error(msg, s) irc.error(s)
return return
ircdb.channels.setChannel(channel, c) ircdb.channels.setChannel(channel, c)
irc.replySuccess(msg) irc.replySuccess()
setdefaultcapability = \ setdefaultcapability = \
privmsgs.checkChannelCapability(setdefaultcapability, 'op') privmsgs.checkChannelCapability(setdefaultcapability, 'op')
@ -469,7 +469,7 @@ class Channel(callbacks.Privmsg):
c = ircdb.channels.getChannel(channel) c = ircdb.channels.getChannel(channel)
c.addCapability(capability) c.addCapability(capability)
ircdb.channels.setChannel(channel, c) ircdb.channels.setChannel(channel, c)
irc.replySuccess(msg) irc.replySuccess()
setcapability = privmsgs.checkChannelCapability(setcapability, 'op') setcapability = privmsgs.checkChannelCapability(setcapability, 'op')
def unsetcapability(self, irc, msg, args, channel): def unsetcapability(self, irc, msg, args, channel):
@ -484,7 +484,7 @@ class Channel(callbacks.Privmsg):
c = ircdb.channels.getChannel(channel) c = ircdb.channels.getChannel(channel)
c.removeCapability(capability) c.removeCapability(capability)
ircdb.channels.setChannel(channel, c) ircdb.channels.setChannel(channel, c)
irc.replySuccess(msg) irc.replySuccess()
unsetcapability = privmsgs.checkChannelCapability(unsetcapability, 'op') unsetcapability = privmsgs.checkChannelCapability(unsetcapability, 'op')
def capabilities(self, irc, msg, args): def capabilities(self, irc, msg, args):
@ -497,7 +497,7 @@ class Channel(callbacks.Privmsg):
c = ircdb.channels.getChannel(channel) c = ircdb.channels.getChannel(channel)
L = list(c.capabilities) L = list(c.capabilities)
L.sort() L.sort()
irc.reply(msg, '[%s]' % ', '.join(L)) irc.reply('[%s]' % ', '.join(L))
def lobotomies(self, irc, msg, args): def lobotomies(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -511,9 +511,9 @@ class Channel(callbacks.Privmsg):
if L: if L:
L.sort() L.sort()
s = 'I\'m currently lobotomized in %s.' % utils.commaAndify(L) s = 'I\'m currently lobotomized in %s.' % utils.commaAndify(L)
irc.reply(msg, s) irc.reply(s)
else: else:
irc.reply(msg, 'I\'m not currently lobotomized in any channels.') irc.reply('I\'m not currently lobotomized in any channels.')
Class = Channel Class = Channel

View File

@ -56,10 +56,10 @@ class Misc(callbacks.Privmsg):
self.log.debug('Misc.invalidCommand called (tokens %s)', tokens) self.log.debug('Misc.invalidCommand called (tokens %s)', tokens)
if conf.replyWhenNotCommand: if conf.replyWhenNotCommand:
command = tokens and tokens[0] or '' command = tokens and tokens[0] or ''
irc.error(msg, '%r is not a valid command.' % command) irc.error('%r is not a valid command.' % command)
else: else:
if not isinstance(irc.irc, irclib.Irc): if not isinstance(irc.irc, irclib.Irc):
irc.reply(msg, '[%s]' % ' '.join(tokens)) irc.reply('[%s]' % ' '.join(tokens))
def list(self, irc, msg, args): def list(self, irc, msg, args):
"""[--private] [<module name>] """[--private] [<module name>]
@ -79,14 +79,14 @@ class Misc(callbacks.Privmsg):
names = [cb.name() for cb in irc.callbacks names = [cb.name() for cb in irc.callbacks
if evenPrivate or (hasattr(cb, 'public') and cb.public)] if evenPrivate or (hasattr(cb, 'public') and cb.public)]
names.sort() names.sort()
irc.reply(msg, ', '.join(names)) irc.reply(', '.join(names))
else: else:
cb = irc.getCallback(name) cb = irc.getCallback(name)
if cb is None: if cb is None:
irc.error(msg, 'No such plugin %r exists.' % name) irc.error('No such plugin %r exists.' % name)
elif isinstance(cb, callbacks.PrivmsgRegexp) or \ elif isinstance(cb, callbacks.PrivmsgRegexp) or \
not isinstance(cb, callbacks.Privmsg): not isinstance(cb, callbacks.Privmsg):
irc.error(msg, 'That plugin exists, but it has no commands.') irc.error('That plugin exists, but it has no commands.')
else: else:
commands = [] commands = []
for s in dir(cb): for s in dir(cb):
@ -98,9 +98,9 @@ class Misc(callbacks.Privmsg):
commands.append(s) commands.append(s)
if commands: if commands:
commands.sort() commands.sort()
irc.reply(msg, ', '.join(commands)) irc.reply(', '.join(commands))
else: else:
irc.error(msg, 'That plugin exists, but it has no ' irc.error('That plugin exists, but it has no '
'commands with help.') 'commands with help.')
def apropos(self, irc, msg, args): def apropos(self, irc, msg, args):
@ -127,9 +127,9 @@ class Misc(callbacks.Privmsg):
L.append('%s %s' % (name, key)) L.append('%s %s' % (name, key))
if L: if L:
L.sort() L.sort()
irc.reply(msg, utils.commaAndify(L)) irc.reply(utils.commaAndify(L))
else: else:
irc.error(msg, 'No appropriate commands were found.') irc.error('No appropriate commands were found.')
def help(self, irc, msg, args): def help(self, irc, msg, args):
"""[<plugin>] <command> """[<plugin>] <command>
@ -139,9 +139,9 @@ class Misc(callbacks.Privmsg):
""" """
def getHelp(method, name=None): def getHelp(method, name=None):
if hasattr(method, '__doc__') and method.__doc__: if hasattr(method, '__doc__') and method.__doc__:
irc.reply(msg, callbacks.getHelp(method, name=name)) irc.reply(callbacks.getHelp(method, name=name))
else: else:
irc.error(msg, '%s has no help.' % name) irc.error('%s has no help.' % name)
if len(args) > 1: if len(args) > 1:
cb = irc.getCallback(args[0]) cb = irc.getCallback(args[0])
if cb is not None: if cb is not None:
@ -152,9 +152,9 @@ class Misc(callbacks.Privmsg):
method = getattr(cb, command) method = getattr(cb, command)
getHelp(method, name) getHelp(method, name)
else: else:
irc.error(msg, 'There is no such command %s.' % name) irc.error('There is no such command %s.' % name)
else: else:
irc.error(msg, 'There is no such plugin %s' % args[0]) irc.error('There is no such plugin %s' % args[0])
return return
command = callbacks.canonicalName(privmsgs.getArgs(args)) command = callbacks.canonicalName(privmsgs.getArgs(args))
# Users might expect "@help @list" to work. # Users might expect "@help @list" to work.
@ -168,7 +168,7 @@ class Misc(callbacks.Privmsg):
if ambiguous: if ambiguous:
names = [cb.name() for cb in cbs] names = [cb.name() for cb in cbs]
names.sort() names.sort()
irc.error(msg, 'That command exists in the %s plugins. ' irc.error('That command exists in the %s plugins. '
'Please specify exactly which plugin command ' 'Please specify exactly which plugin command '
'you want help with.'% utils.commaAndify(names)) 'you want help with.'% utils.commaAndify(names))
return return
@ -178,7 +178,7 @@ class Misc(callbacks.Privmsg):
method = getattr(cb, tokens[1]) method = getattr(cb, tokens[1])
getHelp(method) getHelp(method)
elif not cbs: elif not cbs:
irc.error(msg, 'There is no such command %s.' % command) irc.error('There is no such command %s.' % command)
else: else:
cb = cbs[0] cb = cbs[0]
method = getattr(cb, command) method = getattr(cb, command)
@ -193,18 +193,18 @@ class Misc(callbacks.Privmsg):
nick = privmsgs.getArgs(args, required=0, optional=1) nick = privmsgs.getArgs(args, required=0, optional=1)
if nick: if nick:
try: try:
irc.reply(msg, irc.state.nickToHostmask(nick)) irc.reply(irc.state.nickToHostmask(nick))
except KeyError: except KeyError:
irc.error(msg, 'I haven\'t seen anyone named %r' % nick) irc.error('I haven\'t seen anyone named %r' % nick)
else: else:
irc.reply(msg, msg.prefix) irc.reply(msg.prefix)
def version(self, irc, msg, args): def version(self, irc, msg, args):
"""takes no arguments """takes no arguments
Returns the version of the current bot. Returns the version of the current bot.
""" """
irc.reply(msg, conf.version) irc.reply(conf.version)
def revision(self, irc, msg, args): def revision(self, irc, msg, args):
"""[<module>] """[<module>]
@ -220,12 +220,12 @@ class Misc(callbacks.Privmsg):
modules[moduleName.lower()] = moduleName modules[moduleName.lower()] = moduleName
module = sys.modules[modules[name.lower()]] module = sys.modules[modules[name.lower()]]
except KeyError: except KeyError:
irc.error(msg, 'I couldn\'t find a module named %s' % name) irc.error('I couldn\'t find a module named %s' % name)
return return
if hasattr(module, '__revision__'): if hasattr(module, '__revision__'):
irc.reply(msg, module.__revision__) irc.reply(module.__revision__)
else: else:
irc.error(msg, 'Module %s has no __revision__.' % name) irc.error('Module %s has no __revision__.' % name)
else: else:
def getVersion(s): def getVersion(s):
try: try:
@ -244,14 +244,14 @@ class Misc(callbacks.Privmsg):
names[name] = getVersion(module.__revision__) names[name] = getVersion(module.__revision__)
break break
L = ['%s: %s' % (k, v) for (k, v) in names.items()] L = ['%s: %s' % (k, v) for (k, v) in names.items()]
irc.reply(msg, utils.commaAndify(L)) irc.reply(utils.commaAndify(L))
def source(self, irc, msg, args): def source(self, irc, msg, args):
"""takes no arguments """takes no arguments
Returns a URL saying where to get SupyBot. Returns a URL saying where to get SupyBot.
""" """
irc.reply(msg, 'My source is at http://supybot.sf.net/') irc.reply('My source is at http://supybot.sf.net/')
def logfilesize(self, irc, msg, args): def logfilesize(self, irc, msg, args):
"""[<logfile>] """[<logfile>]
@ -262,7 +262,7 @@ class Misc(callbacks.Privmsg):
filenameArg = privmsgs.getArgs(args, required=0, optional=1) filenameArg = privmsgs.getArgs(args, required=0, optional=1)
if filenameArg: if filenameArg:
if not filenameArg.endswith('.log'): if not filenameArg.endswith('.log'):
irc.error(msg, 'That filename doesn\'t appear to be a log.') irc.error('That filename doesn\'t appear to be a log.')
return return
filenameArg = os.path.basename(filenameArg) filenameArg = os.path.basename(filenameArg)
ret = [] ret = []
@ -278,16 +278,16 @@ class Misc(callbacks.Privmsg):
ret.append('%s: %s' % (filename, stats.st_size)) ret.append('%s: %s' % (filename, stats.st_size))
if ret: if ret:
ret.sort() ret.sort()
irc.reply(msg, utils.commaAndify(ret)) irc.reply(utils.commaAndify(ret))
else: else:
irc.error(msg, 'I couldn\'t find any logfiles.') irc.error('I couldn\'t find any logfiles.')
def getprefixchar(self, irc, msg, args): def getprefixchar(self, irc, msg, args):
"""takes no arguments """takes no arguments
Returns the prefix character(s) the bot is currently using. Returns the prefix character(s) the bot is currently using.
""" """
irc.reply(msg, repr(conf.prefixChars)) irc.reply(repr(conf.prefixChars))
def plugin(self, irc, msg, args): def plugin(self, irc, msg, args):
"""<command> """<command>
@ -297,9 +297,9 @@ class Misc(callbacks.Privmsg):
command = callbacks.canonicalName(privmsgs.getArgs(args)) command = callbacks.canonicalName(privmsgs.getArgs(args))
cbs = callbacks.findCallbackForCommand(irc, command) cbs = callbacks.findCallbackForCommand(irc, command)
if cbs: if cbs:
irc.reply(msg, utils.commaAndify([cb.name() for cb in cbs])) irc.reply(utils.commaAndify([cb.name() for cb in cbs]))
else: else:
irc.error(msg, 'There is no such command %s' % command) irc.error('There is no such command %s' % command)
def more(self, irc, msg, args): def more(self, irc, msg, args):
"""[<nick>] """[<nick>]
@ -317,10 +317,10 @@ class Misc(callbacks.Privmsg):
if not private: if not private:
self._mores[userHostmask] = L[:] self._mores[userHostmask] = L[:]
else: else:
irc.error(msg, '%s has no public mores.' % nick) irc.error('%s has no public mores.' % nick)
return return
except KeyError: except KeyError:
irc.error(msg, 'Sorry, I can\'t find a hostmask for %s' % nick) irc.error('Sorry, I can\'t find a hostmask for %s' % nick)
return return
try: try:
L = self._mores[userHostmask] L = self._mores[userHostmask]
@ -328,11 +328,11 @@ class Misc(callbacks.Privmsg):
if L: if L:
chunk += ' \x02(%s)\x0F' % \ chunk += ' \x02(%s)\x0F' % \
utils.nItems('message', len(L), 'more') utils.nItems('message', len(L), 'more')
irc.reply(msg, chunk, True) irc.reply(chunk, True)
except KeyError: except KeyError:
irc.error(msg, 'You haven\'t asked me a command!') irc.error('You haven\'t asked me a command!')
except IndexError: except IndexError:
irc.error(msg, 'That\'s all, there is no more.') irc.error('That\'s all, there is no more.')
def _validLastMsg(self, msg): def _validLastMsg(self, msg):
return msg.prefix and \ return msg.prefix and \
@ -374,7 +374,7 @@ class Misc(callbacks.Privmsg):
return r.search(m.args[1]) return r.search(m.args[1])
predicates.setdefault('regexp', []).append(f) predicates.setdefault('regexp', []).append(f)
except ValueError, e: except ValueError, e:
irc.error(msg, str(e)) irc.error(str(e))
return return
iterable = ifilter(self._validLastMsg, reviter(irc.state.history)) iterable = ifilter(self._validLastMsg, reviter(irc.state.history))
iterable.next() # Drop the first message. iterable.next() # Drop the first message.
@ -384,9 +384,9 @@ class Misc(callbacks.Privmsg):
if not predicate(m): if not predicate(m):
break break
else: else:
irc.reply(msg, ircmsgs.prettyPrint(m)) irc.reply(ircmsgs.prettyPrint(m))
return return
irc.error(msg, 'I couldn\'t find a message matching that criteria in ' irc.error('I couldn\'t find a message matching that criteria in '
'my history of %s messages.' % len(irc.state.history)) 'my history of %s messages.' % len(irc.state.history))
def seconds(self, irc, msg, args): def seconds(self, irc, msg, args):
@ -408,7 +408,7 @@ class Misc(callbacks.Privmsg):
try: try:
i = int(s) i = int(s)
except ValueError: except ValueError:
irc.error(msg, 'Invalid argument: %s' % arg) irc.error('Invalid argument: %s' % arg)
return return
if kind == 'd': if kind == 'd':
seconds += i*86400 seconds += i*86400
@ -418,7 +418,7 @@ class Misc(callbacks.Privmsg):
seconds += i*60 seconds += i*60
elif kind == 's': elif kind == 's':
seconds += i seconds += i
irc.reply(msg, str(seconds)) irc.reply(str(seconds))
def tell(self, irc, msg, args): def tell(self, irc, msg, args):
"""<nick|channel> <text> """<nick|channel> <text>
@ -428,10 +428,10 @@ class Misc(callbacks.Privmsg):
""" """
(target, text) = privmsgs.getArgs(args, required=2) (target, text) = privmsgs.getArgs(args, required=2)
if not ircutils.isNick(target) and not ircutils.isChannel(target): if not ircutils.isNick(target) and not ircutils.isChannel(target):
irc.error(msg, '%s is not a valid nick or channel.' % target) irc.error('%s is not a valid nick or channel.' % target)
return return
s = '%s wants me to tell you: %s' % (msg.nick, text) s = '%s wants me to tell you: %s' % (msg.nick, text)
irc.reply(msg, s, to=target, private=True) irc.reply(s, to=target, private=True)
def private(self, irc, msg, args): def private(self, irc, msg, args):
"""<text> """<text>
@ -440,7 +440,7 @@ class Misc(callbacks.Privmsg):
here. here.
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
irc.reply(msg, text, private=True) irc.reply(text, private=True)
def action(self, irc, msg, args): def action(self, irc, msg, args):
"""<text> """<text>
@ -460,7 +460,7 @@ class Misc(callbacks.Privmsg):
benefit here. benefit here.
""" """
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
irc.reply(msg, text, notice=True) irc.reply(text, notice=True)
Class = Misc Class = Misc

View File

@ -183,7 +183,7 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
command = callbacks.canonicalName(command) command = callbacks.canonicalName(command)
cbs = callbacks.findCallbackForCommand(irc, command) cbs = callbacks.findCallbackForCommand(irc, command)
if not cbs: if not cbs:
irc.error(msg, 'That\'t not a valid command.') irc.error('That\'t not a valid command.')
return return
if plugin: if plugin:
self.defaultPlugins[command] = plugin self.defaultPlugins[command] = plugin
@ -197,11 +197,11 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
if d: if d:
raise KeyError raise KeyError
assert len(L) == 2, 'Not disambiguated!' assert len(L) == 2, 'Not disambiguated!'
irc.reply(msg, L[0]) irc.reply(L[0])
except KeyError: except KeyError:
irc.error(msg,'I have no default plugin for that command.') irc.error('I have no default plugin for that command.')
return return
irc.replySuccess(msg) irc.replySuccess()
def eval(self, irc, msg, args): def eval(self, irc, msg, args):
"""<expression> """<expression>
@ -211,13 +211,13 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
if conf.allowEval: if conf.allowEval:
s = privmsgs.getArgs(args) s = privmsgs.getArgs(args)
try: try:
irc.reply(msg, repr(eval(s))) irc.reply(repr(eval(s)))
except SyntaxError, e: except SyntaxError, e:
irc.reply(msg, '%s: %r' % (utils.exnToString(e), s)) irc.reply('%s: %r' % (utils.exnToString(e), s))
except Exception, e: except Exception, e:
irc.reply(msg, utils.exnToString(e)) irc.reply(utils.exnToString(e))
else: else:
irc.error(msg, conf.replyEvalNotAllowed) irc.error(conf.replyEvalNotAllowed)
def _exec(self, irc, msg, args): def _exec(self, irc, msg, args):
"""<statement> """<statement>
@ -228,11 +228,11 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
s = privmsgs.getArgs(args) s = privmsgs.getArgs(args)
try: try:
exec s exec s
irc.replySuccess(msg) irc.replySuccess()
except Exception, e: except Exception, e:
irc.reply(msg, utils.exnToString(e)) irc.reply(utils.exnToString(e))
else: else:
irc.error(msg, conf.replyEvalNotAllowed) irc.error(conf.replyEvalNotAllowed)
def setconf(self, irc, msg, args): def setconf(self, irc, msg, args):
"""[<name> [<value>]] """[<name> [<value>]]
@ -247,26 +247,26 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
try: try:
value = eval(value) value = eval(value)
except Exception, e: except Exception, e:
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
return return
setattr(conf, name, value) setattr(conf, name, value)
irc.replySuccess(msg) irc.replySuccess()
else: else:
if name == 'allowEval': if name == 'allowEval':
irc.error(msg, 'You can\'t set the value of allowEval.') irc.error('You can\'t set the value of allowEval.')
return return
elif name not in conf.types: elif name not in conf.types:
irc.error(msg, 'I can\'t set that conf variable.') irc.error('I can\'t set that conf variable.')
return return
else: else:
converter = conf.types[name] converter = conf.types[name]
try: try:
value = converter(value) value = converter(value)
except ValueError, e: except ValueError, e:
irc.error(msg, str(e)) irc.error(str(e))
return return
setattr(conf, name, value) setattr(conf, name, value)
irc.replySuccess(msg) irc.replySuccess()
elif name: elif name:
typeNames = {conf.mystr: 'string', typeNames = {conf.mystr: 'string',
conf.mybool: 'boolean', conf.mybool: 'boolean',
@ -274,17 +274,17 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
try: try:
type = typeNames[conf.types[name]] type = typeNames[conf.types[name]]
except KeyError: except KeyError:
irc.error(msg, 'That configuration variable doesn\'t exist.') irc.error('That configuration variable doesn\'t exist.')
return return
try: try:
value = getattr(conf, name) value = getattr(conf, name)
irc.reply(msg, '%s is a %s (%s).' % (name, type, value)) irc.reply('%s is a %s (%s).' % (name, type, value))
except KeyError: except KeyError:
irc.error(msg, '%s is of an unknown type.' % name) irc.error('%s is of an unknown type.' % name)
else: else:
options = conf.types.keys() options = conf.types.keys()
options.sort() options.sort()
irc.reply(msg, ', '.join(options)) irc.reply(', '.join(options))
def setdefaultcapability(self, irc, msg, args): def setdefaultcapability(self, irc, msg, args):
"""<capability> """<capability>
@ -293,7 +293,7 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
""" """
capability = callbacks.canonicalName(privmsgs.getArgs(args)) capability = callbacks.canonicalName(privmsgs.getArgs(args))
conf.defaultCapabilities.add(capability) conf.defaultCapabilities.add(capability)
irc.replySuccess(msg) irc.replySuccess()
def unsetdefaultcapability(self, irc, msg, args): def unsetdefaultcapability(self, irc, msg, args):
"""<capability> """<capability>
@ -302,7 +302,7 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
""" """
capability = callbacks.canonicalName(privmsgs.getArgs(args)) capability = callbacks.canonicalName(privmsgs.getArgs(args))
conf.defaultCapabilities.remove(capability) conf.defaultCapabilities.remove(capability)
irc.replySuccess(msg) irc.replySuccess()
def ircquote(self, irc, msg, args): def ircquote(self, irc, msg, args):
"""<string to be sent to the server> """<string to be sent to the server>
@ -313,7 +313,7 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
try: try:
m = ircmsgs.IrcMsg(s) m = ircmsgs.IrcMsg(s)
except Exception, e: except Exception, e:
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
else: else:
irc.queueMsg(m) irc.queueMsg(m)
@ -339,7 +339,7 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
Runs all the periodic flushers in world.flushers. Runs all the periodic flushers in world.flushers.
""" """
world.flush() world.flush()
irc.replySuccess(msg) irc.replySuccess()
def upkeep(self, irc, msg, args): def upkeep(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -348,9 +348,9 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
""" """
collected = world.upkeep() collected = world.upkeep()
if gc.garbage: if gc.garbage:
irc.reply(msg, 'Garbage! %r' % gc.garbage) irc.reply('Garbage! %r' % gc.garbage)
else: else:
irc.reply(msg, '%s collected.' % utils.nItems('object', collected)) irc.reply('%s collected.' % utils.nItems('object', collected))
def set(self, irc, msg, args): def set(self, irc, msg, args):
"""<name> <value> """<name> <value>
@ -361,7 +361,7 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
""" """
(name, value) = privmsgs.getArgs(args, optional=1) (name, value) = privmsgs.getArgs(args, optional=1)
world.tempvars[name] = value world.tempvars[name] = value
irc.replySuccess(msg) irc.replySuccess()
def unset(self, irc, msg, args): def unset(self, irc, msg, args):
"""<name> """<name>
@ -371,9 +371,9 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
name = privmsgs.getArgs(args) name = privmsgs.getArgs(args)
try: try:
del world.tempvars[name] del world.tempvars[name]
irc.replySuccess(msg) irc.replySuccess()
except KeyError: except KeyError:
irc.error(msg, 'That variable wasn\'t set.') irc.error('That variable wasn\'t set.')
def load(self, irc, msg, args): def load(self, irc, msg, args):
"""<plugin> """<plugin>
@ -385,18 +385,18 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
""" """
name = privmsgs.getArgs(args) name = privmsgs.getArgs(args)
if irc.getCallback(name): if irc.getCallback(name):
irc.error(msg, 'That module is already loaded.') irc.error('That module is already loaded.')
return return
try: try:
module = loadPluginModule(name) module = loadPluginModule(name)
except ImportError, e: except ImportError, e:
if name in str(e): if name in str(e):
irc.error(msg, 'No plugin %s exists.' % name) irc.error('No plugin %s exists.' % name)
else: else:
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
return return
loadPluginClass(irc, module) loadPluginClass(irc, module)
irc.replySuccess(msg) irc.replySuccess()
def reload(self, irc, msg, args): def reload(self, irc, msg, args):
"""<plugin> """<plugin>
@ -419,13 +419,13 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
del callback del callback
gc.collect() gc.collect()
callback = loadPluginClass(irc, module) callback = loadPluginClass(irc, module)
irc.replySuccess(msg) irc.replySuccess()
except ImportError: except ImportError:
for callback in callbacks: for callback in callbacks:
irc.addCallback(callback) irc.addCallback(callback)
irc.error(msg, 'No plugin %s exists.' % name) irc.error('No plugin %s exists.' % name)
else: else:
irc.error(msg, 'There was no callback %s.' % name) irc.error('There was no callback %s.' % name)
def unload(self, irc, msg, args): def unload(self, irc, msg, args):
"""<plugin> """<plugin>
@ -440,9 +440,9 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
callback.die() callback.die()
del callback del callback
gc.collect() gc.collect()
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, 'There was no callback %s' % name) irc.error('There was no callback %s' % name)
def reconf(self, irc, msg, args): def reconf(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -452,7 +452,7 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
""" """
ircdb.users.reload() ircdb.users.reload()
ircdb.channels.reload() ircdb.channels.reload()
irc.replySuccess(msg) irc.replySuccess()
Class = Owner Class = Owner

View File

@ -74,12 +74,12 @@ class User(callbacks.Privmsg):
users = [u.name for u in ircdb.users if p(u.name)] users = [u.name for u in ircdb.users if p(u.name)]
if users: if users:
utils.sortBy(str.lower, users) utils.sortBy(str.lower, users)
irc.reply(msg, utils.commaAndify(users)) irc.reply(utils.commaAndify(users))
else: else:
if glob: if glob:
irc.reply(msg, 'There are no matching registered users.') irc.reply('There are no matching registered users.')
else: else:
irc.reply(msg, 'There are no registered users.') irc.reply('There are no registered users.')
def register(self, irc, msg, args): def register(self, irc, msg, args):
"""[--hashed] <name> <password> """[--hashed] <name> <password>
@ -99,16 +99,16 @@ class User(callbacks.Privmsg):
self._checkNotChannel(irc, msg, password) self._checkNotChannel(irc, msg, password)
try: try:
ircdb.users.getUserId(name) ircdb.users.getUserId(name)
irc.error(msg, 'That name is already assigned to someone.') irc.error('That name is already assigned to someone.')
return return
except KeyError: except KeyError:
pass pass
if ircutils.isUserHostmask(name): if ircutils.isUserHostmask(name):
irc.error(msg, 'Hostmasks aren\'t valid usernames.') irc.error('Hostmasks aren\'t valid usernames.')
return return
try: try:
u = ircdb.users.getUser(msg.prefix) u = ircdb.users.getUser(msg.prefix)
irc.error(msg,'Your hostmask is already registered to %s' % u.name) irc.error('Your hostmask is already registered to %s' % u.name)
return return
except KeyError: except KeyError:
pass pass
@ -117,7 +117,7 @@ class User(callbacks.Privmsg):
user.setPassword(password, hashed=hashed) user.setPassword(password, hashed=hashed)
user.addHostmask(msg.prefix) user.addHostmask(msg.prefix)
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.replySuccess(msg) irc.replySuccess()
def unregister(self, irc, msg, args): def unregister(self, irc, msg, args):
"""<name> <password> """<name> <password>
@ -130,13 +130,13 @@ class User(callbacks.Privmsg):
id = ircdb.users.getUserId(name) id = ircdb.users.getUserId(name)
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
except KeyError: except KeyError:
irc.error(msg, 'That username isn\'t registered.') irc.error('That username isn\'t registered.')
return return
if user.checkPassword(password): if user.checkPassword(password):
ircdb.users.delUser(id) ircdb.users.delUser(id)
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, conf.replyIncorrectAuth) irc.error(conf.replyIncorrectAuth)
def changename(self, irc, msg, args): def changename(self, irc, msg, args):
"""<name> <new name> [<password>] """<name> <new name> [<password>]
@ -152,18 +152,18 @@ class User(callbacks.Privmsg):
id = ircdb.users.getUserId(name) id = ircdb.users.getUserId(name)
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
except KeyError: except KeyError:
irc.error(msg, 'That username isn\'t registered.') irc.error('That username isn\'t registered.')
return return
try: try:
id = ircdb.users.getUserId(newname) id = ircdb.users.getUserId(newname)
irc.error(msg, '%r is already registered.' % newname) irc.error('%r is already registered.' % newname)
return return
except KeyError: except KeyError:
pass pass
if user.checkHostmask(msg.prefix) or user.checkPassword(password): if user.checkHostmask(msg.prefix) or user.checkPassword(password):
user.name = newname user.name = newname
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.replySuccess(msg) irc.replySuccess()
def addhostmask(self, irc, msg, args): def addhostmask(self, irc, msg, args):
"""<name> <hostmask> [<password>] """<name> <hostmask> [<password>]
@ -176,32 +176,32 @@ class User(callbacks.Privmsg):
(name, hostmask, password) = privmsgs.getArgs(args, 2, 1) (name, hostmask, password) = privmsgs.getArgs(args, 2, 1)
self._checkNotChannel(irc, msg, password) self._checkNotChannel(irc, msg, password)
if not ircutils.isUserHostmask(hostmask): if not ircutils.isUserHostmask(hostmask):
irc.error(msg, 'That\'s not a valid hostmask.') irc.error('That\'s not a valid hostmask.')
return return
s = hostmask.translate(string.ascii, '!@*?') s = hostmask.translate(string.ascii, '!@*?')
if len(s) < 10: if len(s) < 10:
s = 'Hostmask must contain more than 10 non-wildcard characters.' s = 'Hostmask must contain more than 10 non-wildcard characters.'
irc.error(msg, s) irc.error(s)
return return
try: try:
id = ircdb.users.getUserId(name) id = ircdb.users.getUserId(name)
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
try: try:
otherId = ircdb.users.getUserId(hostmask) otherId = ircdb.users.getUserId(hostmask)
if otherId != id: if otherId != id:
irc.error(msg, 'That hostmask is already registered.') irc.error('That hostmask is already registered.')
return return
except KeyError: except KeyError:
pass pass
if user.checkHostmask(msg.prefix) or user.checkPassword(password): if user.checkHostmask(msg.prefix) or user.checkPassword(password):
user.addHostmask(hostmask) user.addHostmask(hostmask)
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, conf.replyIncorrectAuth) irc.error(conf.replyIncorrectAuth)
return return
def removehostmask(self, irc, msg, args): def removehostmask(self, irc, msg, args):
@ -218,18 +218,18 @@ class User(callbacks.Privmsg):
id = ircdb.users.getUserId(name) id = ircdb.users.getUserId(name)
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
if user.checkHostmask(msg.prefix) or user.checkPassword(password): if user.checkHostmask(msg.prefix) or user.checkPassword(password):
try: try:
user.removeHostmask(hostmask) user.removeHostmask(hostmask)
except ValueError: except ValueError:
irc.error(msg, 'There was no such hostmask.') irc.error('There was no such hostmask.')
return return
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, conf.replyIncorrectAuth) irc.error(conf.replyIncorrectAuth)
return return
def setpassword(self, irc, msg, args): def setpassword(self, irc, msg, args):
@ -251,14 +251,14 @@ class User(callbacks.Privmsg):
id = ircdb.users.getUserId(name) id = ircdb.users.getUserId(name)
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
if user.checkPassword(oldpassword): if user.checkPassword(oldpassword):
user.setPassword(newpassword, hashed=hashed) user.setPassword(newpassword, hashed=hashed)
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.replySuccess(msg) irc.replySuccess()
else: else:
irc.error(msg, conf.replyIncorrectAuth) irc.error(conf.replyIncorrectAuth)
def username(self, irc, msg, args): def username(self, irc, msg, args):
"""<hostmask|nick> """<hostmask|nick>
@ -271,13 +271,13 @@ class User(callbacks.Privmsg):
try: try:
hostmask = irc.state.nickToHostmask(hostmask) hostmask = irc.state.nickToHostmask(hostmask)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
try: try:
user = ircdb.users.getUser(hostmask) user = ircdb.users.getUser(hostmask)
irc.reply(msg, user.name) irc.reply(user.name)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
def hostmasks(self, irc, msg, args): def hostmasks(self, irc, msg, args):
"""[<name>] """[<name>]
@ -286,24 +286,24 @@ class User(callbacks.Privmsg):
specified, returns the hostmasks of the user calling the command. specified, returns the hostmasks of the user calling the command.
""" """
if ircutils.isChannel(msg.args[0]): if ircutils.isChannel(msg.args[0]):
irc.error(msg, conf.replyRequiresPrivacy) irc.error(conf.replyRequiresPrivacy)
return return
name = privmsgs.getArgs(args, required=0, optional=1) name = privmsgs.getArgs(args, required=0, optional=1)
try: try:
user = ircdb.users.getUser(msg.prefix) user = ircdb.users.getUser(msg.prefix)
if name: if name:
if name != user.name and not user.checkCapability('owner'): if name != user.name and not user.checkCapability('owner'):
irc.error(msg, 'You may only retrieve your own hostmasks.') irc.error('You may only retrieve your own hostmasks.')
else: else:
try: try:
user = ircdb.users.getUser(name) user = ircdb.users.getUser(name)
irc.reply(msg, repr(user.hostmasks)) irc.reply(repr(user.hostmasks))
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
else: else:
irc.reply(msg, repr(user.hostmasks)) irc.reply(repr(user.hostmasks))
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
def capabilities(self, irc, msg, args): def capabilities(self, irc, msg, args):
"""[<name>] """[<name>]
@ -317,9 +317,9 @@ class User(callbacks.Privmsg):
name = privmsgs.getArgs(args) name = privmsgs.getArgs(args)
try: try:
user = ircdb.users.getUser(name) user = ircdb.users.getUser(name)
irc.reply(msg, '[%s]' % ', '.join(user.capabilities)) irc.reply('[%s]' % ', '.join(user.capabilities))
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
def identify(self, irc, msg, args): def identify(self, irc, msg, args):
"""<name> <password> """<name> <password>
@ -334,18 +334,18 @@ class User(callbacks.Privmsg):
id = ircdb.users.getUserId(name) id = ircdb.users.getUserId(name)
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
if user.checkPassword(password): if user.checkPassword(password):
try: try:
user.setAuth(msg.prefix) user.setAuth(msg.prefix)
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.replySuccess(msg) irc.replySuccess()
except ValueError: except ValueError:
irc.error(msg, 'Your secure flag is true and your hostmask ' irc.error('Your secure flag is true and your hostmask '
'doesn\'t match any of your known hostmasks.') 'doesn\'t match any of your known hostmasks.')
else: else:
irc.error(msg, conf.replyIncorrectAuth) irc.error(conf.replyIncorrectAuth)
def unidentify(self, irc, msg, args): def unidentify(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -356,11 +356,11 @@ class User(callbacks.Privmsg):
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
except KeyError: except KeyError:
irc.error(msg, conf.replyNoUser) irc.error(conf.replyNoUser)
return return
user.unsetAuth() user.unsetAuth()
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.replySuccess(msg) irc.replySuccess()
def whoami(self, irc, msg, args): def whoami(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -369,9 +369,9 @@ class User(callbacks.Privmsg):
""" """
try: try:
user = ircdb.users.getUser(msg.prefix) user = ircdb.users.getUser(msg.prefix)
irc.reply(msg, user.name) irc.reply(user.name)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
def setsecure(self, irc, msg, args): def setsecure(self, irc, msg, args):
"""<password> [<True|False>] """<password> [<True|False>]
@ -389,21 +389,21 @@ class User(callbacks.Privmsg):
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
user = ircdb.users.getUser(id) user = ircdb.users.getUser(id)
except KeyError: except KeyError:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
if value == '': if value == '':
value = not user.secure value = not user.secure
elif value.lower() in ('true', 'false'): elif value.lower() in ('true', 'false'):
value = eval(value.capitalize()) value = eval(value.capitalize())
else: else:
irc.error(msg, '%s is not a valid boolean value.' % value) irc.error('%s is not a valid boolean value.' % value)
return return
if user.checkPassword(password) and \ if user.checkPassword(password) and \
user.checkHostmask(msg.prefix, useAuth=False): user.checkHostmask(msg.prefix, useAuth=False):
user.secure = value user.secure = value
ircdb.users.setUser(id, user) ircdb.users.setUser(id, user)
irc.reply(msg, 'Secure flag set to %s' % value) irc.reply('Secure flag set to %s' % value)
else: else:
irc.error(msg, conf.replyIncorrectAuth) irc.error(conf.replyIncorrectAuth)
Class = User Class = User

View File

@ -296,28 +296,28 @@ class RichReplyMethods(object):
s = prefix s = prefix
return s return s
def replySuccess(self, msg, s='', **kwargs): def replySuccess(self, s='', **kwargs):
self.reply(msg, self._makeReply(conf.replySuccess, s), **kwargs) self.reply(self._makeReply(conf.replySuccess, s), **kwargs)
def replyNoCapability(self, msg, capability, s='', **kwargs): def replyNoCapability(self, capability, s='', **kwargs):
s = self._makeReply(conf.replyNoCapability % s, s) s = self._makeReply(conf.replyNoCapability % s, s)
self.reply(msg, s, **kwargs) self.reply(s, **kwargs)
def replyNotRegistered(self, msg, s='', **kwargs): def replyNotRegistered(self, s='', **kwargs):
self.reply(msg, self._makeReply(conf.replyNotRegistered, s), **kwargs) self.reply(self._makeReply(conf.replyNotRegistered, s), **kwargs)
def replyPossibleBug(self, msg, s='', **kwargs): def replyPossibleBug(self, s='', **kwargs):
self.reply(msg, self._makeReply(conf.replyPossibleBug, s), **kwargs) self.reply(self._makeReply(conf.replyPossibleBug, s), **kwargs)
def replyNoUser(self, msg, s='', **kwargs): def replyNoUser(self, s='', **kwargs):
self.reply(msg, self._makeReply(conf.replyNoUser, s), **kwargs) self.reply(self._makeReply(conf.replyNoUser, s), **kwargs)
def replyRequiresPrivacy(self, msg, s='', **kwargs): def replyRequiresPrivacy(self, s='', **kwargs):
s = self._makeReply(conf.replyRequiresPrivacy, s) s = self._makeReply(conf.replyRequiresPrivacy, s)
self.reply(msg, s, **kwargs) self.reply(s, **kwargs)
def replyError(self, msg, s='', **kwargs): def replyError(self, s='', **kwargs):
self.reply(msg, self._makeReply(conf.replyError, s), **kwargs) self.reply(self._makeReply(conf.replyError, s), **kwargs)
class IrcObjectProxy(RichReplyMethods): class IrcObjectProxy(RichReplyMethods):
@ -412,7 +412,7 @@ class IrcObjectProxy(RichReplyMethods):
del self.args[0] del self.args[0]
cb = cbs[0] cb = cbs[0]
if not checkCommandCapability(self.msg, name): if not checkCommandCapability(self.msg, name):
self.error(self.msg, conf.replyNoCapability % name) self.error(conf.replyNoCapability % name)
return return
command = getattr(cb, name) command = getattr(cb, name)
Privmsg.handled = True Privmsg.handled = True
@ -423,14 +423,14 @@ class IrcObjectProxy(RichReplyMethods):
else: else:
cb.callCommand(command, self, self.msg, self.args) cb.callCommand(command, self, self.msg, self.args)
except (getopt.GetoptError, ArgumentError): except (getopt.GetoptError, ArgumentError):
self.reply(self.msg, formatArgumentError(command, name=name)) self.reply(formatArgumentError(command, name=name))
except CannotNest, e: except CannotNest, e:
if not isinstance(self.irc, irclib.Irc): if not isinstance(self.irc, irclib.Irc):
self.error(self.msg, 'Command %r cannot be nested.' % name) self.error('Command %r cannot be nested.' % name)
def reply(self, msg, s, noLengthCheck=False, prefixName=True, def reply(self, s, noLengthCheck=False, prefixName=True,
action=False, private=False, notice=False, to=None): action=False, private=False, notice=False, to=None):
"""reply(msg, s) -> replies to msg with s """reply(s) -> replies to msg with s
Keyword arguments: Keyword arguments:
noLengthCheck=False: True if the length shouldn't be checked noLengthCheck=False: True if the length shouldn't be checked
@ -447,6 +447,7 @@ class IrcObjectProxy(RichReplyMethods):
# These use |= or &= based on whether or not they default to True or # These use |= or &= based on whether or not they default to True or
# False. Those that default to True use &=; those that default to # False. Those that default to True use &=; those that default to
# False use |=. # False use |=.
msg = self.msg
self.action |= action self.action |= action
self.notice |= notice self.notice |= notice
self.private |= private self.private |= private
@ -455,7 +456,7 @@ class IrcObjectProxy(RichReplyMethods):
self.noLengthCheck |= noLengthCheck self.noLengthCheck |= noLengthCheck
if self.finalEvaled: if self.finalEvaled:
if isinstance(self.irc, self.__class__): if isinstance(self.irc, self.__class__):
self.irc.reply(msg, s, self.noLengthCheck, self.prefixName, self.irc.reply(s, self.noLengthCheck, self.prefixName,
self.action, self.private, self.notice, self.to) self.action, self.private, self.notice, self.to)
elif self.noLengthCheck: elif self.noLengthCheck:
self.irc.queueMsg(reply(msg, s, self.prefixName, self.irc.queueMsg(reply(msg, s, self.prefixName,
@ -501,20 +502,20 @@ class IrcObjectProxy(RichReplyMethods):
self.args[self.counter] = s self.args[self.counter] = s
self.evalArgs() self.evalArgs()
def error(self, msg, s, private=False): def error(self, s, private=False):
"""error(msg, text) -> replies to msg with an error message of text. """error(text) -> replies to msg with an error message of text.
Keyword arguments: Keyword arguments:
private=False: True if the error should be given in private. private=False: True if the error should be given in private.
""" """
if isinstance(self.irc, self.__class__): if isinstance(self.irc, self.__class__):
self.irc.error(msg, s, private) self.irc.error(s, private)
else: else:
s = 'Error: ' + s s = 'Error: ' + s
if private or conf.errorReplyPrivate: if private or conf.errorReplyPrivate:
self.irc.queueMsg(ircmsgs.privmsg(msg.nick, s)) self.irc.queueMsg(ircmsgs.privmsg(self.msg.nick, s))
else: else:
self.irc.queueMsg(reply(msg, s)) self.irc.queueMsg(reply(self.msg, s))
self.finished = True self.finished = True
def killProxy(self): def killProxy(self):
@ -567,11 +568,11 @@ class CommandThread(threading.Thread):
self.command.im_class.threaded = original self.command.im_class.threaded = original
except (getopt.GetoptError, ArgumentError): except (getopt.GetoptError, ArgumentError):
name = self.commandName name = self.commandName
self.irc.reply(self.msg, formatArgumentError(self.command, name)) self.irc.reply(formatArgumentError(self.command, name))
except CannotNest: except CannotNest:
if not isinstance(self.irc.irc, irclib.Irc): if not isinstance(self.irc.irc, irclib.Irc):
s = 'Command %r cannot be nested.' % self.commandName s = 'Command %r cannot be nested.' % self.commandName
self.irc.error(self.msg, s) self.irc.error(s)
class ConfigIrcProxy(RichReplyMethods): class ConfigIrcProxy(RichReplyMethods):
@ -579,10 +580,10 @@ class ConfigIrcProxy(RichReplyMethods):
def __init__(self, irc): def __init__(self, irc):
self.__dict__['irc'] = irc self.__dict__['irc'] = irc
def reply(self, msg, s, *args): def reply(self, s, *args, **kwargs):
return None return None
def error(self, msg, s, *args): def error(self, s, *args, **kwargs):
log.warning('ConfigIrcProxy saw an error: %s' % s) log.warning('ConfigIrcProxy saw an error: %s' % s)
def getRealIrc(self): def getRealIrc(self):
@ -607,12 +608,12 @@ class Privmsg(irclib.IrcCallback):
noIgnore = False noIgnore = False
handled = False handled = False
errored = False errored = False
Proxy = IrcObjectProxy
commandArgs = ['self', 'irc', 'msg', 'args'] commandArgs = ['self', 'irc', 'msg', 'args']
# This must be class-scope, so all subclasses use the same one. # This must be class-scope, so all subclasses use the same one.
_mores = ircutils.IrcDict() _mores = ircutils.IrcDict()
def __init__(self): def __init__(self):
self.__parent = super(Privmsg, self) self.__parent = super(Privmsg, self)
self.Proxy = IrcObjectProxy
myName = self.name() myName = self.name()
self.log = log.getPluginLogger(myName) self.log = log.getPluginLogger(myName)
### Setup the dispatcher command. ### Setup the dispatcher command.
@ -638,14 +639,14 @@ class Privmsg(irclib.IrcCallback):
handleBadArgs() handleBadArgs()
elif self.isCommand(name): elif self.isCommand(name):
if not checkCommandCapability(msg, name): if not checkCommandCapability(msg, name):
irc.error(msg, conf.replyNoCapability % name) irc.error(conf.replyNoCapability % name)
return return
del args[0] del args[0]
method = getattr(self, name) method = getattr(self, name)
try: try:
method(irc, msg, args) method(irc, msg, args)
except (getopt.GetoptError, ArgumentError): except (getopt.GetoptError, ArgumentError):
irc.reply(msg, formatArgumentError(method, name)) irc.reply(formatArgumentError(method, name))
else: else:
handleBadArgs() handleBadArgs()
else: else:
@ -718,10 +719,10 @@ class Privmsg(irclib.IrcCallback):
raise raise
except (SyntaxError, Error), e: except (SyntaxError, Error), e:
self.log.info('Error return: %s', e) self.log.info('Error return: %s', e)
irc.error(msg, str(e)) irc.error(str(e))
except Exception, e: except Exception, e:
self.log.exception('Uncaught exception:') self.log.exception('Uncaught exception:')
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
# Not catching getopt.GetoptError, ArgumentError, CannotNest -- those # Not catching getopt.GetoptError, ArgumentError, CannotNest -- those
# are handled by IrcObjectProxy. # are handled by IrcObjectProxy.
elapsed = time.time() - start elapsed = time.time() - start
@ -729,20 +730,18 @@ class Privmsg(irclib.IrcCallback):
class IrcObjectProxyRegexp(RichReplyMethods): class IrcObjectProxyRegexp(RichReplyMethods):
def __init__(self, irc, *args): def __init__(self, irc, msg):
self.irc = irc self.irc = irc
self.msg = msg
def error(self, msg, s, private=False): def error(self, s, **kwargs):
private = private or conf.errorReplyPrivate self.reply('Error: ' + s, **kwargs)
self.reply(msg, 'Error: ' + s, private=private)
def reply(self, msg, s, prefixName=True, action=False, private=False, def reply(self, s, action=False, **kwargs):
notice=False):
if action: if action:
self.irc.queueMsg(ircmsgs.action(ircutils.replyTo(msg), s)) self.irc.queueMsg(ircmsgs.action(ircutils.replyTo(self.msg), s))
else: else:
self.irc.queueMsg(reply(msg, s, private=private, notice=notice, self.irc.queueMsg(reply(self.msg, s, **kwargs))
prefixName=prefixName))
def __getattr__(self, attr): def __getattr__(self, attr):
return getattr(self.irc, attr) return getattr(self.irc, attr)
@ -769,11 +768,11 @@ class PrivmsgRegexp(Privmsg):
because it's much more easily coded and maintained. because it's much more easily coded and maintained.
""" """
flags = re.I flags = re.I
Proxy = IrcObjectProxyRegexp
commandArgs = ['self', 'irc', 'msg', 'match'] commandArgs = ['self', 'irc', 'msg', 'match']
def __init__(self): def __init__(self):
self.__parent = super(PrivmsgRegexp, self) self.__parent = super(PrivmsgRegexp, self)
self.__parent.__init__() self.__parent.__init__()
self.Proxy = IrcObjectProxyRegexp
self.res = [] self.res = []
#for name, value in self.__class__.__dict__.iteritems(): #for name, value in self.__class__.__dict__.iteritems():
for name, value in self.__class__.__dict__.items(): for name, value in self.__class__.__dict__.items():
@ -791,7 +790,7 @@ class PrivmsgRegexp(Privmsg):
self.__parent.callCommand(method, irc, msg, *L) self.__parent.callCommand(method, irc, msg, *L)
except Exception, e: except Exception, e:
self.log.exception('Uncaught exception from callCommand:') self.log.exception('Uncaught exception from callCommand:')
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
def doPrivmsg(self, irc, msg): def doPrivmsg(self, irc, msg):
if Privmsg.errored: if Privmsg.errored:
@ -806,7 +805,7 @@ class PrivmsgRegexp(Privmsg):
break break
else: else:
spans.add(m.span()) spans.add(m.span())
proxy = IrcObjectProxyRegexp(irc) proxy = self.Proxy(irc, msg)
self.callCommand(method, proxy, msg, m) self.callCommand(method, proxy, msg, m)
@ -818,6 +817,7 @@ class PrivmsgCommandAndRegexp(Privmsg):
flags = re.I flags = re.I
regexps = () regexps = ()
addressedRegexps = () addressedRegexps = ()
Proxy = IrcObjectProxyRegexp
def __init__(self): def __init__(self):
self.__parent = super(PrivmsgCommandAndRegexp, self) self.__parent = super(PrivmsgCommandAndRegexp, self)
self.__parent.__init__() self.__parent.__init__()
@ -838,7 +838,7 @@ class PrivmsgCommandAndRegexp(Privmsg):
except Exception, e: except Exception, e:
if 'catchErrors' in kwargs and kwargs['catchErrors']: if 'catchErrors' in kwargs and kwargs['catchErrors']:
self.log.exception('Uncaught exception in callCommand:') self.log.exception('Uncaught exception in callCommand:')
irc.error(msg, utils.exnToString(e)) irc.error(utils.exnToString(e))
else: else:
raise raise
@ -850,7 +850,7 @@ class PrivmsgCommandAndRegexp(Privmsg):
for (r, method) in self.res: for (r, method) in self.res:
name = method.__name__ name = method.__name__
for m in r.finditer(msg.args[1]): for m in r.finditer(msg.args[1]):
proxy = IrcObjectProxyRegexp(irc) proxy = self.Proxy(irc, msg)
self.callCommand(method, proxy, msg, m, catchErrors=True) self.callCommand(method, proxy, msg, m, catchErrors=True)
if not Privmsg.handled: if not Privmsg.handled:
s = addressed(irc.nick, msg) s = addressed(irc.nick, msg)
@ -860,7 +860,7 @@ class PrivmsgCommandAndRegexp(Privmsg):
if Privmsg.handled and name not in self.alwaysCall: if Privmsg.handled and name not in self.alwaysCall:
continue continue
for m in r.finditer(s): for m in r.finditer(s):
proxy = IrcObjectProxyRegexp(irc) proxy = self.Proxy(irc, msg)
self.callCommand(method,proxy,msg,m,catchErrors=True) self.callCommand(method,proxy,msg,m,catchErrors=True)
Privmsg.handled = True Privmsg.handled = True

View File

@ -272,7 +272,7 @@ class Mixin(object):
if hasattr(self, 'globalConfigurables'): if hasattr(self, 'globalConfigurables'):
names.extend(self.globalConfigurables.names()) names.extend(self.globalConfigurables.names())
names.sort() names.sort()
irc.reply(msg, utils.commaAndify(names)) irc.reply(utils.commaAndify(names))
else: else:
try: try:
channel = privmsgs.getChannel(msg, args) channel = privmsgs.getChannel(msg, args)
@ -285,17 +285,17 @@ class Mixin(object):
s = configurables.help(name) s = configurables.help(name)
value = configurables.get(name, channel) value = configurables.get(name, channel)
s = '%s (Current value: %r)' % (s, value) s = '%s (Current value: %r)' % (s, value)
irc.reply(msg, s) irc.reply(s)
if name in self.configurables: if name in self.configurables:
if value: if value:
if ircdb.checkCapability(msg.prefix, capability): if ircdb.checkCapability(msg.prefix, capability):
try: try:
self.configurables.set(name, value, channel) self.configurables.set(name, value, channel)
irc.replySuccess(msg) irc.replySuccess()
except Error, e: except Error, e:
irc.error(msg, str(e)) irc.error(str(e))
else: else:
irc.error(msg, conf.replyNoCapability % capability) irc.error(conf.replyNoCapability % capability)
else: else:
help(self.configurables) help(self.configurables)
elif hasattr(self, 'globalConfigurables') and \ elif hasattr(self, 'globalConfigurables') and \
@ -304,17 +304,17 @@ class Mixin(object):
if ircdb.checkCapability(msg.prefix, 'admin'): if ircdb.checkCapability(msg.prefix, 'admin'):
try: try:
self.globalConfigurables.set(name, value, channel) self.globalConfigurables.set(name, value, channel)
irc.replySuccess(msg) irc.replySuccess()
except Error, e: except Error, e:
irc.error(msg, str(e)) irc.error(str(e))
else: else:
s = '%s is a global capability, and requires ' \ s = '%s is a global capability, and requires ' \
'the "admin" capability.' 'the "admin" capability.'
irc.error(msg, s) irc.error(s)
else: else:
help(self.globalConfigurables) help(self.globalConfigurables)
else: else:
irc.error(msg, 'There is no config variable %r' % name) irc.error('There is no config variable %r' % name)
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:

View File

@ -98,7 +98,7 @@ def checkCapability(f, capability):
else: else:
self.log.warning('%r attempted %s without %s.', self.log.warning('%r attempted %s without %s.',
msg.prefix, f.func_name, capability) msg.prefix, f.func_name, capability)
irc.error(msg, conf.replyNoCapability % capability) irc.error(conf.replyNoCapability % capability)
newf = types.FunctionType(newf.func_code, newf.func_globals, newf = types.FunctionType(newf.func_code, newf.func_globals,
f.func_name, closure=newf.func_closure) f.func_name, closure=newf.func_closure)
newf.__doc__ = f.__doc__ newf.__doc__ = f.__doc__
@ -119,7 +119,7 @@ def checkChannelCapability(f, capability):
else: else:
self.log.warning('%r attempted %s without %s.', self.log.warning('%r attempted %s without %s.',
msg.prefix, f.func_name, capability) msg.prefix, f.func_name, capability)
irc.error(msg, conf.replyNoCapability % chancap) irc.error(conf.replyNoCapability % chancap)
newf = types.FunctionType(newf.func_code, newf.func_globals, newf = types.FunctionType(newf.func_code, newf.func_globals,
f.func_name, closure=newf.func_closure) f.func_name, closure=newf.func_closure)
newf.__doc__ = f.__doc__ newf.__doc__ = f.__doc__
@ -143,7 +143,7 @@ def name(f):
name = ircdb.users.getUser(msg.prefix).name name = ircdb.users.getUser(msg.prefix).name
except KeyError: except KeyError:
if conf.requireRegistration: if conf.requireRegistration:
irc.error(msg, conf.replyNotRegistered) irc.error(conf.replyNotRegistered)
return return
else: else:
name = msg.prefix name = msg.prefix
@ -209,7 +209,7 @@ class CapabilityCheckingPrivmsg(callbacks.Privmsg):
else: else:
self.log.warning('%r tried to call %s without %s.', self.log.warning('%r tried to call %s without %s.',
msg.prefix, f.im_func.func_name, self.capability) msg.prefix, f.im_func.func_name, self.capability)
irc.error(msg, conf.replyNoCapability % self.capability) irc.error(conf.replyNoCapability % self.capability)
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:

View File

@ -212,17 +212,17 @@ class PrivmsgTestCase(ChannelPluginTestCase):
self.assertResponse('echo []', '[]') self.assertResponse('echo []', '[]')
def testSimpleReply(self): def testSimpleReply(self):
self.assertResponse("eval irc.reply(msg, 'foo')", 'foo') self.assertResponse("eval irc.reply('foo')", 'foo')
def testSimpleReplyAction(self): def testSimpleReplyAction(self):
self.assertResponse("eval irc.reply(msg, 'foo', action=True)", self.assertResponse("eval irc.reply('foo', action=True)",
'\x01ACTION foo\x01') '\x01ACTION foo\x01')
def testErrorPrivateKwarg(self): def testErrorPrivateKwarg(self):
try: try:
originalConfErrorReplyPrivate = conf.errorReplyPrivate originalConfErrorReplyPrivate = conf.errorReplyPrivate
conf.errorReplyPrivate = False conf.errorReplyPrivate = False
m = self.getMsg("eval irc.error(msg, 'foo', private=True)") m = self.getMsg("eval irc.error('foo', private=True)")
self.failIf(ircutils.isChannel(m.args[0])) self.failIf(ircutils.isChannel(m.args[0]))
finally: finally:
conf.errorReplyPrivate = originalConfErrorReplyPrivate conf.errorReplyPrivate = originalConfErrorReplyPrivate
@ -249,22 +249,22 @@ class PrivmsgTestCase(ChannelPluginTestCase):
class First(callbacks.Privmsg): class First(callbacks.Privmsg):
def firstcmd(self, irc, msg, args): def firstcmd(self, irc, msg, args):
"""First""" """First"""
irc.reply(msg, 'foo') irc.reply('foo')
class Second(callbacks.Privmsg): class Second(callbacks.Privmsg):
def secondcmd(self, irc, msg, args): def secondcmd(self, irc, msg, args):
"""Second""" """Second"""
irc.reply(msg, 'bar') irc.reply('bar')
class FirstRepeat(callbacks.Privmsg): class FirstRepeat(callbacks.Privmsg):
def firstcmd(self, irc, msg, args): def firstcmd(self, irc, msg, args):
"""FirstRepeat""" """FirstRepeat"""
irc.reply(msg, 'baz') irc.reply('baz')
class Third(callbacks.Privmsg): class Third(callbacks.Privmsg):
def third(self, irc, msg, args): def third(self, irc, msg, args):
"""Third""" """Third"""
irc.reply(msg, ' '.join(args)) irc.reply(' '.join(args))
def testDispatching(self): def testDispatching(self):
self.irc.addCallback(self.First()) self.irc.addCallback(self.First())
@ -338,7 +338,7 @@ class PrivmsgTestCase(ChannelPluginTestCase):
class InvalidCommand(callbacks.Privmsg): class InvalidCommand(callbacks.Privmsg):
def invalidCommand(self, irc, msg, tokens): def invalidCommand(self, irc, msg, tokens):
irc.reply(msg, 'foo') irc.reply('foo')
def testInvalidCommandOneReplyOnly(self): def testInvalidCommandOneReplyOnly(self):
try: try: