Hey. I only recently started using Python, and my friend suggested using Twisted as a means to create this IRC bot, as it will be a lot simpler. Here is the code I have so far (which is heavily based off logbot.py haha)
from twisted.internet import reactor, protocol
from twisted.words.protocols import irc
from twisted.python import log
import sys, time
class M开发者_JS百科essageLogger:
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()
The problem with this is that the bot only logs channel messages, but I would also like it to log channel joins and parts. What is the easiest way to accomplish this? Thanks.
Define methods for joins and parts and log inside them too:
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))
The api documentation and source code are probably useful for you in the future.
The documentation seems pretty clear to me. Override the userJoined
and userLeft
methods like you did for privmsg
.
精彩评论