Huge update to the logging infrastructure.

This commit is contained in:
Jeremy Fincher 2003-11-26 18:21:12 +00:00
parent c97fe5e4a1
commit 48166f4895
62 changed files with 398 additions and 397 deletions

View File

@ -43,7 +43,6 @@ import sets
import types import types
import conf import conf
import debug
import utils import utils
import privmsgs import privmsgs
import callbacks import callbacks

View File

@ -34,6 +34,8 @@
Bugzilla bug retriever Bugzilla bug retriever
""" """
__revision__ = "$Id$"
import os import os
import re import re
import string import string
@ -43,9 +45,7 @@ from itertools import imap, ifilter
from htmlentitydefs import entitydefs as entities from htmlentitydefs import entitydefs as entities
import conf import conf
import debug
import utils import utils
__revision__ = "$Id$"
import plugins import plugins
import ircutils import ircutils
@ -194,13 +194,10 @@ class Bugzilla(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
try: try:
name = self.shorthand[name] name = self.shorthand[name]
(url, description) = self.db[name] (url, description) = self.db[name]
#debug.printf(url)
#debug.printf(description)
except KeyError: except KeyError:
irc.error(msg, replyNoBugzilla % name) irc.error(msg, replyNoBugzilla % name)
return return
queryurl = '%s/xml.cgi?id=%s' % (url, number) queryurl = '%s/xml.cgi?id=%s' % (url, number)
#debug.printf(queryurl)
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:

View File

@ -50,7 +50,6 @@ from itertools import imap, ifilter
import sqlite import sqlite
import conf import conf
import debug
import utils import utils
import ircdb import ircdb
import ircmsgs import ircmsgs
@ -359,7 +358,6 @@ class ChannelDB(plugins.ChannelDBHandler,
cursor = db.cursor() cursor = db.cursor()
(optlist, rest) = getopt.getopt(args, '', ['user']) (optlist, rest) = getopt.getopt(args, '', ['user'])
name = privmsgs.getArgs(rest) name = privmsgs.getArgs(rest)
#debug.printf(optlist)
if ('--user', '') in optlist: if ('--user', '') in optlist:
table = 'user_stats' table = 'user_stats'
criterion = 'user_id=%s' criterion = 'user_id=%s'
@ -376,7 +374,6 @@ class ChannelDB(plugins.ChannelDBHandler,
criterion = 'normalized=%s' criterion = 'normalized=%s'
name = ircutils.toLower(name) name = ircutils.toLower(name)
sql = "SELECT last_seen,last_msg FROM %s WHERE %s" % (table,criterion) sql = "SELECT last_seen,last_msg FROM %s WHERE %s" % (table,criterion)
#debug.printf(sql)
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(msg, 'I have not seen %s.' % name)

View File

@ -42,7 +42,6 @@ from cStringIO import StringIO
import os import os
import conf import conf
import debug
import world import world
import irclib import irclib
import ircmsgs import ircmsgs
@ -85,7 +84,7 @@ class ChannelLogger(irclib.IrcCallback):
log.flush() log.flush()
except ValueError, e: except ValueError, e:
if e.args[0] != 'I/O operation on a closed file': if e.args[0] != 'I/O operation on a closed file':
debug.recoverableException() self.log.exception('Odd exception:')
def getLog(self, channel): def getLog(self, channel):
if channel in self.logs: if channel in self.logs:
@ -96,7 +95,7 @@ class ChannelLogger(irclib.IrcCallback):
self.logs[channel] = log self.logs[channel] = log
return log return log
except IOError: except IOError:
debug.recoverableException() self.log.exception('Error opening log:')
return StringIO() return StringIO()
def timestamp(self, log): def timestamp(self, log):

View File

@ -45,7 +45,6 @@ import time
sys.path.append(os.pardir) sys.path.append(os.pardir)
import conf import conf
import debug
import ircmsgs import ircmsgs
import callbacks import callbacks
@ -55,34 +54,34 @@ class Ctcp(callbacks.PrivmsgRegexp):
public = False public = False
def ping(self, irc, msg, match): def ping(self, irc, msg, match):
"\x01PING (.*)\x01" "\x01PING (.*)\x01"
debug.msg('Received CTCP PING from %s' % msg.nick, 'normal') self.log.info('Received CTCP PING from %s', msg.prefix)
irc.queueMsg(notice(msg.nick, '\x01PING %s\x01' % match.group(1))) irc.queueMsg(notice(msg.nick, '\x01PING %s\x01' % match.group(1)))
def version(self, irc, msg, match): def version(self, irc, msg, match):
"\x01VERSION\x01" "\x01VERSION\x01"
debug.msg('Received CTCP VERSION from %s' % msg.nick, 'normal') self.log.info('Received CTCP VERSION from %s', msg.prefix)
s = '\x01VERSION SupyBot %s\x01' % conf.version s = '\x01VERSION SupyBot %s\x01' % conf.version
irc.queueMsg(notice(msg.nick, s)) irc.queueMsg(notice(msg.nick, s))
def userinfo(self, irc, msg, match): def userinfo(self, irc, msg, match):
"\x01USERINFO\x01" "\x01USERINFO\x01"
debug.msg('Received CTCP USERINFO from %s' % msg.nick, 'normal') self.log.info('Received CTCP USERINFO from %s', msg.prefix)
irc.queueMsg(notice(msg.nick, '\x01USERINFO\x01')) irc.queueMsg(notice(msg.nick, '\x01USERINFO\x01'))
def time(self, irc, msg, match): def time(self, irc, msg, match):
"\x01TIME\x01" "\x01TIME\x01"
debug.msg('Received CTCP TIME from %s' % msg.nick, 'normal') self.log.info('Received CTCP TIME from %s' % msg.prefix)
irc.queueMsg(notice(msg.nick, '\x01%s\x01' % time.ctime())) irc.queueMsg(notice(msg.nick, '\x01%s\x01' % time.ctime()))
def finger(self, irc, msg, match): def finger(self, irc, msg, match):
"\x01FINGER\x01" "\x01FINGER\x01"
debug.msg('Received CTCP FINGER from %s' % msg.nick, 'normal') self.log.info('Received CTCP FINGER from %s' % msg.prefix)
s = '\x01SupyBot, the best Python bot in existence!\x01' s = '\x01SupyBot, the best Python bot in existence!\x01'
irc.queueMsg(notice(msg.nick, s)) irc.queueMsg(notice(msg.nick, s))
def source(self, irc, msg, match): def source(self, irc, msg, match):
"\x01SOURCE\x01" "\x01SOURCE\x01"
debug.msg('Received CTCP SOURCE from %s' % msg.nick, 'normal') self.log.info('Received CTCP SOURCE from %s' % msg.prefix)
s = 'http://www.sourceforge.net/projects/supybot/' s = 'http://www.sourceforge.net/projects/supybot/'
irc.queueMsg(notice(msg.nick, s)) irc.queueMsg(notice(msg.nick, s))

View File

@ -41,7 +41,6 @@ import socket
import textwrap import textwrap
import threading import threading
import debug
import utils import utils
import world import world
import ircmsgs import ircmsgs
@ -75,19 +74,18 @@ class DCC(callbacks.Privmsg):
i = ircutils.dccIP(ip) i = ircutils.dccIP(ip)
sock.bind((host, 0)) sock.bind((host, 0))
port = sock.getsockname()[1] port = sock.getsockname()[1]
debug.msg('DCC CHAT port opened at (%s, %s)' % (host, port), self.log.info('DCC CHAT port opened at (%s, %s)', host, port)
'normal')
sock.listen(1) sock.listen(1)
irc.queueMsg(ircmsgs.privmsg(msg.nick, irc.queueMsg(ircmsgs.privmsg(msg.nick,
'\x01DCC CHAT chat %s %s\x01' % \ '\x01DCC CHAT chat %s %s\x01' % \
(i, port))) (i, port)))
(realSock, addr) = sock.accept() (realSock, addr) = sock.accept()
debug.msg('DCC CHAT accepted from %s' % (addr,), 'normal') self.log.info('DCC CHAT accepted from %s', addr)
for line in textwrap.wrap(text, 80): for line in textwrap.wrap(text, 80):
realSock.send(line) realSock.send(line)
realSock.send('\n') realSock.send('\n')
finally: finally:
debug.msg('Finally closing sock and realSock.', 'normal') self.log.info('Finally closing sock and realSock.')
sock.close() sock.close()
try: try:
realSock.close() realSock.close()

View File

@ -44,7 +44,6 @@ import socket
import dictclient import dictclient
import conf import conf
import debug
import utils import utils
import plugins import plugins
import ircutils import ircutils

View File

@ -43,7 +43,6 @@ __revision__ = "$Id$"
import plugins import plugins
import conf import conf
import debug
import utils import utils
import plugins import plugins
import ircutils import ircutils
@ -132,11 +131,10 @@ class Ebay(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
if not self.configurables.get('auction-snarfer', channel=msg.args[0]): if not self.configurables.get('auction-snarfer', channel=msg.args[0]):
return return
url = match.group(0) url = match.group(0)
#debug.printf(url)
try: try:
irc.reply(msg, self._getResponse(url), prefixName=False) irc.reply(msg, self._getResponse(url), prefixName=False)
except EbayError, e: except EbayError, e:
debug.msg('Ebay Auction Snarfer: %s: %s' % (url, e)) self.log.exception('ebaySnarfer exception at %s:', url)
ebaySnarfer = privmsgs.urlSnarfer(ebaySnarfer) ebaySnarfer = privmsgs.urlSnarfer(ebaySnarfer)
def _getResponse(self, url): def _getResponse(self, url):
@ -162,7 +160,6 @@ class Ebay(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
m = r.search(s) m = r.search(s)
if m: if m:
if r in self._multiField: if r in self._multiField:
#debug.printf(m.groups())
# [:3] is to make sure that we don't pass a tuple with # [:3] is to make sure that we don't pass a tuple with
# more than 3 items. this allows self._bidder to work # more than 3 items. this allows self._bidder to work
# since self._bidder returns a 5 item tuple # since self._bidder returns a 5 item tuple

View File

@ -39,7 +39,6 @@ __revision__ = "$Id$"
import plugins import plugins
import conf import conf
import debug
import ircdb import ircdb
import ircmsgs import ircmsgs
import plugins import plugins
@ -104,7 +103,7 @@ class Enforcer(callbacks.Privmsg, plugins.Configurable):
def doJoin(self, irc, msg): def doJoin(self, irc, msg):
if not self.started: if not self.started:
debug.msg('Enforcer not started.', 'normal') self.log.warning('Enforcer not started.')
return return
channel = msg.args[0] channel = msg.args[0]
c = ircdb.channels.getChannel(channel) c = ircdb.channels.getChannel(channel)
@ -123,7 +122,7 @@ class Enforcer(callbacks.Privmsg, plugins.Configurable):
def doTopic(self, irc, msg): def doTopic(self, irc, msg):
if not self.started: if not self.started:
debug.msg('Enforcer not started.', 'normal') self.log.info('Enforcer not started.')
return return
channel = msg.args[0] channel = msg.args[0]
topic = msg.args[1] topic = msg.args[1]
@ -142,7 +141,7 @@ class Enforcer(callbacks.Privmsg, plugins.Configurable):
def do332(self, irc, msg): def do332(self, irc, msg):
# This command gets sent right after joining a channel. # This command gets sent right after joining a channel.
if not self.started: if not self.started:
debug.msg('Enforcer not started.', 'normal') self.log.info('Enforcer not started.')
return return
(channel, topic) = msg.args[1:] (channel, topic) = msg.args[1:]
self.topics[channel] = topic self.topics[channel] = topic
@ -157,7 +156,7 @@ class Enforcer(callbacks.Privmsg, plugins.Configurable):
def doKick(self, irc, msg): def doKick(self, irc, msg):
if not self.started: if not self.started:
debug.msg('Enforcer not started.', 'normal') self.log.info('Enforcer not started.')
return return
channel = msg.args[0] channel = msg.args[0]
kicked = msg.args[1].split(',') kicked = msg.args[1].split(',')
@ -182,7 +181,7 @@ class Enforcer(callbacks.Privmsg, plugins.Configurable):
def doMode(self, irc, msg): def doMode(self, irc, msg):
if not self.started: if not self.started:
debug.msg('Enforcer not started.', 'normal') self.log.info('Enforcer not started.')
return return
channel = msg.args[0] channel = msg.args[0]
if not ircutils.isChannel(channel) or msg.nick == self.chanserv: if not ircutils.isChannel(channel) or msg.nick == self.chanserv:
@ -246,9 +245,6 @@ class Enforcer(callbacks.Privmsg, plugins.Configurable):
if ircutils.isUserHostmask(msg.prefix) and \ if ircutils.isUserHostmask(msg.prefix) and \
not msg.nick == self.chanserv: not msg.nick == self.chanserv:
return callbacks.Privmsg.__call__(self, irc, msg) return callbacks.Privmsg.__call__(self, irc, msg)
else:
debug.msg('Enforcer plugin not started. '
'Give the bot the start command.', 'normal')
Class = Enforcer Class = Enforcer

View File

@ -410,4 +410,5 @@ class Factoids(plugins.ChannelDBHandler, callbacks.Privmsg):
Class = Factoids Class = Factoids
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:

View File

@ -49,10 +49,8 @@ class FixRelayBot(irclib.IrcCallback):
_re = re.compile(r'<([^@]+)@[^>]+>\s+(.*)') _re = re.compile(r'<([^@]+)@[^>]+>\s+(.*)')
def inFilter(self, irc, msg): def inFilter(self, irc, msg):
if msg.command == 'PRIVMSG': if msg.command == 'PRIVMSG':
#debug.printf('Message command was PRIVMSG')
m = self._re.match(msg.args[1]) m = self._re.match(msg.args[1])
if m: if m:
#debug.printf('Regexp matched: %r, %r, %r' % m.groups())
nick = m.group(1) nick = m.group(1)
host = random.random()*100 host = random.random()*100
newprefix = ircutils.joinHostmask(nick, nick, host) newprefix = ircutils.joinHostmask(nick, nick, host)

View File

@ -37,7 +37,6 @@ __revision__ = "$Id$"
import plugins import plugins
import debug
import ircutils import ircutils
import callbacks import callbacks

View File

@ -50,7 +50,6 @@ import mimetypes
from itertools import imap from itertools import imap
import conf import conf
import debug
import utils import utils
import ircmsgs import ircmsgs
import ircutils import ircutils

View File

@ -48,7 +48,6 @@ from itertools import imap
import sqlite import sqlite
import conf import conf
import debug
import ircdb import ircdb
import utils import utils
import world import world
@ -241,7 +240,7 @@ class FunDB(callbacks.Privmsg, plugins.Configurable):
except ValueError, e: except ValueError, e:
irc.error(msg, 'The regexp wasn\'t valid: %s.' % e.args[0]) irc.error(msg, 'The regexp wasn\'t valid: %s.' % e.args[0])
except re.error, e: except re.error, e:
irc.error(msg, debug.exnToString(e)) irc.error(msg, utils.exnToString(e))
return return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()

View File

@ -42,7 +42,6 @@ import sets
import urllib2 import urllib2
import conf import conf
import debug
import utils import utils
import plugins import plugins
import ircutils import ircutils
@ -183,12 +182,9 @@ class Gameknot(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
r"http://(?:www\.)?gameknot\.com/chess\.pl\?bd=\d+(&r=\d+)?" r"http://(?:www\.)?gameknot\.com/chess\.pl\?bd=\d+(&r=\d+)?"
if not self.configurables.get('game-snarfer', channel=msg.args[0]): if not self.configurables.get('game-snarfer', channel=msg.args[0]):
return return
#debug.printf('Got a GK URL from %s' % msg.prefix)
url = match.group(0) url = match.group(0)
fd = urllib2.urlopen(url) fd = urllib2.urlopen(url)
#debug.printf('Got the connection.')
s = fd.read() s = fd.read()
#debug.printf('Got the string.')
fd.close() fd.close()
try: try:
if 'no longer available' in s: if 'no longer available' in s:
@ -197,13 +193,13 @@ class Gameknot(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
return return
m = self._gkGameTitle.search(s) m = self._gkGameTitle.search(s)
if m is None: if m is None:
debug.msg('Gameknot._gkGameTitle didn\'t match (%s).' % url) self.log.warning('_gkGameTitle didn\'t match (%s).', url)
return return
gameTitle = m.groups() gameTitle = m.groups()
gameTitle = ircutils.bold(gameTitle) gameTitle = ircutils.bold(gameTitle)
L = self._gkPlayer.findall(s) L = self._gkPlayer.findall(s)
if not L: if not L:
debug.msg('Gameknot._gkPlayer didn\'t match (%s).' % url) self.log.warning('_gkPlayer didn\'t match (%s).', url)
return return
((wRating, wName), (bRating, bName)) = L ((wRating, wName), (bRating, bName)) = L
wName = ircutils.bold(wName) wName = ircutils.bold(wName)
@ -242,7 +238,7 @@ class Gameknot(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
irc.error(msg,'That doesn\'t appear to be a proper Gameknot game.'\ irc.error(msg,'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, debug.exnToString(e)) irc.error(msg, utils.exnToString(e))
gameknotSnarfer = privmsgs.urlSnarfer(gameknotSnarfer) gameknotSnarfer = privmsgs.urlSnarfer(gameknotSnarfer)
def gameknotStatsSnarfer(self, irc, msg, match): def gameknotStatsSnarfer(self, irc, msg, match):

View File

@ -48,7 +48,6 @@ import SOAP
import google import google
import conf import conf
import debug
import utils import utils
import ircmsgs import ircmsgs
import plugins import plugins
@ -106,7 +105,7 @@ totalSearches = 0
totalTime = 0 totalTime = 0
last24hours = structures.queue() last24hours = structures.queue()
def search(*args, **kwargs): def search(log, *args, **kwargs):
try: try:
global totalSearches, totalTime, last24hours global totalSearches, totalTime, last24hours
data = google.doGoogleSearch(*args, **kwargs) data = google.doGoogleSearch(*args, **kwargs)
@ -123,7 +122,7 @@ def search(*args, **kwargs):
else: else:
raise raise
except SOAP.faultType, e: except SOAP.faultType, e:
debug.msg(debug.exnToString(e)) log.exception('Uncaught SOAP error:')
raise callbacks.Error, 'Invalid Google license key.' raise callbacks.Error, 'Invalid Google license key.'
class Google(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable): class Google(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
@ -201,7 +200,7 @@ class Google(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
else: else:
kwargs[option[2:]] = argument kwargs[option[2:]] = argument
searchString = privmsgs.getArgs(rest) searchString = privmsgs.getArgs(rest)
data = search(searchString, **kwargs) data = search(self.log, searchString, **kwargs)
irc.reply(msg, self.formatData(data)) irc.reply(msg, self.formatData(data))
def metagoogle(self, irc, msg, args): def metagoogle(self, irc, msg, args):
@ -222,7 +221,7 @@ class Google(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
else: else:
kwargs[option[2:]] = argument kwargs[option[2:]] = argument
searchString = privmsgs.getArgs(rest) searchString = privmsgs.getArgs(rest)
data = search(searchString, **kwargs) data = search(self.log, searchString, **kwargs)
meta = data.meta meta = data.meta
categories = [d['fullViewableName'] for d in meta.directoryCategories] categories = [d['fullViewableName'] for d in meta.directoryCategories]
categories = [utils.dqrepr(s.replace('_', ' ')) for s in categories] categories = [utils.dqrepr(s.replace('_', ' ')) for s in categories]
@ -247,7 +246,7 @@ class Google(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
results = [] results = []
for arg in args: for arg in args:
data = search(arg) data = search(self.log, arg)
results.append((data.meta.estimatedTotalResultsCount, arg)) results.append((data.meta.estimatedTotalResultsCount, arg))
results.sort() results.sort()
results.reverse() results.reverse()
@ -286,7 +285,7 @@ class Google(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
return return
searchString = match.group(1) searchString = match.group(1)
try: try:
data = search(searchString, safeSearch=1) data = search(self.log, searchString, safeSearch=1)
except google.NoLicenseKey: except google.NoLicenseKey:
return return
if data.results: if data.results:

View File

@ -47,7 +47,6 @@ from itertools import imap, ifilter
import conf import conf
import utils import utils
import debug
import privmsgs import privmsgs
import callbacks import callbacks
@ -66,9 +65,14 @@ class Http(callbacks.Privmsg):
def callCommand(self, method, irc, msg, *L): def callCommand(self, method, irc, msg, *L):
try: try:
callbacks.Privmsg.callCommand(self, method, irc, msg, *L) callbacks.Privmsg.callCommand(self, method, irc, msg, *L)
except socket.gaierror, e: except socket.error, e:
irc.error(msg, e.args[1]) if e.args[0] == 111:
except urllib2.HTTPError, r: irc.error(msg, 'Connection refused.')
elif e.args[0] in (110, 10060):
irc.error(msg, 'Connection timed out.')
else:
irc.error(msg, e.args[1])
except (urllib2.HTTPError, urllib2.URLError), e:
irc.error(msg, str(e)) irc.error(msg, str(e))
_titleRe = re.compile(r'<title>(.*?)</title>', re.I | re.S) _titleRe = re.compile(r'<title>(.*?)</title>', re.I | re.S)
@ -115,7 +119,7 @@ class Http(callbacks.Privmsg):
'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, debug.exnToString(e)) irc.error(msg, utils.exnToString(e))
def stockquote(self, irc, msg, args): def stockquote(self, irc, msg, args):
"""<company symbol> """<company symbol>
@ -182,7 +186,6 @@ class Http(callbacks.Privmsg):
city = '+'.join(args) city = '+'.join(args)
city = city.rstrip(',') city = city.rstrip(',')
city = city.lower() city = city.lower()
#debug.printf((state, city))
#We must break the States up into two sections. The US and #We must break the States up into two sections. The US and
#Canada are the only countries that require a State argument. #Canada are the only countries that require a State argument.
@ -199,7 +202,6 @@ class Http(callbacks.Privmsg):
'pass=&dpp=&forecast=zandh&config=&'\ 'pass=&dpp=&forecast=zandh&config=&'\
'place=%s&state=%s&country=%s' % \ 'place=%s&state=%s&country=%s' % \
(city, state, country) (city, state, country)
#debug.printf(url)
html = getPage(url) html = getPage(url)
if 'was not found' in html: if 'was not found' in html:
url = 'http://www.hamweather.net/cgi-bin/hw3/hw3.cgi?'\ url = 'http://www.hamweather.net/cgi-bin/hw3/hw3.cgi?'\
@ -290,7 +292,6 @@ class Http(callbacks.Privmsg):
for (i, s) in enumerate(defs): for (i, s) in enumerate(defs):
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]
#debug.printf(defs)
if len(defs) == 0: if len(defs) == 0:
irc.reply(msg,'No definitions found. (%s)'%conf.replyPossibleBug) irc.reply(msg,'No definitions found. (%s)'%conf.replyPossibleBug)
else: else:

View File

@ -43,7 +43,6 @@ import os.path
import sqlite import sqlite
import conf import conf
import debug
import ircmsgs import ircmsgs
import callbacks import callbacks
@ -205,7 +204,7 @@ if __name__ == '__main__':
(key, value) = r.split(line, 1) (key, value) = r.split(line, 1)
cursor.execute(sql, key, value) cursor.execute(sql, key, value)
except Exception, e: except Exception, e:
print 'Invalid line (%s): %r' %(debug.exnToString(e),line) print 'Invalid line (%s): %r' %(utils.exnToString(e),line)
db.commit() db.commit()

View File

@ -44,7 +44,6 @@ import os.path
import sqlite import sqlite
import debug
import ircmsgs import ircmsgs
import ircutils import ircutils
import privmsgs import privmsgs
@ -91,7 +90,6 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
return return
channel = msg.args[0] channel = msg.args[0]
db = self.getDb(channel) db = self.getDb(channel)
#debug.printf([channel, db.db.filename])
cursor = db.cursor() cursor = db.cursor()
if ircmsgs.isAction(msg): if ircmsgs.isAction(msg):
words = ircmsgs.unAction(msg).split() words = ircmsgs.unAction(msg).split()
@ -132,7 +130,6 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
""" """
channel = privmsgs.getChannel(msg, args) channel = privmsgs.getChannel(msg, args)
db = self.getDb(channel) db = self.getDb(channel)
#debug.printf([channel, db.db.filename])
cursor = db.cursor() cursor = db.cursor()
words = [] words = []
cursor.execute("""SELECT id, first, second FROM pairs cursor.execute("""SELECT id, first, second FROM pairs
@ -174,7 +171,6 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
""" """
channel = privmsgs.getChannel(msg, args) channel = privmsgs.getChannel(msg, args)
db = self.getDb(channel) db = self.getDb(channel)
#debug.printf([channel, db.db.filename])
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT COUNT(*) FROM pairs""") cursor.execute("""SELECT COUNT(*) FROM pairs""")
n = cursor.fetchone()[0] n = cursor.fetchone()[0]
@ -189,7 +185,6 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
""" """
channel = privmsgs.getChannel(msg, args) channel = privmsgs.getChannel(msg, args)
db = self.getDb(channel) db = self.getDb(channel)
#debug.printf([channel, db.db.filename])
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT COUNT(*) FROM pairs WHERE is_first=1""") cursor.execute("""SELECT COUNT(*) FROM pairs WHERE is_first=1""")
n = cursor.fetchone()[0] n = cursor.fetchone()[0]
@ -204,7 +199,6 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
""" """
channel = privmsgs.getChannel(msg, args) channel = privmsgs.getChannel(msg, args)
db = self.getDb(channel) db = self.getDb(channel)
#debug.printf([channel, db.db.filename])
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT COUNT(*) FROM follows""") cursor.execute("""SELECT COUNT(*) FROM follows""")
n = cursor.fetchone()[0] n = cursor.fetchone()[0]
@ -219,7 +213,6 @@ class Markov(plugins.ChannelDBHandler, callbacks.Privmsg):
""" """
channel = privmsgs.getChannel(msg, args) channel = privmsgs.getChannel(msg, args)
db = self.getDb(channel) db = self.getDb(channel)
#debug.printf([channel, db.db.filename])
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT COUNT(*) FROM follows WHERE word ISNULL""") cursor.execute("""SELECT COUNT(*) FROM follows WHERE word ISNULL""")
n = cursor.fetchone()[0] n = cursor.fetchone()[0]

View File

@ -46,7 +46,6 @@ from itertools import imap
import unum.units import unum.units
import debug
import utils import utils
import privmsgs import privmsgs
import callbacks import callbacks
@ -120,7 +119,6 @@ class Math(callbacks.Privmsg):
text = privmsgs.getArgs(args) text = privmsgs.getArgs(args)
text = text.translate(string.ascii, '_[] \t') text = text.translate(string.ascii, '_[] \t')
text = text.replace('lambda', '') text = text.replace('lambda', '')
#debug.printf(text)
def handleMatch(m): def handleMatch(m):
s = m.group(1) s = m.group(1)
if s.startswith('0x'): if s.startswith('0x'):
@ -137,7 +135,6 @@ class Math(callbacks.Privmsg):
x = abs(x) x = abs(x)
return str(x) return str(x)
text = self._mathRe.sub(handleMatch, text) text = self._mathRe.sub(handleMatch, text)
#debug.printf(text)
try: try:
x = complex(eval(text, self._mathEnv, self._mathEnv)) x = complex(eval(text, self._mathEnv, self._mathEnv))
irc.reply(msg, self._complexToString(x)) irc.reply(msg, self._complexToString(x))
@ -149,7 +146,7 @@ class Math(callbacks.Privmsg):
except NameError, e: except NameError, e:
irc.error(msg, '%s is not a defined function.' % str(e).split()[1]) irc.error(msg, '%s is not a defined function.' % str(e).split()[1])
except Exception, e: except Exception, e:
irc.error(msg, debug.exnToString(e)) irc.error(msg, utils.exnToString(e))
_rpnEnv = { _rpnEnv = {
'dup': lambda s: s.extend([s.pop()]*2), 'dup': lambda s: s.extend([s.pop()]*2),

View File

@ -36,7 +36,7 @@ command, it checks the factoid database for a key that matches what was said
and if nothing is found, responds with an entry from the "dunno" database. and if nothing is found, responds with an entry from the "dunno" database.
""" """
__revision__ = "$Id$" __revision__="$Id$"
import plugins import plugins
@ -51,7 +51,6 @@ from itertools import imap
from cStringIO import StringIO from cStringIO import StringIO
import conf import conf
import debug
import ircdb import ircdb
import utils import utils
import ircmsgs import ircmsgs

View File

@ -41,7 +41,6 @@ import sets
import socket import socket
import telnetlib import telnetlib
import debug
import utils import utils
import ircutils import ircutils
import privmsgs import privmsgs
@ -119,7 +118,6 @@ class Network(callbacks.Privmsg):
(domain, url, status, created, updated, expires) (domain, url, status, created, updated, expires)
irc.reply(msg, s) irc.reply(msg, s)
except NameError, e: except NameError, e:
#debug.printf(e)
irc.error(msg, 'I couldn\'t find such a domain.') irc.error(msg, 'I couldn\'t find such a domain.')

View File

@ -45,7 +45,6 @@ from itertools import imap
import sqlite import sqlite
import conf import conf
import debug
import utils import utils
import ircdb import ircdb
import ircmsgs import ircmsgs

View File

@ -40,7 +40,6 @@ import plugins
import urllib2 import urllib2
import debug
import utils import utils
import privmsgs import privmsgs
import callbacks import callbacks
@ -261,7 +260,7 @@ class OSU(callbacks.Privmsg):
else: else:
irc.reply(msg, 'Possible matches: %s' % ', '.join(emails)) irc.reply(msg, 'Possible matches: %s' % ', '.join(emails))
except Exception, e: except Exception, e:
irc.error(msg, debug.exnToString(e)) irc.error(msg, utils.exnToString(e))
def building(self, irc, msg, args): def building(self, irc, msg, args):
"""<building abbreviation> """<building abbreviation>

View File

@ -38,17 +38,17 @@ __revision__ = "$Id$"
import plugins import plugins
import os
import time
import sqlite
import conf
import utils import utils
import ircdb import ircdb
import ircutils import ircutils
import privmsgs import privmsgs
import callbacks import callbacks
import conf
import debug
import os.path
import time
import sqlite
def configure(onStart, afterConnect, advanced): def configure(onStart, afterConnect, advanced):

View File

@ -53,7 +53,6 @@ sys.stdout = StringIO()
import this import this
sys.stdout = sys.__stdout__ sys.stdout = sys.__stdout__
import debug
import utils import utils
import ircutils import ircutils
import privmsgs import privmsgs
@ -200,7 +199,6 @@ class Python(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
if m: if m:
resp.append('%s: %s' % self._bold(m.groups())) resp.append('%s: %s' % self._bold(m.groups()))
if resp: if resp:
#debug.printf('; '.join(resp))
irc.reply(msg, '; '.join(resp), prefixName = False) irc.reply(msg, '; '.join(resp), prefixName = False)
aspnRecipes = privmsgs.urlSnarfer(aspnRecipes) aspnRecipes = privmsgs.urlSnarfer(aspnRecipes)

View File

@ -165,7 +165,6 @@ class Quotes(plugins.ChannelDBHandler, callbacks.Privmsg):
formats.append(s) formats.append(s)
sql = """SELECT id, quote FROM quotes sql = """SELECT id, quote FROM quotes
WHERE %s""" % ' AND '.join(criteria) WHERE %s""" % ' AND '.join(criteria)
#debug.printf(sql)
cursor = db.cursor() cursor = db.cursor()
cursor.execute(sql, *formats) cursor.execute(sql, *formats)
if cursor.rowcount == 0: if cursor.rowcount == 0:

View File

@ -43,7 +43,6 @@ import time
from itertools import imap, ifilter from itertools import imap, ifilter
import conf import conf
import debug
import utils import utils
import world import world
import irclib import irclib

View File

@ -41,7 +41,6 @@ import urllib2
from itertools import ifilter, imap from itertools import ifilter, imap
import conf import conf
import debug
import utils import utils
__revision__ = "$Id$" __revision__ = "$Id$"
@ -159,7 +158,7 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
return 'http://sourceforge.net%s%s' % (utils.htmlToText( return 'http://sourceforge.net%s%s' % (utils.htmlToText(
m.group(1)), self._hrefOpts) m.group(1)), self._hrefOpts)
except urllib2.HTTPError, e: except urllib2.HTTPError, e:
raise callbacks.Error, e.msg() raise callbacks.Error, str(e)
def _getTrackerList(self, url): def _getTrackerList(self, url):
try: try:
@ -318,18 +317,17 @@ class Sourceforge(callbacks.PrivmsgCommandAndRegexp, plugins.Configurable):
head = '%s #%s:' % (ircutils.bold(linktype), num) head = '%s #%s:' % (ircutils.bold(linktype), num)
resp.append(desc) resp.append(desc)
else: else:
debug.msg('%s does not appear to be a proper Sourceforge '\ s = '%s does not appear to be a proper Sourceforge ' \
'Tracker page (%s)' % (url, conf.replyPossibleBug)) 'Tracker page (%s)' % (url, conf.replyPossibleBug)
self.log.warning(s)
for r in self._res: for r in self._res:
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(msg, '%s #%s: %s' % (ircutils.bold(linktype),
ircutils.bold(num), '; '.join(resp)), prefixName = False) ircutils.bold(num), '; '.join(resp)), prefixName = False)
except urllib2.HTTPError, e: except (urllib2.HTTPError, socket.error), e:
debug.msg(e.msg()) self.log.warning(str(e))
except socket.error, e:
debug.msg(e.msg())
sfSnarfer = privmsgs.urlSnarfer(sfSnarfer) sfSnarfer = privmsgs.urlSnarfer(sfSnarfer)
Class = Sourceforge Class = Sourceforge

View File

@ -191,8 +191,8 @@ class Status(callbacks.Privmsg):
elif sys.platform.startswith('netbsd'): elif sys.platform.startswith('netbsd'):
mem = os.stat('/proc/%s/mem')[7] mem = os.stat('/proc/%s/mem')[7]
response += ' I\'m taking up %s kB of memory.' % mem response += ' I\'m taking up %s kB of memory.' % mem
except Exception, e: except Exception:
debug.msg(debug.exnToString(e)) self.log.exception('Uncaught exception in cpustats:')
irc.reply(msg, response) irc.reply(msg, response)
def cmdstats(self, irc, msg, args): def cmdstats(self, irc, msg, args):

View File

@ -47,7 +47,6 @@ import os.path
import sqlite import sqlite
import conf import conf
import debug
import ircdb import ircdb
import utils import utils
import privmsgs import privmsgs

View File

@ -41,7 +41,6 @@ import re
import random import random
import conf import conf
import debug
import utils import utils
import ircdb import ircdb
import ircmsgs import ircmsgs
@ -161,7 +160,7 @@ class Topic(callbacks.Privmsg):
irc.error(msg, 'The regexp wasn\'t valid: %s' % e.args[0]) irc.error(msg, 'The regexp wasn\'t valid: %s' % e.args[0])
return return
except re.error, e: except re.error, e:
irc.error(msg, debug.exnToString(e)) irc.error(msg, utils.exnToString(e))
return return
topics = self._splitTopic(irc.state.getTopic(channel)) topics = self._splitTopic(irc.state.getTopic(channel))
if not topics: if not topics:
@ -214,7 +213,6 @@ class Topic(callbacks.Privmsg):
except IndexError: except IndexError:
irc.error(msg, 'That\'s not a valid topic number.') irc.error(msg, 'That\'s not a valid topic number.')
return return
## debug.printf(topic)
match = self.topicUnformatter.match(topic) match = self.topicUnformatter.match(topic)
if match is None: if match is None:
name = '' name = ''

View File

@ -49,7 +49,6 @@ import urlparse
import sqlite import sqlite
import conf import conf
import debug
import utils import utils
import ircmsgs import ircmsgs
import ircutils import ircutils
@ -176,10 +175,9 @@ class URL(callbacks.PrivmsgCommandAndRegexp,
cursor = db.cursor() cursor = db.cursor()
(tinyurl, updateDb) = self._getTinyUrl(url, channel) (tinyurl, updateDb) = self._getTinyUrl(url, channel)
if tinyurl is None: if tinyurl is None:
debug.msg('tinyurl was None for url %r' % url) self.log.warning('tinyurl was None for url %r', url)
return return
elif updateDb: elif updateDb:
#debug.printf(url)
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(msg, s, prefixName=False)
@ -206,7 +204,6 @@ class URL(callbacks.PrivmsgCommandAndRegexp,
if cursor.rowcount == 0: if cursor.rowcount == 0:
updateDb = True updateDb = True
try: try:
#debug.printf('Trying to get tinyurl for %r' % url)
fd = urllib2.urlopen('http://tinyurl.com/create.php?url=%s' % fd = urllib2.urlopen('http://tinyurl.com/create.php?url=%s' %
url) url)
s = fd.read() s = fd.read()
@ -220,14 +217,13 @@ class URL(callbacks.PrivmsgCommandAndRegexp,
if cmd: if cmd:
raise callbacks.Error, e.msg() raise callbacks.Error, e.msg()
else: else:
debug.msg(e.msg()) self.log.warning(str(e))
else: else:
updateDb = False updateDb = False
tinyurl = cursor.fetchone()[0] tinyurl = cursor.fetchone()[0]
return (tinyurl, updateDb) return (tinyurl, updateDb)
def _formatUrl(self, url, added, addedBy): def _formatUrl(self, url, added, addedBy):
#debug.printf((url, added, addedBy))
when = time.strftime(conf.humanTimestampFormat, when = time.strftime(conf.humanTimestampFormat,
time.localtime(int(added))) time.localtime(int(added)))
return '<%s> (added by %s at %s)' % (url, addedBy, when) return '<%s> (added by %s at %s)' % (url, addedBy, when)

View File

@ -11,17 +11,17 @@ import sets
import pydoc import pydoc
import pprint import pprint
import socket import socket
import logging
import optparse import optparse
import textwrap import textwrap
from itertools import imap from itertools import imap
import ansi import ansi
import conf import conf
import debug
import utils import utils
import ircutils import ircutils
debug.minimumPriority = 'high' conf.minimumLogPriority = logging.CRITICAL
useColor = False useColor = False
@ -69,7 +69,7 @@ def loadPlugin(name):
except Exception, e: except Exception, e:
myPrint("""We encountered a bit of trouble trying to load plugin %r. myPrint("""We encountered a bit of trouble trying to load plugin %r.
Python told us %r. We'll skip over it for now, you can always add it Python told us %r. We'll skip over it for now, you can always add it
later.""" % (name, debug.exnToString(e))) later.""" % (name, utils.exnToString(e)))
return None return None
def describePlugin(module, showUsage): def describePlugin(module, showUsage):
@ -146,7 +146,6 @@ def main():
server = None server = None
onStart = [] onStart = []
afterConnect = [] afterConnect = []
debugVariables = {}
configVariables = {} configVariables = {}
myPrint("""This is a wizard to help you start running supybot. What it myPrint("""This is a wizard to help you start running supybot. What it
@ -473,39 +472,39 @@ def main():
configVariables['enablePipeSyntax'] = True configVariables['enablePipeSyntax'] = True
### ###
# debug variables. # logging variables.
### ###
# debug.stderr # conf.stdoutLogging
myPrint("""By default, your bot will log not only to files in the logs myPrint("""By default, your bot will log not only to files in the logs
directory you gave it, but also to stderr. We find this useful for directory you gave it, but also to stdout. We find this useful for
debugging, and also just for the pretty output (it's colored!)""") debugging, and also just for the pretty output (it's colored!)""")
if yn('Would you like to turn off this logging to stderr?') == 'y': if yn('Would you like to turn off this logging to stdout?') == 'y':
debugVariables['stderr'] = False confVariables['stdoutLogging'] = False
else: else:
# debug.colorterm # conf.something
myPrint("""Some terminals may not be able to display the pretty colors myPrint("""Some terminals may not be able to display the pretty colors
logged to stderr. By default, though, we turn the colors off for logged to stderr. By default, though, we turn the colors off for
Windows machines and leave it on for *nix machines.""") Windows machines and leave it on for *nix machines.""")
if yn('Would you like to turn this colorization off?') == 'y': if yn('Would you like to turn this colorization off?') == 'y':
debugVariables['colorterm'] = False confVariables['colorterm'] = False
# debug.minimumPriority ## # conf.minimumLogPriority
myPrint("""Your bot can handle debug messages at four priorities, 'high,' ## myPrint("""Your bot can handle debug messages at several priorities,
'normal,' 'low,' and 'verbose,' in decreasing order of priority. By ## CRITICAL, in decreasing order of priority. By
default, your bot will log all of these priorities. You can, however, ## default, your bot will log all of these priorities. You can, however,
specify that he only log messages above a certain priority level. Of ## specify that he only log messages above a certain priority level. Of
course, all error messages will still be logged.""") ## course, all error messages will still be logged.""")
priority = anything('What would you like the minimum priority to be? ' ## priority = anything('What would you like the minimum priority to be? '
'Just press enter to accept the default.') ## 'Just press enter to accept the default.')
while priority and priority not in ['verbose', 'low', 'normal', 'high']: ## while priority and priority not in ['verbose', 'low', 'normal', 'high']:
myPrint("""That's not a valid priority. Valid priorities include ## myPrint("""That's not a valid priority. Valid priorities include
'verbose,' 'low,' 'normal,' and 'high,' not including the quotes or ## 'verbose,' 'low,' 'normal,' and 'high,' not including the quotes or
the commas.""") ## the commas.""")
priority = anything('What would you like the minimum priority to be? ' ## priority = anything('What would you like the minimum priority to be? '
'Just press enter to accept the default.') ## 'Just press enter to accept the default.')
if priority: ## if priority:
debugVariables['minimumPriority'] = priority ## confVariables['minimumLogPriority'] = priority
if advanced: if advanced:
myPrint("""Here's some stuff you only get to choose if you're an myPrint("""Here's some stuff you only get to choose if you're an
@ -625,7 +624,6 @@ def main():
template = template.replace('"%%server%%"', repr(server)) template = template.replace('"%%server%%"', repr(server))
template = template.replace('"%%onStart%%"', format(onStart)) template = template.replace('"%%onStart%%"', format(onStart))
template = template.replace('"%%afterConnect%%"', format(afterConnect)) template = template.replace('"%%afterConnect%%"', format(afterConnect))
template = template.replace('"%%debugVariables%%"', format(debugVariables))
template = template.replace('"%%configVariables%%"', template = template.replace('"%%configVariables%%"',
format(configVariables)) format(configVariables))
template = template.replace('/usr/bin/env python', template = template.replace('/usr/bin/env python',

View File

@ -42,7 +42,6 @@ import time
from itertools import imap from itertools import imap
import conf import conf
import debug
import ircdb import ircdb
import utils import utils
import ircmsgs import ircmsgs

View File

@ -43,7 +43,6 @@ import getopt
from itertools import imap, ifilter from itertools import imap, ifilter
import conf import conf
import debug
import utils import utils
import irclib import irclib
import ircmsgs import ircmsgs
@ -54,7 +53,7 @@ import callbacks
class Misc(callbacks.Privmsg): class Misc(callbacks.Privmsg):
priority = sys.maxint priority = sys.maxint
def invalidCommand(self, irc, msg, tokens): def invalidCommand(self, irc, msg, tokens):
#debug.printf('Misc.invalidCommand called') self.log.debug('Misc.invalidCommand called')
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(msg, '%r is not a valid command.' % command)
@ -112,7 +111,8 @@ class Misc(callbacks.Privmsg):
not isinstance(cb, callbacks.PrivmsgRegexp): not isinstance(cb, callbacks.PrivmsgRegexp):
for attr in dir(cb): for attr in dir(cb):
if s in attr and cb.isCommand(attr): if s in attr and cb.isCommand(attr):
commands.setdefault(attr, []).append(cb.name()) if attr == callbacks.canonicalName(attr):
commands.setdefault(attr, []).append(cb.name())
for (key, names) in commands.iteritems(): for (key, names) in commands.iteritems():
if len(names) == 1: if len(names) == 1:
L.append(key) L.append(key)
@ -210,10 +210,13 @@ class Misc(callbacks.Privmsg):
irc.error(msg, 'Module %s has no __revision__.' % name) irc.error(msg, 'Module %s has no __revision__.' % name)
else: else:
def getVersion(s): def getVersion(s):
return s.split(None, 3)[2] try:
return s.split(None, 3)[2]
except:
self.log.exception('Couldn\'t get id string: %r', s)
names = {} names = {}
dirs = map(os.path.abspath, conf.pluginDirs) dirs = map(os.path.abspath, conf.pluginDirs)
for (name, module) in sys.modules.iteritems(): for (name, module) in sys.modules.items(): # Don't use iteritems.
if hasattr(module, '__revision__'): if hasattr(module, '__revision__'):
if 'supybot' in module.__file__: if 'supybot' in module.__file__:
names[name] = getVersion(module.__revision__) names[name] = getVersion(module.__revision__)
@ -251,7 +254,10 @@ class Misc(callbacks.Privmsg):
if file.endswith('.log'): if file.endswith('.log'):
stats = os.stat(os.path.join(conf.logDir, file)) stats = os.stat(os.path.join(conf.logDir, file))
result.append((file, str(stats.st_size))) result.append((file, str(stats.st_size)))
irc.reply(msg, ', '.join(imap(': '.join, result))) if result:
irc.reply(msg, ', '.join(imap(': '.join, result)))
else:
irc.reply(msg, 'I couldn\'t find any logfiles.')
def getprefixchar(self, irc, msg, args): def getprefixchar(self, irc, msg, args):
"""takes no arguments """takes no arguments

View File

@ -44,8 +44,8 @@ import imp
import sys import sys
import linecache import linecache
import log
import conf import conf
import debug
import utils import utils
import world import world
import ircdb import ircdb
@ -62,7 +62,7 @@ def loadPluginModule(name):
try: try:
files.extend(os.listdir(dir)) files.extend(os.listdir(dir))
except EnvironmentError: except EnvironmentError:
debug.msg('Invalid plugin directory: %s' % dir, 'verbose') log.warning('Invalid plugin directory: %s', dir)
loweredFiles = map(str.lower, files) loweredFiles = map(str.lower, files)
try: try:
index = loweredFiles.index(name.lower()+'.py') index = loweredFiles.index(name.lower()+'.py')
@ -188,9 +188,9 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
try: try:
irc.reply(msg, repr(eval(s))) irc.reply(msg, repr(eval(s)))
except SyntaxError, e: except SyntaxError, e:
irc.reply(msg, '%s: %r' % (debug.exnToString(e), s)) irc.reply(msg, '%s: %r' % (utils.exnToString(e), s))
except Exception, e: except Exception, e:
irc.reply(msg, debug.exnToString(e)) irc.reply(msg, utils.exnToString(e))
else: else:
irc.error(msg, conf.replyEvalNotAllowed) irc.error(msg, conf.replyEvalNotAllowed)
@ -205,7 +205,7 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
exec s exec s
irc.reply(msg, conf.replySuccess) irc.reply(msg, conf.replySuccess)
except Exception, e: except Exception, e:
irc.reply(msg, debug.exnToString(e)) irc.reply(msg, utils.exnToString(e))
else: else:
irc.error(msg, conf.replyEvalNotAllowed) irc.error(msg, conf.replyEvalNotAllowed)
@ -222,7 +222,7 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
try: try:
value = eval(value) value = eval(value)
except Exception, e: except Exception, e:
irc.error(msg, debug.exnToString(e)) irc.error(msg, utils.exnToString(e))
return return
setattr(conf, name, value) setattr(conf, name, value)
irc.reply(msg, conf.replySuccess) irc.reply(msg, conf.replySuccess)
@ -279,22 +279,6 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
conf.defaultCapabilities.remove(capability) conf.defaultCapabilities.remove(capability)
irc.reply(msg, conf.replySuccess) irc.reply(msg, conf.replySuccess)
def settrace(self, irc, msg, args):
"""takes no arguments
Starts the function-tracing debug mode; beware that this makes *huge*
logfiles.
"""
sys.settrace(debug.tracer)
irc.reply(msg, conf.replySuccess)
def unsettrace(self, irc, msg, args):
"""takes no arguments
Stops the function-tracing debug mode."""
sys.settrace(None)
irc.reply(msg, conf.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>
@ -303,10 +287,10 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
s = privmsgs.getArgs(args) s = privmsgs.getArgs(args)
try: try:
m = ircmsgs.IrcMsg(s) m = ircmsgs.IrcMsg(s)
except Exception, e:
irc.error(msg, utils.exnToString(e))
else:
irc.queueMsg(m) irc.queueMsg(m)
except Exception:
debug.recoverableException()
irc.error(msg, conf.replyError)
def quit(self, irc, msg, args): def quit(self, irc, msg, args):
"""[<int return value>] """[<int return value>]
@ -321,7 +305,7 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
driver.die() driver.die()
for irc in world.ircs[:]: for irc in world.ircs[:]:
irc.die() irc.die()
debug.exit(i) raise SystemExit
def flush(self, irc, msg, args): def flush(self, irc, msg, args):
"""takes no arguments """takes no arguments
@ -383,7 +367,7 @@ class Owner(privmsgs.CapabilityCheckingPrivmsg):
if name in str(e): if name in str(e):
irc.error(msg, 'No plugin %s exists.' % name) irc.error(msg, 'No plugin %s exists.' % name)
else: else:
irc.error(msg, debug.exnToString(e)) irc.error(msg, utils.exnToString(e))
return return
loadPluginClass(irc, module) loadPluginClass(irc, module)
irc.reply(msg, conf.replySuccess) irc.reply(msg, conf.replySuccess)

View File

@ -40,9 +40,9 @@ import socket
import asyncore import asyncore
import asynchat import asynchat
import repl import log
import conf import conf
import debug import repl
import ircdb import ircdb
import world import world
import drivers import drivers
@ -51,16 +51,15 @@ import schedule
class AsyncoreRunnerDriver(drivers.IrcDriver): class AsyncoreRunnerDriver(drivers.IrcDriver):
def run(self): def run(self):
#debug.printf(asyncore.socket_map) log.printf(repr(asyncore.socket_map))
try: try:
asyncore.poll(conf.poll) asyncore.poll(conf.poll)
except: except:
debug.recoverableException() log.exception('Uncaught exception:')
class AsyncoreDriver(asynchat.async_chat, object): class AsyncoreDriver(asynchat.async_chat, object):
def __init__(self, (server, port), irc): def __init__(self, (server, port), irc):
#debug.methodNamePrintf(self, '__init__')
asynchat.async_chat.__init__(self) asynchat.async_chat.__init__(self)
self.server = (server, port) self.server = (server, port)
self.irc = irc self.irc = irc
@ -71,22 +70,19 @@ class AsyncoreDriver(asynchat.async_chat, object):
try: try:
self.connect(self.server) self.connect(self.server)
except: except:
debug.recoverableException('terse') log.exception('Error connecting:')
self.close() self.close()
def scheduleReconnect(self): def scheduleReconnect(self):
#debug.methodNamePrintf(self, 'scheduleReconnect')
when = time.time() + 60 when = time.time() + 60
whenS = time.strftime(conf.logTimestampFormat, time.localtime(when)) whenS = time.strftime(conf.logTimestampFormat, time.localtime(when))
debug.msg('Scheduling reconnect to %s at %s' % (self.server, whenS), log.info('Scheduling reconnect to %s at %s', self.server, whenS)
'normal')
def makeNewDriver(): def makeNewDriver():
self.irc.reset() self.irc.reset()
driver = self.__class__(self.server, self.irc) driver = self.__class__(self.server, self.irc)
schedule.addEvent(makeNewDriver, when) schedule.addEvent(makeNewDriver, when)
def writable(self): def writable(self):
#debug.methodNamePrintf(self, 'writable')
while self.connected: while self.connected:
m = self.irc.takeMsg() m = self.irc.takeMsg()
if m: if m:
@ -96,38 +92,31 @@ class AsyncoreDriver(asynchat.async_chat, object):
return asynchat.async_chat.writable(self) return asynchat.async_chat.writable(self)
def handle_error(self): def handle_error(self):
#debug.recoverableException()
self.handle_close() self.handle_close()
def collect_incoming_data(self, s): def collect_incoming_data(self, s):
#debug.methodNamePrintf(self, 'collect_incoming_data')
self.buffer += s self.buffer += s
def found_terminator(self): def found_terminator(self):
#debug.methodNamePrintf(self, 'found_terminator')
start = time.time() start = time.time()
msg = ircmsgs.IrcMsg(self.buffer) msg = ircmsgs.IrcMsg(self.buffer)
debug.msg('Time to parse IrcMsg: %s' % (time.time()-start), 'verbose') log.verbose('Time to parse IrcMsg: %s', time.time()-start)
self.buffer = '' self.buffer = ''
try: try:
self.irc.feedMsg(msg) self.irc.feedMsg(msg)
except: except:
debug.msg('Exception caught outside Irc object.', 'normal') log.exception('Uncaught exception outside Irc object:')
debug.recoverableException()
def handle_close(self): def handle_close(self):
#debug.methodNamePrintf(self, 'handle_close')
self.scheduleReconnect() self.scheduleReconnect()
self.die() self.die()
reconnect = handle_close reconnect = handle_close
def handle_connect(self): def handle_connect(self):
#debug.methodNamePrintf(self, 'handle_connect')
pass pass
def die(self): def die(self):
#debug.methodNamePrintf(self, 'die')
self.close() self.close()
@ -141,7 +130,7 @@ class ReplListener(asyncore.dispatcher, object):
def handle_accept(self): def handle_accept(self):
(sock, addr) = self.accept() (sock, addr) = self.accept()
debug.msg('Connection made to telnet-REPL: ' + str(addr),'normal') log.info('Connection made to telnet-REPL: %s', addr)
Repl((sock, addr)) Repl((sock, addr))
@ -191,8 +180,7 @@ Name: """ % (world.version, sys.version.translate(string.ascii, '\r\n'))
self.push('Unknown user.\n') self.push('Unknown user.\n')
self.tries += 1 self.tries += 1
self.prompt = 'Name: ' self.prompt = 'Name: '
msg = 'Unknown user %s on telnet REPL.' % name log.warning('Unknown user %s on telnet REPL.', name)
debug.msg(msg,'high')
self.push(self.prompt) self.push(self.prompt)
elif self.u is not None and not self.authed: elif self.u is not None and not self.authed:
password = self.buffer password = self.buffer
@ -205,16 +193,16 @@ Name: """ % (world.version, sys.version.translate(string.ascii, '\r\n'))
self.push('Only owners can use this feature.\n') self.push('Only owners can use this feature.\n')
self.close() self.close()
msg = 'Attempted non-owner user %s on telnet REPL' % name msg = 'Attempted non-owner user %s on telnet REPL' % name
debug.msg(msg, 'high') log.warning(msg)
else: else:
self.push('Incorrect Password.\n') self.push('Incorrect Password.\n')
self.prompt = 'Name: ' self.prompt = 'Name: '
self.u = None self.u = None
msg = 'Invalid password for user %s on telnet REPL.' % name msg = 'Invalid password for user %s on telnet REPL.' % name
debug.msg(msg, 'high') log.warning(msg)
self.push(self.prompt) self.push(self.prompt)
elif self.authed: elif self.authed:
debug.msg('Telnet REPL: %s' % self.buffer) log.info('Telnet REPL: %s', self.buffer)
ret = self.repl.addLine(self.buffer+'\r\n') ret = self.repl.addLine(self.buffer+'\r\n')
self.buffer = '' self.buffer = ''
if ret is not repl.NotYet: if ret is not repl.NotYet:

View File

@ -56,8 +56,8 @@ import threading
from itertools import imap, ifilter from itertools import imap, ifilter
from cStringIO import StringIO from cStringIO import StringIO
import log
import conf import conf
import debug
import utils import utils
import world import world
import ircdb import ircdb
@ -199,7 +199,7 @@ class Tokenizer:
ends = [] ends = []
while True: while True:
token = lexer.get_token() token = lexer.get_token()
#debug.printf(repr(token)) log.printf(repr(token))
if not token: if not token:
break break
elif token == '|': elif token == '|':
@ -239,7 +239,7 @@ def tokenize(s):
_lastTokenized = None _lastTokenized = None
_lastTokenizedResult = None _lastTokenizedResult = None
raise SyntaxError, str(e) raise SyntaxError, str(e)
debug.msg('tokenize took %s seconds.' % (time.time() - start), 'verbose') log.verbose('tokenize took %s seconds.' % (time.time() - start))
return copy.deepcopy(_lastTokenizeResult) return copy.deepcopy(_lastTokenizeResult)
def getCommands(tokens): def getCommands(tokens):
@ -276,7 +276,7 @@ def formatArgumentError(method, name=None):
class IrcObjectProxy: class IrcObjectProxy:
"A proxy object to allow proper nested of commands (even threaded ones)." "A proxy object to allow proper nested of commands (even threaded ones)."
def __init__(self, irc, msg, args): def __init__(self, irc, msg, args):
#debug.printf('IrcObjectProxy.__init__: %s' % args) log.printf('IrcObjectProxy.__init__: %s' % args)
self.irc = irc self.irc = irc
self.msg = msg self.msg = msg
self.args = args self.args = args
@ -307,7 +307,7 @@ class IrcObjectProxy:
def _callInvalidCommands(self): def _callInvalidCommands(self):
for cb in self.irc.callbacks: for cb in self.irc.callbacks:
#debug.printf('Trying to call %s.invalidCommand' % cb.name()) log.printf('Trying to call %s.invalidCommand' % cb.name())
if self.finished: if self.finished:
break break
if hasattr(cb, 'invalidCommand'): if hasattr(cb, 'invalidCommand'):
@ -347,22 +347,21 @@ class IrcObjectProxy:
del self.args[0] del self.args[0]
cb = cbs[0] cb = cbs[0]
anticap = ircdb.makeAntiCapability(name) anticap = ircdb.makeAntiCapability(name)
#debug.printf('Checking for %s' % anticap) log.printf('Checking for %s' % anticap)
if ircdb.checkCapability(self.msg.prefix, anticap): if ircdb.checkCapability(self.msg.prefix, anticap):
#debug.printf('Being prevented with anticap') log.printf('Being prevented with anticap')
debug.msg('Preventing %s from calling %s' % \ log.info('Preventing %s from calling %s' %
(self.msg.nick, name), 'normal') (self.msg.nick, name))
s = conf.replyNoCapability % name s = conf.replyNoCapability % name
self.error(self.msg, s, private=True) self.error(self.msg, s, private=True)
return return
recipient = self.msg.args[0] recipient = self.msg.args[0]
if ircutils.isChannel(recipient): if ircutils.isChannel(recipient):
chancap = ircdb.makeChannelCapability(recipient, anticap) chancap = ircdb.makeChannelCapability(recipient, anticap)
#debug.printf('Checking for %s' % chancap)
if ircdb.checkCapability(self.msg.prefix, chancap): if ircdb.checkCapability(self.msg.prefix, chancap):
#debug.printf('Being prevented with chancap') log.printf('Being prevented with chancap')
debug.msg('Preventing %s from calling %s' % \ log.info('Preventing %s from calling %s' %
(self.msg.nick, name), 'normal') (self.msg.nick, name))
s = conf.replyNoCapability % name s = conf.replyNoCapability % name
self.error(self.msg, s, private=True) self.error(self.msg, s, private=True)
return return
@ -380,10 +379,10 @@ class IrcObjectProxy:
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(self.msg, 'Command %r cannot be nested.' % name)
except (SyntaxError, Error), e: except (SyntaxError, Error), e:
self.reply(self.msg, debug.exnToString(e)) self.reply(self.msg, utils.exnToString(e))
except Exception, e: except Exception, e:
debug.recoverableException() log.exception('Uncaught exception in finalEval:')
self.error(self.msg, debug.exnToString(e)) self.error(self.msg, utils.exnToString(e))
def reply(self, msg, s, noLengthCheck=False, prefixName=True, def reply(self, msg, s, noLengthCheck=False, prefixName=True,
action=False, private=False, notice=False, to=None): action=False, private=False, notice=False, to=None):
@ -496,7 +495,7 @@ class CommandThread(threading.Thread):
name = '%s.%s with args %r' % (self.className, self.commandName, args) name = '%s.%s with args %r' % (self.className, self.commandName, args)
threading.Thread.__init__(self, target=callCommand, name=name, threading.Thread.__init__(self, target=callCommand, name=name,
args=(command, irc, msg, args)+L) args=(command, irc, msg, args)+L)
debug.msg('Spawning thread %s' % name, 'verbose') log.verbose('Spawning thread %s' % name)
self.irc = irc self.irc = irc
self.msg = msg self.msg = msg
self.setDaemon(True) self.setDaemon(True)
@ -512,10 +511,10 @@ class CommandThread(threading.Thread):
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(self.msg, s)
except (SyntaxError, Error), e: except (SyntaxError, Error), e:
self.irc.reply(self.msg, debug.exnToString(e)) self.irc.reply(self.msg, utils.exnToString(e))
except Exception, e: except Exception, e:
debug.recoverableException() log.exception('Uncaught exception in CommandThread.run:')
self.irc.error(self.msg, debug.exnToString(e)) self.irc.error(self.msg, utils.exnToString(e))
class ConfigIrcProxy(object): class ConfigIrcProxy(object):
@ -527,7 +526,7 @@ class ConfigIrcProxy(object):
return None return None
def error(self, msg, s, *args): def error(self, msg, s, *args):
debug.msg('ConfigIrcProxy saw an error: %s' % s, 'normal') log.info('ConfigIrcProxy saw an error: %s' % s)
def getRealIrc(self): def getRealIrc(self):
irc = self.__dict__['irc'] irc = self.__dict__['irc']
@ -554,7 +553,10 @@ class Privmsg(irclib.IrcCallback):
def __init__(self): def __init__(self):
self.__parent = super(Privmsg, self) self.__parent = super(Privmsg, self)
self.Proxy = IrcObjectProxy self.Proxy = IrcObjectProxy
canonicalname = canonicalName(self.name()) myName = self.name()
self.log = log.getPluginLogger(myName)
### Setup the dispatcher command.
canonicalname = canonicalName(myName)
self._original = getattr(self, canonicalname, None) self._original = getattr(self, canonicalname, None)
docstring = """<command> [<args> ...] docstring = """<command> [<args> ...]
@ -562,7 +564,7 @@ class Privmsg(irclib.IrcCallback):
commands provided by this plugin. In most cases this dispatcher commands provided by this plugin. In most cases this dispatcher
command is unnecessary; in cases where more than one plugin defines a command is unnecessary; in cases where more than one plugin defines a
given command, use this command to tell the bot which plugin's command given command, use this command to tell the bot which plugin's command
to use.""" % (self.name(), self.name()) to use.""" % (myName, myName)
def dispatcher(self, irc, msg, args): def dispatcher(self, irc, msg, args):
def handleBadArgs(): def handleBadArgs():
if self._original: if self._original:
@ -599,7 +601,7 @@ class Privmsg(irclib.IrcCallback):
args = args[:] args = args[:]
command = canonicalName(args.pop(0)) command = canonicalName(args.pop(0))
if self.isCommand(command): if self.isCommand(command):
#debug.printf('%s: %r' % (command, args)) self.log.debug('%s: %r', command, args)
method = getattr(self, command) method = getattr(self, command)
line = '%s %s' % (command, ' '.join(imap(utils.dqrepr, args))) line = '%s %s' % (command, ' '.join(imap(utils.dqrepr, args)))
msg = ircmsgs.privmsg(fakeIrc.nick, line, fakeIrc.prefix) msg = ircmsgs.privmsg(fakeIrc.nick, line, fakeIrc.prefix)
@ -614,7 +616,7 @@ class Privmsg(irclib.IrcCallback):
if self.noIgnore or not ircdb.checkIgnored(msg.prefix,msg.args[0]): if self.noIgnore or not ircdb.checkIgnored(msg.prefix,msg.args[0]):
self.__parent.__call__(irc, msg) self.__parent.__call__(irc, msg)
else: else:
debug.msg('Ignoring %s.' % msg.prefix) self.log.info('Ignoring %s', msg.prefix)
else: else:
self.__parent.__call__(irc, msg) self.__parent.__call__(irc, msg)
@ -637,8 +639,7 @@ class Privmsg(irclib.IrcCallback):
start = time.time() start = time.time()
f(irc, msg, *L) f(irc, msg, *L)
elapsed = time.time() - start elapsed = time.time() - start
funcname = '%s.%s' % (f.im_class.__name__, f.im_func.func_name) self.log.info('%s took %s seconds', f.im_func.func_name, elapsed)
debug.msg('%s took %s seconds' % (funcname, elapsed), 'verbose')
class IrcObjectProxyRegexp(object): class IrcObjectProxyRegexp(object):
@ -696,18 +697,15 @@ class PrivmsgRegexp(Privmsg):
r = re.compile(value.__doc__, self.flags) r = re.compile(value.__doc__, self.flags)
self.res.append((r, value)) self.res.append((r, value))
except re.error, e: except re.error, e:
s = '%s.%s has an invalid regexp %s: %s' % \ self.log.warning('Invalid regexp: %r (%s)',value.__doc__,e)
(self.__class__.__name__, name,
value.__doc__, debug.exnToString(e))
debug.msg(s)
self.res.sort(lambda (r1, m1), (r2, m2): cmp(m1.__name__, m2.__name__)) self.res.sort(lambda (r1, m1), (r2, m2): cmp(m1.__name__, m2.__name__))
def callCommand(self, method, irc, msg, *L): def callCommand(self, method, irc, msg, *L):
try: try:
self.__parent.callCommand(method, irc, msg, *L) self.__parent.callCommand(method, irc, msg, *L)
except Exception, e: except Exception, e:
debug.recoverableException() self.log.exception('Uncaught exception from callCommand:')
irc.error(msg, debug.exnToString(e)) irc.error(msg, utils.exnToString(e))
def doPrivmsg(self, irc, msg): def doPrivmsg(self, irc, msg):
for (r, method) in self.res: for (r, method) in self.res:
@ -749,8 +747,8 @@ class PrivmsgCommandAndRegexp(Privmsg):
self.__parent.callCommand(f, irc, msg, *L) self.__parent.callCommand(f, irc, msg, *L)
except Exception, e: except Exception, e:
if 'catchErrors' in kwargs and kwargs['catchErrors']: if 'catchErrors' in kwargs and kwargs['catchErrors']:
irc.error(msg, debug.exnToString(e)) self.log.exception('Uncaught exception in callCommand:')
debug.recoverableException() irc.error(msg, utils.exnToString(e))
else: else:
raise raise

View File

@ -37,6 +37,7 @@ import sys
import sets import sets
import os.path import os.path
import logging
### ###
# Directions: # Directions:
@ -59,6 +60,18 @@ pluginDirs = [os.path.join(installDir, s) for s in ('src', 'plugins')]
userfile = 'users.conf' userfile = 'users.conf'
channelfile = 'channels.conf' channelfile = 'channels.conf'
###
# minimumLogPriority: The minimum priority that will be logged. Defaults to
# logging.INFO, which is probably a good value. Can also
# be usefully set to logging.{DEBUG,WARNING,ERROR,CRITICAL}
###
minimumLogPriority = logging.INFO
###
# stdoutLogging: Determines whether or not the bot logs to stdout.
###
stdoutLogging = True
### ###
# logTimestampFormat: A format string defining how timestamps should be. Check # logTimestampFormat: A format string defining how timestamps should be. Check
# the Python library reference for the "time" module to see # the Python library reference for the "time" module to see

View File

@ -41,9 +41,9 @@ import re
import os import os
import sys import sys
import log
import conf import conf
import ansi import ansi
import debug
import ircmsgs import ircmsgs
_drivers = {} _drivers = {}
@ -134,7 +134,7 @@ def run():
if name not in _deadDrivers: if name not in _deadDrivers:
driver.run() driver.run()
except: except:
debug.recoverableException() log.exception('Uncaught exception in in drivers.run:')
_deadDrivers.append(name) _deadDrivers.append(name)
for name in _deadDrivers: for name in _deadDrivers:
try: try:

View File

@ -39,8 +39,8 @@ import time
import string import string
from itertools import imap from itertools import imap
import log
import conf import conf
import debug
import utils import utils
import world import world
import ircutils import ircutils
@ -589,40 +589,30 @@ def _x(capability, ret):
def _checkCapabilityForUnknownUser(capability, users=users, channels=channels): def _checkCapabilityForUnknownUser(capability, users=users, channels=channels):
if isChannelCapability(capability): if isChannelCapability(capability):
#debug.printf('isChannelCapability true.')
(channel, capability) = fromChannelCapability(capability) (channel, capability) = fromChannelCapability(capability)
try: try:
c = channels.getChannel(channel) c = channels.getChannel(channel)
if capability in c.capabilities: if capability in c.capabilities:
#debug.printf('capability in c.capabilities')
return c.checkCapability(capability) return c.checkCapability(capability)
else: else:
#debug.printf('capability not in c.capabilities')
return _x(capability, c.defaultAllow) return _x(capability, c.defaultAllow)
except KeyError: except KeyError:
#debug.printf('no such channel %s' % channel)
pass pass
if capability in conf.defaultCapabilities: if capability in conf.defaultCapabilities:
#debug.printf('capability in conf.defaultCapability')
return True return True
elif invertCapability(capability) in conf.defaultCapabilities: elif invertCapability(capability) in conf.defaultCapabilities:
#debug.printf('inverse capability in conf.defaultCapability')
return False return False
else: else:
#debug.printf('returning appropriate value given no good reason')
return _x(capability, conf.defaultAllow) return _x(capability, conf.defaultAllow)
def checkCapability(hostmask, capability, users=users, channels=channels): def checkCapability(hostmask, capability, users=users, channels=channels):
"""Checks that the user specified by name/hostmask has the capabilty given. """Checks that the user specified by name/hostmask has the capabilty given.
""" """
#debug.printf('*** checking %s for %s' % (hostmask, capability))
if world.startup: if world.startup:
#debug.printf('world.startup is active.')
return _x(capability, True) return _x(capability, True)
try: try:
u = users.getUser(hostmask) u = users.getUser(hostmask)
if u.secure and not u.checkHostmask(hostmask, useAuth=False): if u.secure and not u.checkHostmask(hostmask, useAuth=False):
#debug.printf('Secure user with non-matching hostmask.')
raise KeyError raise KeyError
except KeyError: except KeyError:
# Raised when no hostmasks match. # Raised when no hostmasks match.
@ -630,16 +620,13 @@ def checkCapability(hostmask, capability, users=users, channels=channels):
channels=channels) channels=channels)
except ValueError, e: except ValueError, e:
# Raised when multiple hostmasks match. # Raised when multiple hostmasks match.
debug.msg('%s: %s' % (hostmask, e)) log.warning('%s: %s', hostmask, e)
return _checkCapabilityForUnknownUser(capability, users=users, return _checkCapabilityForUnknownUser(capability, users=users,
channels=channels) channels=channels)
#debug.printf('user found.')
if capability in u.capabilities: if capability in u.capabilities:
#debug.printf('found capability in u.capabilities.')
return u.checkCapability(capability) return u.checkCapability(capability)
else: else:
if isChannelCapability(capability): if isChannelCapability(capability):
#debug.printf('isChannelCapability true, user found too.')
(channel, capability) = fromChannelCapability(capability) (channel, capability) = fromChannelCapability(capability)
try: try:
chanop = makeChannelCapability(channel, 'op') chanop = makeChannelCapability(channel, 'op')
@ -649,19 +636,14 @@ def checkCapability(hostmask, capability, users=users, channels=channels):
pass pass
c = channels.getChannel(channel) c = channels.getChannel(channel)
if capability in c.capabilities: if capability in c.capabilities:
#debug.printf('capability in c.capabilities')
return c.checkCapability(capability) return c.checkCapability(capability)
else: else:
#debug.printf('capability not in c.capabilities')
return _x(capability, c.defaultAllow) return _x(capability, c.defaultAllow)
if capability in conf.defaultCapabilities: if capability in conf.defaultCapabilities:
#debug.printf('capability in conf.defaultCapabilities')
return True return True
elif invertCapability(capability) in conf.defaultCapabilities: elif invertCapability(capability) in conf.defaultCapabilities:
#debug.printf('inverse capability in conf.defaultCapabilities')
return False return False
else: else:
#debug.printf('returning appropriate value given no good reason')
return _x(capability, conf.defaultAllow) return _x(capability, conf.defaultAllow)

View File

@ -38,8 +38,8 @@ import sets
import time import time
from itertools import imap, chain from itertools import imap, chain
import log
import conf import conf
import debug
import utils import utils
import world import world
import ircdb import ircdb
@ -102,10 +102,8 @@ class IrcCallback(IrcCommandDispatcher):
try: try:
method(irc, msg) method(irc, msg)
except Exception, e: except Exception, e:
debug.recoverableException() s = 'Exception caught in generic IrcCallback.__call__:'
s = 'Exception (%s) raised by %s.%s' % \ log.exception(s)
(e, self.__class__.__name__, method.im_func.func_name)
debug.msg(s)
def reset(self): def reset(self):
"""Resets the callback. Called when reconnected to the server.""" """Resets the callback. Called when reconnected to the server."""
@ -151,7 +149,7 @@ class IrcMsgQueue(object):
"""Enqueues a given message.""" """Enqueues a given message."""
if msg in self.msgs: if msg in self.msgs:
if not world.startup: if not world.startup:
debug.msg('Not adding msg %s to queue' % msg, 'normal') log.info('Not adding msg %s to queue' % msg)
else: else:
self.msgs.add(msg) self.msgs.add(msg)
if msg.command in _high: if msg.command in _high:
@ -163,18 +161,19 @@ class IrcMsgQueue(object):
def dequeue(self): def dequeue(self):
"""Dequeues a given message.""" """Dequeues a given message."""
msg = None
if self.highpriority: if self.highpriority:
msg = self.highpriority.dequeue() msg = self.highpriority.dequeue()
elif self.normal: elif self.normal:
msg = self.normal.dequeue() msg = self.normal.dequeue()
elif self.lowpriority: elif self.lowpriority:
msg = self.lowpriority.dequeue() msg = self.lowpriority.dequeue()
else:
msg = None
if msg: if msg:
if msg not in self.msgs: try:
debug.msg('Odd, dequeuing a message that\'s not in self.msgs.') self.msgs.remove(msg)
self.msgs.discard(msg) except KeyError:
s = 'Odd, dequeuing a message that\'s not in self.msgs.'
log.warning(s)
return msg return msg
def __nonzero__(self): def __nonzero__(self):
@ -404,10 +403,10 @@ class Irc(IrcCommandDispatcher):
'333', '353', '332', '366', '005']) '333', '353', '332', '366', '005'])
def __init__(self, nick, user='', ident='', password='', callbacks=None): def __init__(self, nick, user='', ident='', password='', callbacks=None):
world.ircs.append(self) world.ircs.append(self)
self.nick = nick self.nick = intern(nick)
self.password = password self.password = password
self.user = user or nick # Default to nick if user isn't provided. self.user = intern(user or nick) # Default to nick
self.ident = ident or nick # Ditto. self.ident = intern(ident or nick) # Ditto.
self.prefix = '%s!%s@%s' % (nick, ident, 'unset.domain') self.prefix = '%s!%s@%s' % (nick, ident, 'unset.domain')
if callbacks is None: if callbacks is None:
self.callbacks = [] self.callbacks = []
@ -481,13 +480,14 @@ class Irc(IrcCommandDispatcher):
msg = self.fastqueue.dequeue() msg = self.fastqueue.dequeue()
elif self.queue: elif self.queue:
if not world.testing and now - self.lastTake <= conf.throttleTime: if not world.testing and now - self.lastTake <= conf.throttleTime:
debug.msg('Irc.takeMsg throttling.', 'verbose') log.debug('Irc.takeMsg throttling.')
else: else:
self.lastTake = now self.lastTake = now
msg = self.queue.dequeue() msg = self.queue.dequeue()
elif now > (self.lastping + conf.pingInterval): elif now > (self.lastping + conf.pingInterval):
if self.outstandingPing: if self.outstandingPing:
debug.msg('Reconnecting, ping not replied to.', 'normal') s = 'Reconnecting to %s, ping not replied to.' % self.server
log.warning(s)
self.driver.reconnect() self.driver.reconnect()
self.reset() self.reset()
else: else:
@ -497,7 +497,7 @@ class Irc(IrcCommandDispatcher):
self.queueMsg(ircmsgs.ping(now)) self.queueMsg(ircmsgs.ping(now))
if msg: if msg:
for callback in reviter(self.callbacks): for callback in reviter(self.callbacks):
#debug.printf(repr(msg)) log.debug(repr(msg))
try: try:
outFilter = getattr(callback, 'outFilter') outFilter = getattr(callback, 'outFilter')
except AttributeError, e: except AttributeError, e:
@ -505,18 +505,18 @@ class Irc(IrcCommandDispatcher):
try: try:
msg = outFilter(self, msg) msg = outFilter(self, msg)
except: except:
debug.recoverableException() log.exception('Exception caught in outFilter:')
continue continue
if msg is None: if msg is None:
s = '%s.outFilter returned None' % callback.name() log.debug('%s.outFilter returned None' % callback.name())
debug.msg(s) return self.takeMsg()
return None
if len(str(msg)) > 512: if len(str(msg)) > 512:
# Yes, this violates the contract, but at this point it doesn't
# matter. That's why we gotta go munging in private attributes
msg._str = msg._str[:500] + '\r\n' msg._str = msg._str[:500] + '\r\n'
msg._len = len(str(msg)) msg._len = len(str(msg))
self.state.addMsg(self, msg) self.state.addMsg(self, msg)
s = '%s %s' % (time.strftime(conf.logTimestampFormat), msg) log.info('Outgoing message: ' + str(msg).rstrip('\r\n'))
debug.msg(s, 'low')
if msg.command == 'NICK': if msg.command == 'NICK':
# We don't want a race condition where the server's NICK # We don't want a race condition where the server's NICK
# back to us is lost and someone else steals our nick and uses # back to us is lost and someone else steals our nick and uses
@ -562,36 +562,31 @@ class Irc(IrcCommandDispatcher):
def doNick(self, msg): def doNick(self, msg):
"""Handles NICK messages.""" """Handles NICK messages."""
if msg.nick == self.nick: if msg.nick == self.nick:
newNick = msg.args[0] newNick = intern(msg.args[0])
user = ircdb.users.getUser(0) user = ircdb.users.getUser(0)
user.unsetAuth() user.unsetAuth()
user.hostmasks = [] user.hostmasks = []
try: try:
ircdb.users.getUser(newNick) ircdb.users.getUser(newNick)
s = 'User already registered with name %s' % newNick log.error('User already registered with name %s' % newNick)
debug.msg(s, 'high')
except KeyError: except KeyError:
user.name = newNick user.name = newNick
ircdb.users.setUser(0, user) ircdb.users.setUser(0, user)
self.nick = newNick self.nick = newNick
(nick, user, domain) = ircutils.splitHostmask(msg.prefix) (nick, user, domain) = ircutils.splitHostmask(msg.prefix)
self.prefix = ircutils.joinHostmask(self.nick, user, domain) self.prefix = ircutils.joinHostmask(self.nick, user, domain)
self.prefix = intern(self.prefix)
def feedMsg(self, msg): def feedMsg(self, msg):
"""Called by the IrcDriver; feeds a message received.""" """Called by the IrcDriver; feeds a message received."""
debug.msg('%s %s'%(time.strftime(conf.logTimestampFormat), msg),'low') log.info('Incoming message: ' + str(msg).rstrip('\r\n'))
# Yeah, so this is odd. Some networks (oftc) seem to give us certain # Yeah, so this is odd. Some networks (oftc) seem to give us certain
# messages with our nick instead of our prefix. We'll fix that here. # messages with our nick instead of our prefix. We'll fix that here.
if msg.prefix == self.nick: if msg.prefix == self.nick:
debug.msg('Got one of those odd nick-instead-of-prefix msgs.') log.debug('Got one of those odd nick-instead-of-prefix msgs.')
msg = ircmsgs.IrcMsg(prefix=self.prefix, msg=msg) msg = ircmsgs.IrcMsg(prefix=self.prefix, msg=msg)
# Dispatch to specific handlers for commands.
method = self.dispatchCommand(msg.command)
if method is not None:
method(msg)
# This catches cases where we know our own nick (from sending it to the # This catches cases where we know our own nick (from sending it to the
# server) but we don't yet know our prefix. # server) but we don't yet know our prefix.
if msg.nick == self.nick and self.prefix != msg.prefix: if msg.nick == self.nick and self.prefix != msg.prefix:
@ -610,32 +605,37 @@ class Irc(IrcCommandDispatcher):
if msg.prefix != self.server: if msg.prefix != self.server:
self.server = msg.prefix self.server = msg.prefix
# Dispatch to specific handlers for commands.
method = self.dispatchCommand(msg.command)
if method is not None:
method(msg)
# Now update the IrcState object. # Now update the IrcState object.
try: try:
self.state.addMsg(self, msg) self.state.addMsg(self, msg)
except: except:
debug.recoverableException() log.exception('Exception in update of IrcState object:')
# Now call the callbacks. # Now call the callbacks.
for callback in self.callbacks: for callback in self.callbacks:
try: try:
m = callback.inFilter(self, msg) m = callback.inFilter(self, msg)
if not m: if not m:
s = '%s.inFilter returned None' % callback.name() log.debug('%s.inFilter returned None' % callback.name())
debug.msg(s)
return return
msg = m msg = m
except: except:
debug.recoverableException() log.exception('Uncaught exception in inFilter:')
for callback in self.callbacks: for callback in self.callbacks:
try: try:
if callback is not None: if callback is not None:
callback(self, msg) callback(self, msg)
except: except:
debug.recoverableException() log.exception('Uncaught exception in callback:')
def die(self): def die(self):
"""Makes the Irc object die. Dead.""" """Makes the Irc object die. Dead."""
log.info('Irc object for %s dying.' % self.server)
for callback in self.callbacks: for callback in self.callbacks:
callback.die() callback.die()
if self.driver is not None: if self.driver is not None:

View File

@ -43,7 +43,6 @@ import fix
import re import re
import string import string
import debug
import ircutils import ircutils
### ###
@ -124,13 +123,14 @@ class IrcMsg(object):
else: else:
self.args = msg.args self.args = msg.args
else: else:
self.prefix = prefix self.prefix = intern(prefix)
self.command = command self.command = intern(command)
assert all(ircutils.isValidArgument, args) assert all(ircutils.isValidArgument, args)
self.args = args self.args = args
self.args = tuple(self.args) self.args = tuple(map(intern, self.args))
if ircutils.isUserHostmask(self.prefix): if ircutils.isUserHostmask(self.prefix):
(self.nick,self.user,self.host)=ircutils.splitHostmask(self.prefix) (self.nick,self.user,self.host) = \
map(intern, ircutils.splitHostmask(self.prefix))
else: else:
(self.nick, self.user, self.host) = (self.prefix,)*3 (self.nick, self.user, self.host) = (self.prefix,)*3

View File

@ -94,7 +94,7 @@ _lowertrans = string.maketrans(string.ascii_uppercase + r'\[]~',
string.ascii_lowercase + r'|{}^') string.ascii_lowercase + r'|{}^')
def toLower(s): def toLower(s):
"""Returns the string s lowered according to IRC case rules.""" """Returns the string s lowered according to IRC case rules."""
return s.translate(_lowertrans) return intern(s.translate(_lowertrans))
def nickEqual(nick1, nick2): def nickEqual(nick1, nick2):
"""Returns True if nick1 == nick2 according to IRC case rules.""" """Returns True if nick1 == nick2 according to IRC case rules."""
@ -329,7 +329,7 @@ def unDccIP(i):
class IrcString(str): class IrcString(str):
"""This class does case-insensitive comparison and hashing of nicks.""" """This class does case-insensitive comparison and hashing of nicks."""
def __init__(self, s): def __init__(self, s):
str.__init__(self, s) str.__init__(self, intern(s))
self.lowered = toLower(s) self.lowered = toLower(s)
def __eq__(self, s): def __eq__(self, s):

132
src/log.py Normal file
View File

@ -0,0 +1,132 @@
#!/usr/bin/env python
###
# Copyright (c) 2002, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
__revision__ = "$Id$"
import fix
import os
import sys
import atexit
import logging
import conf
deadlyExceptions = [KeyboardInterrupt, SystemExit]
if not os.path.exists(conf.logDir):
os.mkdir(conf.logDir, 0755)
pluginLogDir = os.path.join(conf.logDir, 'plugins')
if not os.path.exists(pluginLogDir):
os.mkdir(pluginLogDir, 0755)
class Formatter(logging.Formatter):
def formatTime(self, record, datefmt=None):
if datefmt is None:
datefmt = conf.logTimestampFormat
return logging.Formatter.formatTime(self, record, datefmt)
def formatException(self, (E, e, tb)):
for exn in deadlyExceptions:
if issubclass(e.__class__, exn):
raise
### TODO: formatException should use cgitb.
return logging.Formatter.formatException(self, (E, e, tb))
class DailyRotatingHandler(logging.FileHandler):
def __init__(self, *args):
self.lastRollover = time.localtime()
logging.FileHandler.__init__(self, *args)
def emit(self, record):
now = time.localtime()
if now[2] != self.lastRollover[2]:
self.doRollover()
self.lastRollover = now
logging.FileHandler.emit(self, record)
def doRollover(self):
self.stream.close()
extension = time.strftime('%d-%b-%Y', self.lastRollover)
os.rename(self.baseFilename, '%s.%s' % (self.baseFilename, extension))
self.stream = file(self.baseFilename, 'w')
# This is available publically.
formatter = Formatter('%(levelname)s %(asctime)s %(message)s')
pluginFormatter = Formatter('%(levelname)s %(asctime)s %(name)s %(message)s')
# These are not.
_logger = logging.getLogger('supybot')
_handler = logging.FileHandler(os.path.join(conf.logDir, 'misc.log'))
_handler.setFormatter(formatter)
_handler.setLevel(conf.minimumLogPriority)
_logger.addHandler(_handler)
_logger.setLevel(-1)
if conf.stdoutLogging:
_stdoutHandler = logging.StreamHandler(sys.stdout)
_stdoutHandler.setLevel(conf.minimumLogPriority)
_logger.addHandler(_stdoutHandler)
debug = _logger.debug
info = _logger.info
warning = _logger.warning
error = _logger.error
critical = _logger.critical
exception = _logger.exception
printf = curry(_logger.log, 1)
logging.PRINTF = 1
logging._levelNames['PRINTF'] = logging.PRINTF
logging._levelNames[logging.PRINTF] = 'PRINTF'
verbose = curry(_logger.log, 5)
logging.VERBOSE = 5
logging._levelNames['VERBOSE'] = logging.VERBOSE
logging._levelNames[logging.VERBOSE] = 'VERBOSE'
atexit.register(logging.shutdown)
def getPluginLogger(name):
log = logging.getLogger('supybot.plugins.%s' % name)
if not log.handlers:
filename = os.path.join(pluginLogDir, '%s.log' % name)
handler = logging.FileHandler(filename)
handler.setLevel(conf.minimumLogPriority)
handler.setFormatter(pluginFormatter)
log.addHandler(handler)
return log
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:

View File

@ -49,7 +49,6 @@ __revision__ = "$Id$"
import fix import fix
import cdb import cdb
import conf import conf
import debug
import utils import utils
import world import world
import ircdb import ircdb
@ -203,8 +202,7 @@ class PeriodicFileDownloader(object):
s = infd.read(4096) s = infd.read(4096)
infd.close() infd.close()
outfd.close() outfd.close()
msg = 'Downloaded %s in %s seconds' % (filename, time.time() - start) self.log.info('Downloaded %s in %s seconds',filename,time.time()-start)
debug.msg(msg, 'verbose')
self.downloadedCounter[filename] += 1 self.downloadedCounter[filename] += 1
self.lastDownloaded[filename] = time.time() self.lastDownloaded[filename] = time.time()
if f is None: if f is None:
@ -218,15 +216,14 @@ class PeriodicFileDownloader(object):
start = time.time() start = time.time()
f(newFilename) f(newFilename)
total = time.time() - start total = time.time() - start
msg = 'Function ran on %s in %s seconds' % (filename, total) self.log.info('Function ran on %s in %s seconds', filename, total)
debug.msg(msg, 'verbose')
self.currentlyDownloading.remove(filename) self.currentlyDownloading.remove(filename)
def getFile(self, filename): def getFile(self, filename):
(url, timeLimit, f) = self.periodicFiles[filename] (url, timeLimit, f) = self.periodicFiles[filename]
if time.time() - self.lastDownloaded[filename] > timeLimit and \ if time.time() - self.lastDownloaded[filename] > timeLimit and \
filename not in self.currentlyDownloading: filename not in self.currentlyDownloading:
debug.msg('Beginning download of %s' % url, 'verbose') self.log.info('Beginning download of %s', url)
self.currentlyDownloading.add(filename) self.currentlyDownloading.add(filename)
args = (filename, url, f) args = (filename, url, f)
name = '%s #%s' % (filename, self.downloadedCounter[filename]) name = '%s #%s' % (filename, self.downloadedCounter[filename])
@ -345,12 +342,11 @@ class Configurable(object):
try: try:
self.configurables.set(name, eval(value), channel) self.configurables.set(name, eval(value), channel)
except ConfigurableTypeError, e: except ConfigurableTypeError, e:
name = '%s.%s' % (self.__class__.__name__, name) s = 'Couldn\'t read configurable from file: %s'
s = 'Couldn\'t read configurable %s from file: %s'%(name,e) self.log.warning(s, e)
debug.msg(s)
except KeyError, e: except KeyError, e:
s = 'Configurable variable %s doesn\'t exist anymore'%name s = 'Configurable variable %s doesn\'t exist anymore.'
debug.msg(s) self.log.warning(s, name)
def die(self): def die(self):
fd = file(self.filename, 'w') fd = file(self.filename, 'w')

View File

@ -42,7 +42,6 @@ import types
import threading import threading
import conf import conf
import debug
import ircdb import ircdb
import world import world
import ircutils import ircutils
@ -166,14 +165,12 @@ def urlSnarfer(f):
if q is None: if q is None:
q = structures.smallqueue() q = structures.smallqueue()
self._snarfedUrls = q self._snarfedUrls = q
#debug.printf('before pruning: %r' % q)
while q and q[0][2] < cutoff: while q and q[0][2] < cutoff:
q.dequeue() q.dequeue()
#debug.printf('after pruning: %r' % q)
url = match.group(0) url = match.group(0)
if any(lambda t: t[0] == url and t[1] == msg.args[0], q) and \ if any(lambda t: t[0] == url and t[1] == msg.args[0], q) and \
not world.testing: not world.testing:
debug.msg('Refusing to snarf %s.' % url) self.log.warning('Refusing to snarf %s.', url)
else: else:
q.enqueue((url, msg.args[0], now)) q.enqueue((url, msg.args[0], now))
if self.threaded: if self.threaded:

View File

@ -39,7 +39,7 @@ import sys
import traceback import traceback
from cStringIO import StringIO from cStringIO import StringIO
import debug import log
filename = 'repl' filename = 'repl'
@ -86,7 +86,7 @@ class Repl(object):
line = line.rstrip() line = line.rstrip()
self.lines.append(line) self.lines.append(line)
if len(self.lines) > 100: if len(self.lines) > 100:
debug.msg('too many lines in Repl.', 'normal') log.warning('Too many lines in Repl.')
self.lines = [] self.lines = []
return None return None
if line == '' or line == '\n' or line == '\r\n': if line == '' or line == '\n' or line == '\r\n':

View File

@ -76,7 +76,6 @@ class Schedule(drivers.IrcDriver):
self.counter += 1 self.counter += 1
elif isinstance(name, int): elif isinstance(name, int):
raise ValueError, 'int names are reserved for the scheduler.' raise ValueError, 'int names are reserved for the scheduler.'
#debug.printf('Added event to schedule: %s' % name)
assert name not in self.events assert name not in self.events
self.events[name] = f self.events[name] = f
heapq.heappush(self.schedule, mytuple((t, name))) heapq.heappush(self.schedule, mytuple((t, name)))
@ -97,7 +96,6 @@ class Schedule(drivers.IrcDriver):
removePeriodicEvent = removeEvent removePeriodicEvent = removeEvent
def run(self): def run(self):
#debug.printf(`(time.time(), self.schedule)`)
while self.schedule and self.schedule[0][0] < time.time(): while self.schedule and self.schedule[0][0] < time.time():
(t, name) = heapq.heappop(self.schedule) (t, name) = heapq.heappop(self.schedule)
f = self.events[name] f = self.events[name]

View File

@ -35,7 +35,7 @@ Contains simple socket drivers. Asyncore bugged (haha, pun!) me.
from __future__ import division from __future__ import division
__revision__ = "$Id$" __revision__ ="$Id$"
import fix import fix
@ -43,8 +43,8 @@ import time
import socket import socket
from itertools import imap from itertools import imap
import log
import conf import conf
import debug
import drivers import drivers
import ircmsgs import ircmsgs
import schedule import schedule
@ -69,7 +69,6 @@ class SocketDriver(drivers.IrcDriver):
self.reconnect() self.reconnect()
def _sendIfMsgs(self): def _sendIfMsgs(self):
#debug.methodNamePrintf(self, '_sendIfMsgs')
msgs = [self.irc.takeMsg()] msgs = [self.irc.takeMsg()]
while msgs[-1] is not None: while msgs[-1] is not None:
msgs.append(self.irc.takeMsg()) msgs.append(self.irc.takeMsg())
@ -83,12 +82,10 @@ class SocketDriver(drivers.IrcDriver):
# (11, 'Resource temporarily unavailable') raised if connect # (11, 'Resource temporarily unavailable') raised if connect
# hasn't finished yet. # hasn't finished yet.
if e.args[0] != 11: if e.args[0] != 11:
s = 'Disconnect from %s: %s' % (self.server, e.args[1]) log.warning('Disconnect from %s: %s',self.server,e.args[1])
debug.msg(s, 'normal')
self.die() self.die()
def run(self): def run(self):
#debug.methodNamePrintf(self, 'run')
if not self.connected: if not self.connected:
time.sleep(conf.poll) # Otherwise we might spin. time.sleep(conf.poll) # Otherwise we might spin.
return return
@ -100,26 +97,22 @@ class SocketDriver(drivers.IrcDriver):
for line in lines: for line in lines:
start = time.time() start = time.time()
msg = ircmsgs.IrcMsg(line) msg = ircmsgs.IrcMsg(line)
debug.msg('Time to parse IrcMsg: %s' % (time.time()-start), log.verbose('Time to parse IrcMsg: %s', time.time()-start)
'verbose')
try: try:
self.irc.feedMsg(msg) self.irc.feedMsg(msg)
except: except:
debug.msg('Exception caught outside Irc object.', 'normal') log.exception('Uncaught exception outside Irc object:')
debug.recoverableException()
except socket.timeout: except socket.timeout:
pass pass
except socket.error, e: except socket.error, e:
# Same as with _sendIfMsgs. # Same as with _sendIfMsgs.
if e.args[0] != 11: if e.args[0] != 11:
s = 'Disconnect from %s: %s' % (self.server, e.args[1]) log.warning('Disconnect from %s: %s', self.server, e.args[1])
debug.msg(s, 'normal')
self.die() self.die()
return return
self._sendIfMsgs() self._sendIfMsgs()
def reconnect(self): def reconnect(self):
#debug.methodNamePrintf(self, 'reconnect')
self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.conn.settimeout(conf.poll*10) # Allow more time for connect. self.conn.settimeout(conf.poll*10) # Allow more time for connect.
if self.reconnectWaitsIndex < len(self.reconnectWaits)-1: if self.reconnectWaitsIndex < len(self.reconnectWaits)-1:
@ -129,21 +122,19 @@ class SocketDriver(drivers.IrcDriver):
self.conn.settimeout(conf.poll) self.conn.settimeout(conf.poll)
except socket.error, e: except socket.error, e:
if e.args[0] != 115: if e.args[0] != 115:
debug.msg('Error connecting to %s: %s' % (self.server, e)) log.warning('Error connecting to %s: %s', self.server, e)
self.die() self.die()
self.connected = True self.connected = True
self.reconnectWaitPeriodsIndex = 0 self.reconnectWaitPeriodsIndex = 0
def die(self): def die(self):
#debug.methodNamePrintf(self, 'die')
self.irc.reset() self.irc.reset()
self.conn.close() self.conn.close()
self.connected = False self.connected = False
when = time.time() + self.reconnectWaits[self.reconnectWaitsIndex] when = time.time() + self.reconnectWaits[self.reconnectWaitsIndex]
whenS = time.strftime(conf.logTimestampFormat, time.localtime(when)) whenS = time.strftime(conf.logTimestampFormat, time.localtime(when))
debug.msg('Scheduling reconnect to %s at %s' % (self.server, whenS), log.info('Scheduling reconnect to %s at %s', self.server, whenS)
'normal')
schedule.addEvent(self.reconnect, when) schedule.addEvent(self.reconnect, when)
def name(self): def name(self):

View File

@ -56,6 +56,7 @@ started = time.time()
import supybot import supybot
import log
import conf import conf
defaultNick = "%%nick%%" defaultNick = "%%nick%%"
@ -68,7 +69,6 @@ conf.commandsOnStart = "%%onStart%%"
afterConnect = "%%afterConnect%%" afterConnect = "%%afterConnect%%"
debugVariables = "%%debugVariables%%"
configVariables = "%%configVariables%%" configVariables = "%%configVariables%%"
if not isinstance(configVariables, basestring): if not isinstance(configVariables, basestring):
@ -77,17 +77,9 @@ if not isinstance(configVariables, basestring):
if not os.path.exists(conf.dataDir): if not os.path.exists(conf.dataDir):
os.mkdir(conf.dataDir) os.mkdir(conf.dataDir)
if not os.path.exists(conf.logDir):
os.mkdir(conf.logDir)
if not os.path.exists(conf.confDir): if not os.path.exists(conf.confDir):
os.mkdir(conf.confDir) os.mkdir(conf.confDir)
import debug
if not isinstance(debugVariables, basestring):
for (name, value) in debugVariables.iteritems():
setattr(debug, name, value)
def main(): def main():
import world import world
import drivers import drivers
@ -97,11 +89,10 @@ def main():
try: try:
while world.ircs: while world.ircs:
drivers.run() drivers.run()
except (SystemExit, KeyboardInterrupt):
sys.exit(0)
except: except:
try: log.exception('Exception raised out of drivers.run:')
debug.recoverableException()
except: # It must've been deadly for a reason :)
sys.exit(0)
if __name__ == '__main__': if __name__ == '__main__':
### ###

View File

@ -35,8 +35,8 @@ import fix
import time import time
import log
import conf import conf
import debug
import ircdb import ircdb
import drivers import drivers
import ircmsgs import ircmsgs
@ -51,8 +51,7 @@ class TwistedRunnerDriver(drivers.IrcDriver):
try: try:
reactor.iterate(conf.poll) reactor.iterate(conf.poll)
except: except:
debug.msg('Except caught outside reactor.', 'normal') log.exception('Uncaught exception outside reactor:')
debug.recoverableException()
class SupyIrcProtocol(LineReceiver): class SupyIrcProtocol(LineReceiver):
delimiter = '\n' delimiter = '\n'
@ -63,12 +62,11 @@ class SupyIrcProtocol(LineReceiver):
def lineReceived(self, line): def lineReceived(self, line):
start = time.time() start = time.time()
msg = ircmsgs.IrcMsg(line) msg = ircmsgs.IrcMsg(line)
debug.msg('Time to parse IrcMsg: %s' % (time.time()-start), 'verbose') log.verbose('Time to parse IrcMsg: %s', time.time()-start)
try: try:
self.factory.irc.feedMsg(msg) self.factory.irc.feedMsg(msg)
except: except:
debug.msg('Exception caught outside Irc object.', 'normal') log.exception('Uncaught exception outside Irc object:')
debug.recoverableException()
def checkIrcForMsgs(self): def checkIrcForMsgs(self):
if self.connected: if self.connected:
@ -80,7 +78,7 @@ class SupyIrcProtocol(LineReceiver):
def connectionLost(self, failure): def connectionLost(self, failure):
self.mostRecentCall.cancel() self.mostRecentCall.cancel()
self.factory.irc.reset() self.factory.irc.reset()
debug.msg(failure.getErrorMessage(), 'normal') log.warning(failure.getErrorMessage())
def connectionMade(self): def connectionMade(self):
self.factory.irc.driver = self self.factory.irc.driver = self
@ -105,14 +103,10 @@ class SupyReconnectingFactory(ReconnectingClientFactory):
class MyShell(Shell): class MyShell(Shell):
def checkUserAndPass(self, username, password): def checkUserAndPass(self, username, password):
#debug.printf(repr(username))
#debug.printf(repr(password))
try: try:
id = ircdb.users.getUserId(username) id = ircdb.users.getUserId(username)
u = ircdb.users.getUser(id) u = ircdb.users.getUser(id)
#debug.printf(u)
if u.checkPassword(password) and u.checkCapability('owner'): if u.checkPassword(password) and u.checkCapability('owner'):
#debug.printf('returning True')
return True return True
else: else:
return False return False

View File

@ -458,6 +458,9 @@ def safeEval(s, namespace={'True': True, 'False': False, 'None': None}):
raise ValueError, 'Unsafe string.' raise ValueError, 'Unsafe string.'
def exnToString(e):
"""Turns a simple exception instance into a string (better than str(e))"""
return '%s: %s' % (e.__class__.__name__, e)
class IterableMap(object): class IterableMap(object):
"""Define .iteritems() in a class and subclass this to get the other iters. """Define .iteritems() in a class and subclass this to get the other iters.

View File

@ -45,8 +45,8 @@ import types
import atexit import atexit
import threading import threading
import log
import conf import conf
import debug
startedAt = 0.0 startedAt = 0.0
@ -83,12 +83,11 @@ def upkeep(): # Function to be run on occasion to do upkeep stuff.
except IOError: # Win98 sux0rs! except IOError: # Win98 sux0rs!
pass pass
if gc.garbage: if gc.garbage:
debug.msg('Uncollectable garbage: %s' % gc.garbage, 'normal') log.warning('Uncollectable garbage: %s', gc.garbage)
if 'noflush' not in tempvars: if 'noflush' not in tempvars:
flush() flush()
debug.msg('Regexp cache size: %s' % len(sre._cache), 'verbose') log.verbose('Regexp cache size: %s', len(sre._cache))
msg = '%s upkeep ran.' % time.strftime(conf.logTimestampFormat) log.info('%s upkeep ran.', time.strftime(conf.logTimestampFormat))
debug.msg(msg, 'verbose')
return collected return collected
def makeIrcsDie(): def makeIrcsDie():

View File

@ -49,8 +49,6 @@ started = time.time()
import os.path import os.path
import unittest import unittest
import debug
import world import world
world.startedAt = started world.startedAt = started
import ircdb import ircdb
@ -134,7 +132,6 @@ class PluginTestCase(unittest.TestCase):
if self.cleanDataDir: if self.cleanDataDir:
for filename in os.listdir(conf.dataDir): for filename in os.listdir(conf.dataDir):
os.remove(os.path.join(conf.dataDir, filename)) os.remove(os.path.join(conf.dataDir, filename))
debug.reset()
ircdb.users.reload() ircdb.users.reload()
ircdb.channels.reload() ircdb.channels.reload()
if self.plugins is None: if self.plugins is None:
@ -166,7 +163,6 @@ class PluginTestCase(unittest.TestCase):
if self.myVerbose: if self.myVerbose:
print # Extra newline, so it's pretty. print # Extra newline, so it's pretty.
msg = ircmsgs.privmsg(self.irc.nick, query, prefix=self.prefix) msg = ircmsgs.privmsg(self.irc.nick, query, prefix=self.prefix)
#debug.printf(msg)
if self.myVerbose: if self.myVerbose:
print 'Feeding: %r' % msg print 'Feeding: %r' % msg
self.irc.feedMsg(msg) self.irc.feedMsg(msg)
@ -370,10 +366,14 @@ if __name__ == '__main__':
if not os.path.exists(conf.logDir): if not os.path.exists(conf.logDir):
os.mkdir(conf.logDir) os.mkdir(conf.logDir)
debug._close()
for filename in os.listdir(conf.logDir): for filename in os.listdir(conf.logDir):
os.remove(os.path.join(conf.logDir, filename)) if filename == 'plugins':
debug._open() continue
filename = os.path.join(conf.logDir, filename)
os.remove(filename)
pluginLogDir = os.path.join(conf.logDir, 'plugins')
for filename in os.listdir(pluginLogDir):
os.remove(os.path.join(pluginLogDir, filename))
parser = optparse.OptionParser(usage='Usage: %prog [options]', parser = optparse.OptionParser(usage='Usage: %prog [options]',
version='Supybot %s' % conf.version) version='Supybot %s' % conf.version)
@ -390,9 +390,6 @@ if __name__ == '__main__':
parser.add_option('-v', '--verbose', action='store_true', default=False, parser.add_option('-v', '--verbose', action='store_true', default=False,
help='Sets the verbose flag, printing extra information ' help='Sets the verbose flag, printing extra information '
'about each test that runs.') 'about each test that runs.')
parser.add_option('-s', '--stderr', action='store_true', default=False,
help='Sets debug.stderr to True, printing standard log '
'messages to stderr.')
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
if not args: if not args:
args = map(path, glob.glob(os.path.join('test', 'test_*.py'))) args = map(path, glob.glob(os.path.join('test', 'test_*.py')))
@ -414,11 +411,6 @@ if __name__ == '__main__':
else: else:
world.myVerbose = False world.myVerbose = False
if options.stderr:
debug.stderr = True
else:
debug.stderr = False
world.testing = True world.testing = True
names = [os.path.splitext(os.path.basename(name))[0] for name in args] names = [os.path.splitext(os.path.basename(name))[0] for name in args]
names.sort() names.sort()
@ -427,6 +419,5 @@ if __name__ == '__main__':
runner.run(suite) runner.run(suite)
print 'Total asserts: %s' % unittest.asserts print 'Total asserts: %s' % unittest.asserts
world.testing = False world.testing = False
debug._close()
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:

View File

@ -111,7 +111,6 @@ class MiscTestCase(ChannelPluginTestCase, PluginDocumentation):
def testTell(self): def testTell(self):
m = self.getMsg('tell foo [plugin tell]') m = self.getMsg('tell foo [plugin tell]')
#debug.printf(repr(m))
self.failUnless(m.args[0] == 'foo') self.failUnless(m.args[0] == 'foo')
self.failUnless('Misc' in m.args[1]) self.failUnless('Misc' in m.args[1])
m = self.getMsg('tell #foo [plugin tell]') m = self.getMsg('tell #foo [plugin tell]')
@ -152,6 +151,9 @@ class MiscTestCase(ChannelPluginTestCase, PluginDocumentation):
self.assertNotError('apropos f') self.assertNotError('apropos f')
self.assertError('apropos asldkfjasdlkfja') self.assertError('apropos asldkfjasdlkfja')
def testAproposDoesntReturnNonCanonicalNames(self):
self.assertNotRegexp('apropos exec', '_exec')
def testRevision(self): def testRevision(self):
self.assertNotError('revision Misc') self.assertNotError('revision Misc')
self.assertNotError('revision') self.assertNotError('revision')

View File

@ -72,10 +72,6 @@ class OwnerTestCase(PluginTestCase, PluginDocumentation):
finally: finally:
conf.allowEval = originalConfAllowEval conf.allowEval = originalConfAllowEval
def testSettrace(self):
self.assertNotError('settrace')
self.assertNotError('unsettrace')
def testIrcquote(self): def testIrcquote(self):
self.assertResponse('ircquote PRIVMSG %s :foo' % self.irc.nick, 'foo') self.assertResponse('ircquote PRIVMSG %s :foo' % self.irc.nick, 'foo')

View File

@ -38,6 +38,7 @@ class SourceforgeTest(ChannelPluginTestCase, PluginDocumentation):
def testBug(self): def testBug(self):
self.assertHelp('bug') self.assertHelp('bug')
m = self.getMsg('bugs gaim') m = self.getMsg('bugs gaim')
self.failUnless(m, 'No response from Sourceforge.')
n = re.search('#(\d+)', m.args[1]).group(1) n = re.search('#(\d+)', m.args[1]).group(1)
self.assertNotError('bug gaim %s' % n) self.assertNotError('bug gaim %s' % n)
self.assertError('bug gaim') self.assertError('bug gaim')
@ -54,6 +55,7 @@ class SourceforgeTest(ChannelPluginTestCase, PluginDocumentation):
def testRfe(self): def testRfe(self):
m = self.getMsg('rfes gaim') m = self.getMsg('rfes gaim')
self.failUnless(m, 'No response from Sourceforge.')
n = re.search('#(\d+)', m.args[1]).group(1) n = re.search('#(\d+)', m.args[1]).group(1)
self.assertNotError('rfe gaim %s' % n) self.assertNotError('rfe gaim %s' % n)
self.assertError('rfe gaim') self.assertError('rfe gaim')

View File

@ -35,7 +35,6 @@ import os
import unittest import unittest
import conf import conf
import debug
import ircdb import ircdb
import ircutils import ircutils

View File

@ -35,7 +35,6 @@ import copy
import pickle import pickle
import conf import conf
import debug
import irclib import irclib
import ircmsgs import ircmsgs
@ -81,7 +80,7 @@ class IrcMsgQueueTestCase(unittest.TestCase):
try: try:
repr(q) repr(q)
except Exception, e: except Exception, e:
self.fail('repr(q) raised an exception: %s' % debug.exnToString(e)) self.fail('repr(q) raised an exception: %s' % utils.exnToString(e))
def testEmpty(self): def testEmpty(self):
q = irclib.IrcMsgQueue() q = irclib.IrcMsgQueue()

View File

@ -33,7 +33,6 @@ from test import *
import time import time
import debug
import schedule import schedule
class TestSchedule(unittest.TestCase): class TestSchedule(unittest.TestCase):