2011-02-01 135 views
0

嘿。我最近纔開始使用Python,而我的朋友建議使用Twisted作爲創建此IRC bot的手段,因爲它會簡單得多。這裏是我到目前爲止(這在很大程度上基於關閉logbot.py哈哈)代碼Python/Twisted IRC bot日誌記錄問題

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\n' % (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() 

這樣做的問題是,機器人只記錄頻道的消息,但我也想它登錄通道連接和部分。什麼是最簡單的方法來完成這一點?謝謝。

回答

2

定義和連接部分的方法和日誌裏面他們太多:

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 documentationsource code是你將來可能有用。

1

documentation對我來說似乎很清楚。覆蓋userJoineduserLeft方法,就像您爲privmsg所做的那樣。

+0

我在看錯文檔哈哈。謝謝,感謝。 – Felix 2011-02-01 15:56:53