daily pastebin goal
92%
SHARE
TWEET

Untitled

a guest Dec 5th, 2017 94 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from __future__ import print_function
  2.  
  3. # twisted imports
  4. from twisted.words.protocols import irc
  5. from twisted.internet import reactor, protocol
  6. from twisted.python import log
  7.  
  8. # system imports
  9. import time, sys
  10.  
  11.  
  12. class MessageLogger:
  13.     """
  14.     An independent logger class (because separation of application
  15.     and protocol logic is a good thing).
  16.     """
  17.     def __init__(self, file):
  18.         self.file = file
  19.  
  20.     def log(self, message):
  21.         """Write a message to the file."""
  22.         timestamp = time.strftime("[%H:%M:%S]", time.localtime(time.time()))
  23.         self.file.write('%s %s\n' % (timestamp, message))
  24.         self.file.flush()
  25.  
  26.     def close(self):
  27.         self.file.close()
  28.  
  29.  
  30. class LogBot(irc.IRCClient):
  31.     """A logging IRC bot."""
  32.    
  33.     nickname = "twistedbot"
  34.    
  35.     def connectionMade(self):
  36.         irc.IRCClient.connectionMade(self)
  37.         self.logger = MessageLogger(open(self.factory.filename, "a"))
  38.         self.logger.log("[connected at %s]" %
  39.                         time.asctime(time.localtime(time.time())))
  40.  
  41.     def connectionLost(self, reason):
  42.         irc.IRCClient.connectionLost(self, reason)
  43.         self.logger.log("[disconnected at %s]" %
  44.                         time.asctime(time.localtime(time.time())))
  45.         self.logger.close()
  46.  
  47.  
  48.     # callbacks for events
  49.  
  50.     def signedOn(self):
  51.         """Called when bot has successfully signed on to server."""
  52.         self.join(self.factory.channel)
  53.  
  54.     def joined(self, channel):
  55.         """This will get called when the bot joins the channel."""
  56.         self.logger.log("[I have joined %s]" % channel)
  57.  
  58.     def privmsg(self, user, channel, msg):
  59.         """This will get called when the bot receives a message."""
  60.         user = user.split('!', 1)[0]
  61.         self.logger.log("<%s> %s" % (user, msg))
  62.        
  63.         # Check to see if they're sending me a private message
  64.         if channel == self.nickname:
  65.             msg = "It isn't nice to whisper!  Play nice with the group."
  66.             #run function
  67.             runfunction(self)
  68.             self.msg(user, msg)
  69.             return
  70.         # Otherwise check to see if it is a message directed at me
  71.         if msg.startswith(self.nickname + ":"):
  72.             msg = "%s: I am a log bot" % user
  73.             self.msg(channel, msg)
  74.             self.logger.log("<%s> %s" % (self.nickname, msg))
  75.            
  76.     def runfuntion(self):
  77.         print("-----Ran function")
  78.  
  79.     def action(self, user, channel, msg):
  80.         """This will get called when the bot sees someone do an action."""
  81.         user = user.split('!', 1)[0]
  82.         self.logger.log("* %s %s" % (user, msg))
  83.  
  84.     # irc callbacks
  85.  
  86.     def irc_NICK(self, prefix, params):
  87.         """Called when an IRC user changes their nickname."""
  88.         old_nick = prefix.split('!')[0]
  89.         new_nick = params[0]
  90.         self.logger.log("%s is now known as %s" % (old_nick, new_nick))
  91.  
  92.  
  93.     # For fun, override the method that determines how a nickname is changed on
  94.     # collisions. The default method appends an underscore.
  95.     def alterCollidedNick(self, nickname):
  96.         """
  97.         Generate an altered version of a nickname that caused a collision in an
  98.         effort to create an unused related name for subsequent registration.
  99.         """
  100.         return nickname + '^'
  101.  
  102.  
  103.  
  104. class LogBotFactory(protocol.ClientFactory):
  105.     """A factory for LogBots.
  106.  
  107.     A new protocol instance will be created each time we connect to the server.
  108.     """
  109.  
  110.     def __init__(self, channel, filename):
  111.         self.channel = channel
  112.         self.filename = filename
  113.  
  114.     def buildProtocol(self, addr):
  115.         p = LogBot()
  116.         p.factory = self
  117.         return p
  118.  
  119.     def clientConnectionLost(self, connector, reason):
  120.         """If we get disconnected, reconnect to server."""
  121.         connector.connect()
  122.  
  123.     def clientConnectionFailed(self, connector, reason):
  124.         print("connection failed:", reason)
  125.         reactor.stop()
  126.  
  127.  
  128. if __name__ == '__main__':
  129.     # initialize logging
  130.     log.startLogging(sys.stdout)
  131.  
  132.     # create factory protocol and application
  133.     f = LogBotFactory(sys.argv[1], sys.argv[2])
  134.  
  135.     # connect factory to this host and port
  136.     reactor.connectTCP("irc.freenode.net", 6667, f)
  137.  
  138.     # run bot
  139.     reactor.run()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top