Advertisement
Guest User

Untitled

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