All pastes #344502 Raw Edit

Unnamed

public python v1 · immutable
·published 2007-02-07 20:12 UTC
rendered paste body
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.# See LICENSE for details.# twisted importsfrom twisted.words.protocols import ircfrom twisted.internet import reactor, protocol, task, utils, deferfrom twisted.python import logfrom twisted.web import client# system importsimport time, sysfrom xml.dom.minidom import parseStringclass MessageLogger:    def __init__(self, file):        self.file = file    def log(self, message):        timestamp = time.strftime("[%H:%M:%S]", time.localtime(time.time()))        self.file.write('%s %s\n' % (timestamp, message))        self.file.flush()    def close(self):        self.file.close()class MuninPlugin(object):    def setup(self, irc, channel, server, plugin, metric,            announce_msg, fixed_msg):        self.irc = irc        self.channel = channel        self.server = server        self.plugin = plugin        self.metric = metric        self.announce_msg = announce_msg        self.fixed_msg = fixed_msg        self.loop = task.LoopingCall(self.poll)        self.loop.start(30*60)        self.lastLag = None    def poll(self):        d = utils.getProcessOutput('/usr/bin/ssh',            [self.server, '/etc/munin/plugins/%s' % self.plugin])        def _foo(result):            result = result.split('\n')            for line in result:                if line.startswith('%s.value' % self.metric):                    lag = int(line.split()[1])            msg = '%s: %s' % (self.announce_msg, lag)            if self.lastLag != None:                delta = lag - self.lastLag                msg = '%s (%+d)' % (msg, delta)            self.lastLag = lag            msg = '%s ... ook' % msg            self.irc.msg(self.channel, msg)            if lag < 10 :                self.irc.msg(self.channel, '%s, eek eek ook!' % self.fixed_msg)                self.loop.stop()        d.addCallback(_foo)        return d        class LogBot(irc.IRCClient):        lastCallout = None        def connectionMade(self):        irc.IRCClient.connectionMade(self)        self.logger = MessageLogger(open(self.factory.filename, "a"))        self.logger.log("[connected at %s]" %                         time.asctime(time.localtime(time.time())))    def connectionLost(self, reason):        irc.IRCClient.connectionLost(self, reason)        self.logger.log("[disconnected at %s]" %                         time.asctime(time.localtime(time.time())))        self.logger.close()    def signedOn(self):        """Called when bot has succesfully signed on to server."""        self.join(self.factory.channel)    def _monitorDigg(self):        d = client.getPage('http://services.digg.com/stories/1298237')        def _foo(result):            dom = parseString(result)            story = dom.getElementsByTagName('story')[0]            digs = int(story.getAttribute('digs'))            print 'last callout: %-6s this poll: %-6s' % (                self.lastCallout, digs)            if self.lastCallout == None or digs - self.lastCallout > 50:                self.msg('#%s' % self.factory.channel.split()[0], '%s digs!' % digs)                self.lastCallout = digs            return result        d.addCallback(_foo)        return d    def joined(self, channel):        self.logger.log("[I have joined %s]" % channel)        # self.loop = task.LoopingCall(self._monitorDigg)        # self.loop.start(60.0)        # self.loop = task.LoopingCall(self._monitorMunin)        # self.loop.start(60*10)        # self.loop.start(5)    def privmsg(self, user, channel, msg):        """This will get called when the bot receives a message."""        user = user.split('!', 1)[0]        self.logger.log("<%s> %s" % (user, msg))                # Check to see if they're sending me a private message        if channel == self.nickname:            msg = 'ook'            self.msg(user, msg)            return        # Otherwise check to see if it is a message directed at me        if msg.startswith(self.nickname + ":"):            self.logger.log("<%s> %s" % (self.nickname, msg))            print msg.split(None, 1)            nick, msg = msg.split(None, 1)            msg = ''.join([c for c in msg if c not in [',', '.']])            def _match(msg, phrases):                print msg                for phrase in phrases:                    if msg.startswith(phrase):                        return msg[len(phrase):].strip(), True                return msg.strip(), False            msg, matched = _match(msg, ['yo', 'heya', 'hey', 'hi'])            msg, matched = _match(msg, ['can you', 'could you'])            msg, matched = _match(msg, ['check out', 'watch', 'keep an eye on'])            if matched:                msg, matched = _match(msg, ['events'])                if matched:                    plugin = MuninPlugin()                    plugin.setup(self, channel, 'jb01x', 'events_sqlite', 'new_events',                        'current qt event flush lag', 'qt events caught up')                    return            self.msg(channel, '%s: ook ook' % user)    def action(self, user, channel, msg):        """This will get called when the bot sees someone do an action."""        user = user.split('!', 1)[0]        self.logger.log("* %s %s" % (user, msg))    # irc callbacks    def irc_NICK(self, prefix, params):        """Called when an IRC user changes their nickname."""        old_nick = prefix.split('!')[0]        new_nick = params[0]        self.logger.log("%s is now known as %s" % (old_nick, new_nick))class LogBotFactory(protocol.ClientFactory):    protocol = LogBot    def __init__(self, nickname, channel, filename):        self.nickname = nickname        self.channel = channel        self.filename = filename    def buildProtocol(self, addr):        p = protocol.ClientFactory.buildProtocol(self, addr)        p.nickname = self.nickname        return p    def clientConnectionLost(self, connector, reason):        connector.connect()    def clientConnectionFailed(self, connector, reason):        reactor.stop()# args: nickname room log_fileif __name__ == '__main__':    log.startLogging(sys.stdout)    f = LogBotFactory(sys.argv[1], sys.argv[2], sys.argv[3])    reactor.connectTCP("irc.revver.com", 6667, f)    reactor.run()