cedbot_muc.py 7.1 KB

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