Find file
Fetching contributors…
Cannot retrieve contributors at this time
165 lines (118 sloc) 4.9 KB
# Copyright (c) 2001-2009 Twisted Matrix Laboratories.
# See LICENSE for details.
An example IRC log bot - logs a channel's events to a file.
If someone says the bot's name in the channel followed by a ':',
<foo> logbot: hello!
the bot will reply:
<logbot> foo: I am a log bot
Run this script with two arguments, the channel name the bot should
connect to, and file to log to, e.g.:
$ python test test.log
will log channel #test to the file 'test.log'.
# twisted imports
from twisted.words.protocols import irc
from twisted.internet import reactor, protocol
from twisted.python import log
# system imports
import time, sys
class MessageLogger:
An independent logger class (because separation of application
and protocol logic is a good thing).
def __init__(self, file):
self.file = file
def log(self, message):
"""Write a message to the file."""
timestamp = time.strftime("[%H:%M:%S]", time.localtime(time.time()))
self.file.write('%s %s\n' % (timestamp, message))
def close(self):
class LogBot(irc.IRCClient):
"""A logging IRC bot."""
nickname = "colorbot"
def connectionMade(self):
self.logger = MessageLogger(open(self.factory.filename, "a"))
self.logger.log("[connected at %s]" %
def connectionLost(self, reason):
irc.IRCClient.connectionLost(self, reason)
self.logger.log("[disconnected at %s]" %
# callbacks for events
def signedOn(self):
"""Called when bot has succesfully signed on to server."""
def joined(self, channel):
"""This will get called when the bot joins the channel."""
self.logger.log("[I have joined %s]" % channel)
self.msg(channel, "\x0304red friend =)\x03")
"""self.msg(channel, "\x0303green friend =)\x03")
self.msg(channel, "\x0302blue friend =)\x03")
self.msg(channel, "\x0314grey friend =)\x03")
self.msg(channel, "\x0300,01 black friend =)\x03")"""
self.msg(channel, "\x0314[ \x03\x0304Ah\x03\x0314 ] [ \x03\x0303Jc\x03\x0314 ] [ \x03\x03027d\x03\x0314 ] [ \x03\x028s\x0314 ]\x03")
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 = "It isn't nice to whisper! Play nice with the group."
self.msg(user, msg)
# Otherwise check to see if it is a message directed at me
if msg.startswith(self.nickname + ":"):
msg = "%s: I am a log bot" % user
self.msg(channel, msg)
self.logger.log("<%s> %s" % (self.nickname, msg))
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))
# For fun, override the method that determines how a nickname is changed on
# collisions. The default method appends an underscore.
def alterCollidedNick(self, nickname):
Generate an altered version of a nickname that caused a collision in an
effort to create an unused related name for subsequent registration.
return nickname + '^'
class LogBotFactory(protocol.ClientFactory):
"""A factory for LogBots.
A new protocol instance will be created each time we connect to the server.
# the class of the protocol to build when new connection is made
protocol = LogBot
def __init__(self, channel, filename): = channel
self.filename = filename
def clientConnectionLost(self, connector, reason):
"""If we get disconnected, reconnect to server."""
def clientConnectionFailed(self, connector, reason):
print "connection failed:", reason
if __name__ == '__main__':
# initialize logging
# create factory protocol and application
f = LogBotFactory('#pangaea', 'fooo')
# connect factory to this host and port
reactor.connectTCP("", 6667, f)
# run bot