How to not python ever


SUBMITTED BY: Guest

DATE: Nov. 11, 2013, 12:53 p.m.

FORMAT: Python

SIZE: 6.4 kB

HITS: 978

  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 Karma:
  24. """
  25. For all things internet points
  26. """
  27. def __init__(self):
  28. self.users = {} #A dictionary. Nickname and status (Really we just want to see if it has an r for registered)
  29. self.userKarma = {} #A dictionary, nickname and points. Will have to cross-check with users to see if people are registered
  30. def registered(self, target):
  31. user = self.users.get(target)
  32. if user == None:
  33. return -1 #Does not exist
  34. print(" DOES NOT EXIST " )
  35. elif user.find('r')!=-1:
  36. return 1 #Registered
  37. print(" REGISTERED " )
  38. else:
  39. return 0 #Not registered or other
  40. print(" NOT REGISTERED " )
  41. def points(self, target, amt=None):
  42. if(self.registered(target)!=1):
  43. return -1
  44. if(self.userKarma.get(target) == None): #user did not exist in the points database
  45. self.userKarma[target] = 5
  46. if(amt == None):
  47. return self.userKarma.get(target)
  48. else:
  49. self.userKarma[target] = amt
  50. if self.userKarma.get(target) < 0:
  51. self.userKarma[target] = 0
  52. return -2
  53. class Bot(irc.IRCClient):
  54. """A logging IRC bot."""
  55. nickname = "karma"
  56. def connectionMade(self):
  57. irc.IRCClient.connectionMade(self)
  58. self.logger = MessageLogger(open(self.factory.filename, "a"))
  59. self.logger.log("[connected at %s]" %
  60. time.asctime(time.localtime(time.time())))
  61. self.karma = Karma()
  62. def connectionLost(self, reason):
  63. irc.IRCClient.connectionLost(self, reason)
  64. self.logger.log("[disconnected at %s]" %
  65. time.asctime(time.localtime(time.time())))
  66. self.logger.close()
  67. # callbacks for events
  68. def signedOn(self):
  69. """Called when bot has succesfully signed on to server."""
  70. self.join(self.factory.channel)
  71. def joined(self, channel):
  72. """This will get called when the bot joins the channel."""
  73. self.logger.log("[I have joined %s]" % channel)
  74. self.sendLine("WHO %s" % channel)
  75. def privmsg(self, user, channel, msg):
  76. """This will get called when the bot receives a message."""
  77. user = user.split('!', 1)[0]
  78. self.logger.log("<%s> %s" % (user, msg))
  79. args = msg.split( )
  80. if args[0] == "!give" and len(args) >= 2:
  81. self.sendLine("WHO %s" % channel)
  82. if self.karma.registered(args[1]) and self.karma.registered(user) and self.karma.points(user) > 0:
  83. self.karma.points(args[1], self.karma.points(args[1])+1)
  84. self.karma.points(user, self.karma.points(user)-1)
  85. self.msg( channel, "+1 TO %s FROM %s" % (args[1], user) )
  86. if args[0] == "!karma":
  87. if len(args) >= 2:
  88. if self.karma.registered(args[1]):
  89. self.msg( channel, "%s: %s's karma: %d" % (user, args[1], self.karma.points(args[1]) ) )
  90. else:
  91. if self.karma.registered(user):
  92. self.msg( channel, "%s: Your karma: %d" % (user, self.karma.points(user)) )
  93. # Check to see if they're sending me a private message
  94. if channel == self.nickname:
  95. msg = "It isn't nice to whisper! Play nice with the group."
  96. self.msg(user, msg)
  97. return
  98. # Otherwise check to see if it is a message directed at me
  99. if msg.startswith(self.nickname + ":"):
  100. msg = "%s: !give <name> to give karma. !karma [name] to see someone's karma." % user
  101. self.msg(channel, msg)
  102. self.logger.log("<%s> %s" % (self.nickname, msg))
  103. def action(self, user, channel, msg):
  104. """This will get called when the bot sees someone do an action."""
  105. user = user.split('!', 1)[0]
  106. self.logger.log("* %s %s" % (user, msg))
  107. # irc callbacks
  108. def irc_RPL_WHOREPLY(self, prefix, params):
  109. #print(prefix)
  110. self.karma.users[params[-3]] = params[-2] #2nd last is registered param, 3rd last is nickname
  111. def irc_RPL_ENDOFWHO(self, prefix, params):
  112. for keys,values in self.karma.users.iteritems():
  113. print(keys)
  114. print(values)
  115. def irc_NICK(self, prefix, params):
  116. """Called when an IRC user changes their nickname."""
  117. old_nick = prefix.split('!')[0]
  118. new_nick = params[0]
  119. self.logger.log("%s is now known as %s" % (old_nick, new_nick))
  120. # For fun, override the method that determines how a nickname is changed on
  121. # collisions. The default method appends an underscore.
  122. def alterCollidedNick(self, nickname):
  123. """
  124. Generate an altered version of a nickname that caused a collision in an
  125. effort to create an unused related name for subsequent registration.
  126. """
  127. return nickname + '^'
  128. class BotFactory(protocol.ClientFactory):
  129. """A factory for Bots.
  130. A new protocol instance will be created each time we connect to the server.
  131. """
  132. def __init__(self):
  133. self.channel = "#jacoders"
  134. self.filename = "session.txt"
  135. def buildProtocol(self, addr):
  136. p = Bot()
  137. p.factory = self
  138. return p
  139. def clientConnectionLost(self, connector, reason):
  140. """If we get disconnected, reconnect to server."""
  141. connector.connect()
  142. def clientConnectionFailed(self, connector, reason):
  143. print "connection failed:", reason
  144. reactor.stop()
  145. if __name__ == '__main__':
  146. # initialize logging
  147. log.startLogging(sys.stdout)
  148. # create factory protocol and application
  149. f = BotFactory()
  150. # connect factory to this host and port
  151. reactor.connectTCP("irc.arloria.net", 6667, f)
  152. # run bot
  153. reactor.run()

comments powered by Disqus