Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.12 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. """
  5. SleekXMPP: The Sleek XMPP Library
  6. Copyright (C) 2010 Nathanael C. Fritz
  7. This file is part of SleekXMPP.
  8.  
  9. See the file LICENSE for copying permission.
  10. """
  11.  
  12. import sys
  13. import logging
  14. import getpass
  15. from optparse import OptionParser
  16. import datetime
  17. import xml
  18.  
  19. import sleekxmpp
  20.  
  21. # Python versions before 3.0 do not use UTF-8 encoding
  22. # by default. To ensure that Unicode is handled properly
  23. # throughout SleekXMPP, we will set the default encoding
  24. # ourselves to UTF-8.
  25. if sys.version_info < (3, 0):
  26. reload(sys)
  27. sys.setdefaultencoding('utf8')
  28. else:
  29. raw_input = input
  30.  
  31.  
  32. class MUCBot(sleekxmpp.ClientXMPP):
  33.  
  34. """
  35. A simple SleekXMPP bot that will greets those
  36. who enter the room, and acknowledge any messages
  37. that mentions the bot's nickname.
  38. """
  39.  
  40. def __init__(self, jid, password, room, nick, logfile):
  41. sleekxmpp.ClientXMPP.__init__(self, jid, password)
  42.  
  43. self.room = room
  44. self.nick = nick
  45. self.logfile = logfile
  46.  
  47. # The session_start event will be triggered when
  48. # the bot establishes its connection with the server
  49. # and the XML streams are ready for use. We want to
  50. # listen for this event so that we we can initialize
  51. # our roster.
  52. self.add_event_handler("session_start", self.start)
  53.  
  54. # The groupchat_message event is triggered whenever a message
  55. # stanza is received from any chat room. If you also also
  56. # register a handler for the 'message' event, MUC messages
  57. # will be processed by both handlers.
  58. self.add_event_handler("groupchat_message", self.muc_message)
  59.  
  60. # The groupchat_presence event is triggered whenever a
  61. # presence stanza is received from any chat room, including
  62. # any presences you send yourself. To limit event handling
  63. # to a single room, use the events muc::room@server::presence,
  64. # muc::room@server::got_online, or muc::room@server::got_offline.
  65. self.add_event_handler("muc::%s::got_online" % self.room,
  66. self.muc_online)
  67.  
  68.  
  69. def start(self, event):
  70. """
  71. Process the session_start event.
  72.  
  73. Typical actions for the session_start event are
  74. requesting the roster and broadcasting an initial
  75. presence stanza.
  76.  
  77. Arguments:
  78. event -- An empty dictionary. The session_start
  79. event does not provide any additional
  80. data.
  81. """
  82. self.get_roster()
  83. self.send_presence()
  84. self.plugin['xep_0045'].joinMUC(self.room,
  85. self.nick,
  86. # If a room password is needed, use:
  87. # password=the_room_password,
  88. wait=True)
  89.  
  90. def muc_message(self, msg):
  91. """
  92. Process incoming message stanzas from any chat room. Be aware
  93. that if you also have any handlers for the 'message' event,
  94. message stanzas may be processed by both handlers, so check
  95. the 'type' attribute when using a 'message' event handler.
  96.  
  97. Whenever the bot's nickname is mentioned, respond to
  98. the message.
  99.  
  100. IMPORTANT: Always check that a message is not from yourself,
  101. otherwise you will create an infinite loop responding
  102. to your own messages.
  103.  
  104. This handler will reply to messages that mention
  105. the bot's nickname.
  106.  
  107. Arguments:
  108. msg -- The received message stanza. See the documentation
  109. for stanza objects and the Message stanza to see
  110. how it may be used.
  111. """
  112. print msg
  113. ts = msg.xml.attrib['ts']
  114.  
  115. time = datetime.datetime.fromtimestamp(float(ts)).strftime('%Y-%m-%d %H:%M:%S')
  116. logmsg = "[%s] %s: %s\n" % (time, msg['mucnick'], msg['body'])
  117. with open(self.logfile, 'a') as logfile_:
  118. logfile_.write(logmsg.encode("UTF-8"))
  119. print(logmsg.encode("UTF-8"))
  120.  
  121. def muc_online(self, presence):
  122. """
  123. Process a presence stanza from a chat room. In this case,
  124. presences from users that have just come online are
  125. handled by sending a welcome message that includes
  126. the user's nickname and role in the room.
  127.  
  128. Arguments:
  129. presence -- The received presence stanza. See the
  130. documentation for the Presence stanza
  131. to see how else it may be used.
  132. """
  133.  
  134. if __name__ == '__main__':
  135. # Setup the command line arguments.
  136. optp = OptionParser()
  137.  
  138. # Output verbosity options.
  139. optp.add_option('-q', '--quiet', help='set logging to ERROR',
  140. action='store_const', dest='loglevel',
  141. const=logging.ERROR, default=logging.INFO)
  142. optp.add_option('-d', '--debug', help='set logging to DEBUG',
  143. action='store_const', dest='loglevel',
  144. const=logging.DEBUG, default=logging.INFO)
  145. optp.add_option('-v', '--verbose', help='set logging to COMM',
  146. action='store_const', dest='loglevel',
  147. const=5, default=logging.INFO)
  148.  
  149. # JID and password options.
  150. optp.add_option("-j", "--jid", dest="jid",
  151. help="JID to use")
  152. optp.add_option("-p", "--password", dest="password",
  153. help="password to use")
  154. optp.add_option("-r", "--room", dest="room",
  155. help="MUC room to join")
  156. optp.add_option("-n", "--nick", dest="nick",
  157. help="MUC nickname")
  158. optp.add_option("-o", "--output-file", dest="logfile",
  159. help="History output file")
  160.  
  161. opts, args = optp.parse_args()
  162.  
  163. # Setup logging.
  164. logging.basicConfig(level=opts.loglevel,
  165. format='%(levelname)-8s %(message)s')
  166.  
  167. if opts.jid is None:
  168. opts.jid = raw_input("Username: ")
  169. if opts.password is None:
  170. opts.password = getpass.getpass("Password: ")
  171. if opts.room is None:
  172. opts.room = raw_input("MUC room: ")
  173. if opts.nick is None:
  174. opts.nick = raw_input("MUC nickname: ")
  175. if opts.logfile is None:
  176. opts.logfile = raw_input("History output file: ")
  177.  
  178. # Setup the MUCBot and register plugins. Note that while plugins may
  179. # have interdependencies, the order in which you register them does
  180. # not matter.
  181. xmpp = MUCBot(opts.jid, opts.password, opts.room, opts.nick, opts.logfile)
  182. xmpp.register_plugin('xep_0030') # Service Discovery
  183. xmpp.register_plugin('xep_0045') # Multi-User Chat
  184. xmpp.register_plugin('xep_0199') # XMPP Ping
  185.  
  186. # Connect to the XMPP server and start processing XMPP stanzas.
  187. if xmpp.connect():
  188. # If you do not have the dnspython library installed, you will need
  189. # to manually specify the name of the server if it does not match
  190. # the one in the JID. For example, to use Google Talk you would
  191. # need to use:
  192. #
  193. # if xmpp.connect(('talk.google.com', 5222)):
  194. # ...
  195. xmpp.process(block=True)
  196. print("Done")
  197. else:
  198. print("Unable to connect.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement