Python / Twisted IRC bot日志记录问题

Python/Twisted IRC bot logging problem

嘿。我最近才开始使用python,我的朋友建议使用twisted作为创建这个IRC bot的方法,因为它会更简单。这是我迄今为止拥有的代码(它主要基于logbot.py haha)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from twisted.internet import reactor, protocol
from twisted.words.protocols import irc
from twisted.python import log
import sys, time

class 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
'
% (timestamp, message))
        self.file.flush()

    def close(self):
        self.file.close()

class IRCProtocol(irc.IRCClient):
    nickname ="3n7rar3"
    def connectionMade(self):
        irc.IRCClient.connectionMade(self)
        self.logger = MessageLogger(open(self.factory.filename,"a"))

    def signedOn(self):
        print 'Success! Connection established.'
        self.join(self.factory.channels)
        print 'Joined channel', self.factory.channels

    def privmsg(self, user, channel, msg):
        user = user.split('!', 1)[0]
        self.logger.log("<%s> %s" % (user, msg))

class IRCFactory(protocol.ClientFactory):
    protocol = IRCProtocol
    channels ="#testing"

    def __init__(self, channel, filename):
        self.channel = channel
        self.filename = filename

    def clientConnectionFailed(self, connector, reason):
        print"Connection failed because of %s" % reason
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print"Connection lost: %s" % reason
        connector.connect()

if __name__ =="__main__":
    log.startLogging(sys.stdout)
    host, port ="irc.freenode.net", 6667
    fact = IRCFactory(sys.argv[1],sys.argv[2])
    reactor.connectTCP(host, port, fact)
    reactor.run()

问题是bot只记录通道消息,但我也希望它记录通道连接和部分。最简单的方法是什么?谢谢。


定义联接和部件的方法,并在其中记录:

1
2
3
4
5
6
7
8
def userJoined(self, user, channel):
    log.msg('%s has joined %s' % (user, channel))

def userLeft(self, user, channel):
    log.msg('%s has left %s' % (user, channel))

def userQuit(self, user, quitMessage):
    log.msg('%s has quit. Reason: %s' % (user, quitMessage))

API文档和源代码在将来可能对您有用。


文件对我来说似乎很清楚。重写userJoineduserLeft方法,就像对privmsg所做的那样。