How to note code anything, ever


SUBMITTED BY: Guest

DATE: Nov. 19, 2013, 3:59 p.m.

FORMAT: Python

SIZE: 4.8 kB

HITS: 903

  1. # twisted imports
  2. from twisted.words.protocols import irc
  3. from twisted.internet import reactor, protocol
  4. from twisted.python import log
  5. # system imports
  6. import time, sys
  7. #other
  8. import json
  9. class MessageLogger:
  10. """
  11. An independent logger class (because separation of application
  12. and protocol logic is a good thing).
  13. """
  14. def __init__(self, file):
  15. self.file = file
  16. def log(self, message):
  17. """Write a message to the file."""
  18. timestamp = time.strftime("[%H:%M:%S]", time.localtime(time.time()))
  19. self.file.write('%s %s\n' % (timestamp, message))
  20. self.file.flush()
  21. def close(self):
  22. self.file.close()
  23. class Bot(irc.IRCClient):
  24. """A logging IRC bot."""
  25. nickname = "virus"
  26. infectedChannels = list()
  27. chanInfo = dict()
  28. def connectionMade(self):
  29. irc.IRCClient.connectionMade(self)
  30. self.logger = MessageLogger(open(self.factory.filename, "a"))
  31. self.logger.log("[connected at %s]" %
  32. time.asctime(time.localtime(time.time())))
  33. def connectionLost(self, reason):
  34. irc.IRCClient.connectionLost(self, reason)
  35. self.logger.log("[disconnected at %s]" %
  36. time.asctime(time.localtime(time.time())))
  37. self.logger.close()
  38. # callbacks for events
  39. def signedOn(self):
  40. """Called when bot has succesfully signed on to server."""
  41. self.join(self.factory.rootChannel)
  42. def joined(self, channel):
  43. """This will get called when the bot joins the channel."""
  44. self.logger.log("[I have joined %s]" % channel)
  45. print("joined %s" % channel)
  46. def privmsg(self, user, channel, msg):
  47. """This will get called when the bot receives a message."""
  48. user = user.split('!', 1)[0]
  49. self.logger.log("<%s> %s" % (user, msg))
  50. args = msg.split( )
  51. for substring in args:
  52. if substring.startswith('#') and substring.find(',') == -1:
  53. print("Hitting WHO send")
  54. self.sendLine("WHO %s" % substring)
  55. # Check to see if they're sending me a private message
  56. if channel == self.nickname:
  57. msg = "It isn't nice to whisper! Play nice with the group."
  58. self.msg(user, msg)
  59. return
  60. # Otherwise check to see if it is a message directed at me
  61. if msg.startswith(self.nickname + ":"):
  62. msg = "%s: Infected channels; %s" % (user, '\n'.join(self.infectedChannels))
  63. self.msg(channel, msg)
  64. self.logger.log("<%s> %s" % (self.nickname, msg))
  65. def action(self, user, channel, msg):
  66. """This will get called when the bot sees someone do an action."""
  67. user = user.split('!', 1)[0]
  68. self.logger.log("* %s %s" % (user, msg))
  69. # irc callbacks
  70. def irc_RPL_WHOREPLY(self, prefix, params):
  71. print("Got who reply: %s" % ', '.join(params))
  72. if params[0].lower() not in self.infectedChannels:
  73. self.join(params[0])
  74. self.infectedChannels.append(params[0].lower())
  75. print("Added %s to infected" % params[0].lower())
  76. def irc_NICK(self, prefix, params):
  77. """Called when an IRC user changes their nickname."""
  78. old_nick = prefix.split('!')[0]
  79. new_nick = params[0]
  80. self.logger.log("%s is now known as %s" % (old_nick, new_nick))
  81. # For fun, override the method that determines how a nickname is changed on
  82. # collisions. The default method appends an underscore.
  83. def alterCollidedNick(self, nickname):
  84. """
  85. Generate an altered version of a nickname that caused a collision in an
  86. effort to create an unused related name for subsequent registration.
  87. """
  88. return nickname + '^'
  89. class BotFactory(protocol.ClientFactory):
  90. """A factory for Bots.
  91. A new protocol instance will be created each time we connect to the server.
  92. """
  93. def __init__(self):
  94. self.rootChannel = "#jacoders" #The channel to always join.
  95. self.filename = "session.txt"
  96. def buildProtocol(self, addr):
  97. p = Bot()
  98. p.factory = self
  99. return p
  100. def clientConnectionLost(self, connector, reason):
  101. """If we get disconnected, reconnect to server."""
  102. connector.connect()
  103. def clientConnectionFailed(self, connector, reason):
  104. print "connection failed:", reason
  105. reactor.stop()
  106. if __name__ == '__main__':
  107. # initialize logging
  108. log.startLogging(sys.stdout)
  109. # create factory protocol and application
  110. f = BotFactory()
  111. # connect factory to this host and port
  112. reactor.connectTCP("irc.arloria.net", 6667, f)
  113. # run bot
  114. reactor.run()

comments powered by Disqus