Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- # Copyright (c) 2001-2004 Twisted Matrix Laboratories.
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- """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 ':',
- e.g.
- <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 ircLogBot.py test *.log
- will send newest *.log into channel #test.
- """
- # twisted imports
- from twisted.words.protocols import irc
- from twisted.internet import reactor, protocol
- from twisted.python import log
- # system imports
- import os, glob, time, sys, threading
- 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))
- self.file.flush()
- def close(self):
- self.file.close()
- class LogBot(irc.IRCClient):
- """A logging IRC bot."""
- nickname = "horaguchi_bot"
- channel_now = ""
- 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()
- self.channel_now = ""
- # callbacks for events
- def signedOn(self):
- """Called when bot has succesfully signed on to server."""
- self.join(self.factory.channel)
- def joined(self, channel):
- """This will get called when the bot joins the channel."""
- #self.logger.log("[I have joined %s]" % channel)
- self.channel_now = channel
- t = threading.Thread(target = self.read_localfile)
- t.start()
- def left(self, channel):
- """This will get called when the bot joins the channel."""
- #self.logger.log("[I have left %s]" % channel)
- self.channel_now = ""
- 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)
- return
- # 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))
- # user functions
- def read_localfile(self):
- before_read = ''
- while self.channel_now != '':
- newest_file = ''
- newest_time = 0
- last_read = ''
- for file in glob.glob(self.factory.globname):
- modified = os.stat(file).st_mtime
- if modified > newest_time:
- newest_file = file
- newest_time = modified
- flag_out = False
- for line in open(newest_file, 'r'):
- #line = unicode(line.rstrip()).encode(utf-8)
- line = line.rstrip()
- if flag_out:
- self.msg(self.channel_now, line)
- last_read = line
- if before_read != '':
- if before_read == line:
- flag_out = True
- before_read = last_read
- time.sleep(1)
- 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, globname):
- self.channel = channel
- self.globname = globname
- def clientConnectionLost(self, connector, reason):
- """If we get disconnected, reconnect to server."""
- connector.connect()
- def clientConnectionFailed(self, connector, reason):
- print "connection failed:", reason
- reactor.stop()
- if __name__ == '__main__':
- # initialize logging
- log.startLogging(sys.stdout)
- # create factory protocol and application
- f = LogBotFactory(sys.argv[1], sys.argv[2])
- # connect factory to this host and port
- #reactor.connectTCP("irc.freenode.net", 6667, f)
- #reactor.connectTCP("chat1.ustream.tv", 6667, f)
- reactor.connectTCP("localhost", 6667, f)
- # run bot
- reactor.run()
Add Comment
Please, Sign In to add comment