Guest User

Untitled

a guest
Feb 19th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.06 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2001-2004 Twisted Matrix Laboratories.
  3.  
  4. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  5. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  7. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  8. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  9. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  10. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  11.  
  12. """An example IRC log bot - logs a channel's events to a file.
  13.  
  14. If someone says the bot's name in the channel followed by a ':',
  15. e.g.
  16.  
  17. <foo> logbot: hello!
  18.  
  19. the bot will reply:
  20.  
  21. <logbot> foo: I am a log bot
  22.  
  23. Run this script with two arguments, the channel name the bot should
  24. connect to, and file to log to, e.g.:
  25.  
  26. $ python ircLogBot.py test *.log
  27.  
  28. will send newest *.log into channel #test.
  29. """
  30.  
  31.  
  32. # twisted imports
  33. from twisted.words.protocols import irc
  34. from twisted.internet import reactor, protocol
  35. from twisted.python import log
  36.  
  37. # system imports
  38. import os, glob, time, sys, threading
  39.  
  40. class MessageLogger:
  41. """
  42. An independent logger class (because separation of application
  43. and protocol logic is a good thing).
  44. """
  45. def __init__(self, file):
  46. self.file = file
  47.  
  48. def log(self, message):
  49. """Write a message to the file."""
  50. timestamp = time.strftime("[%H:%M:%S]", time.localtime(time.time()))
  51. self.file.write('%s %s\n' % (timestamp, message))
  52. self.file.flush()
  53.  
  54. def close(self):
  55. self.file.close()
  56.  
  57.  
  58. class LogBot(irc.IRCClient):
  59. """A logging IRC bot."""
  60.  
  61. nickname = "horaguchi_bot"
  62. channel_now = ""
  63.  
  64. def connectionMade(self):
  65. irc.IRCClient.connectionMade(self)
  66. #self.logger = MessageLogger(open(self.factory.filename, "a"))
  67. #self.logger.log("[connected at %s]" %
  68. # time.asctime(time.localtime(time.time())))
  69.  
  70. def connectionLost(self, reason):
  71. irc.IRCClient.connectionLost(self, reason)
  72. #self.logger.log("[disconnected at %s]" %
  73. # time.asctime(time.localtime(time.time())))
  74. #self.logger.close()
  75. self.channel_now = ""
  76.  
  77. # callbacks for events
  78.  
  79. def signedOn(self):
  80. """Called when bot has succesfully signed on to server."""
  81. self.join(self.factory.channel)
  82.  
  83. def joined(self, channel):
  84. """This will get called when the bot joins the channel."""
  85. #self.logger.log("[I have joined %s]" % channel)
  86. self.channel_now = channel
  87. t = threading.Thread(target = self.read_localfile)
  88. t.start()
  89.  
  90. def left(self, channel):
  91. """This will get called when the bot joins the channel."""
  92. #self.logger.log("[I have left %s]" % channel)
  93. self.channel_now = ""
  94.  
  95. def privmsg(self, user, channel, msg):
  96. """This will get called when the bot receives a message."""
  97. user = user.split('!', 1)[0]
  98. #self.logger.log("<%s> %s" % (user, msg))
  99.  
  100. # Check to see if they're sending me a private message
  101. if channel == self.nickname:
  102. msg = "It isn't nice to whisper! Play nice with the group."
  103. self.msg(user, msg)
  104. return
  105.  
  106. # Otherwise check to see if it is a message directed at me
  107. if msg.startswith(self.nickname + ":"):
  108. msg = "%s: I am a log bot" % user
  109. self.msg(channel, msg)
  110. #self.logger.log("<%s> %s" % (self.nickname, msg))
  111.  
  112. def action(self, user, channel, msg):
  113. """This will get called when the bot sees someone do an action."""
  114. user = user.split('!', 1)[0]
  115. #self.logger.log("* %s %s" % (user, msg))
  116.  
  117. # irc callbacks
  118.  
  119. def irc_NICK(self, prefix, params):
  120. """Called when an IRC user changes their nickname."""
  121. old_nick = prefix.split('!')[0]
  122. new_nick = params[0]
  123. #self.logger.log("%s is now known as %s" % (old_nick, new_nick))
  124.  
  125. # user functions
  126. def read_localfile(self):
  127. before_read = ''
  128. while self.channel_now != '':
  129. newest_file = ''
  130. newest_time = 0
  131. last_read = ''
  132. for file in glob.glob(self.factory.globname):
  133. modified = os.stat(file).st_mtime
  134. if modified > newest_time:
  135. newest_file = file
  136. newest_time = modified
  137.  
  138. flag_out = False
  139. for line in open(newest_file, 'r'):
  140. #line = unicode(line.rstrip()).encode(utf-8)
  141. line = line.rstrip()
  142. if flag_out:
  143. self.msg(self.channel_now, line)
  144.  
  145. last_read = line
  146.  
  147. if before_read != '':
  148. if before_read == line:
  149. flag_out = True
  150.  
  151. before_read = last_read
  152.  
  153. time.sleep(1)
  154.  
  155. class LogBotFactory(protocol.ClientFactory):
  156. """A factory for LogBots.
  157.  
  158. A new protocol instance will be created each time we connect to the server.
  159. """
  160.  
  161. # the class of the protocol to build when new connection is made
  162. protocol = LogBot
  163.  
  164. def __init__(self, channel, globname):
  165. self.channel = channel
  166. self.globname = globname
  167.  
  168. def clientConnectionLost(self, connector, reason):
  169. """If we get disconnected, reconnect to server."""
  170. connector.connect()
  171.  
  172. def clientConnectionFailed(self, connector, reason):
  173. print "connection failed:", reason
  174. reactor.stop()
  175.  
  176.  
  177.  
  178. if __name__ == '__main__':
  179. # initialize logging
  180. log.startLogging(sys.stdout)
  181.  
  182. # create factory protocol and application
  183. f = LogBotFactory(sys.argv[1], sys.argv[2])
  184.  
  185. # connect factory to this host and port
  186. #reactor.connectTCP("irc.freenode.net", 6667, f)
  187. #reactor.connectTCP("chat1.ustream.tv", 6667, f)
  188. reactor.connectTCP("localhost", 6667, f)
  189.  
  190. # run bot
  191. reactor.run()
Add Comment
Please, Sign In to add comment