cedbot_muc.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 send_msg(self, f, body):
  70. print("SEND_MSG ---- {0} from {1}".format(body, self.jid))
  71. self.send_message(mto=f,
  72. mbody=body,
  73. mtype='groupchat')
  74. # def beep(self, hz):
  75. # # TODO: make convesdis beeping
  76. #
  77. # def speak():
  78. # # TODO: make convesdis speaking
  79. #
  80. def learn(self, question, user):
  81. # TODO: record unanswerable questions with user from and ask me
  82. print('LEARN ---- unanswered question "%s" by %s' % (question, user))
  83. def muc_message(self, msg):
  84. """
  85. Process incoming message stanzas from any chat room. Be aware
  86. that if you also have any handlers for the 'message' event,
  87. message stanzas may be processed by both handlers, so check
  88. the 'type' attribute when using a 'message' event handler.
  89. Whenever the bot's nickname is mentioned, respond to
  90. the message.
  91. IMPORTANT: Always check that a message is not from yourself,
  92. otherwise you will create an infinite loop responding
  93. to your own messages.
  94. This handler will reply to messages that mention
  95. the bot's nickname.
  96. Arguments:
  97. msg -- The received message stanza. See the documentation
  98. for stanza objects and the Message stanza to see
  99. how it may be used.
  100. """
  101. if msg['mucnick'] != self.nick:
  102. f = msg['from'].bare
  103. if self.nick in msg['body']:
  104. # self.send_msg(self, msg, ":), %s." % msg['mucnick'])
  105. self.send_msg(f, ':) {0}.'.format(msg['mucnick']))
  106. # if 'bip' in msg['body']
  107. # TODO: bip
  108. if '?' in msg['body']:
  109. if 'qui es-tu' in msg['body']:
  110. self.send_msg(f, "Je suis cedbot, le chatbot qui vie dans l'espace transitionel de la convivialité des espaces discrets")
  111. self.send_msg(f, "plus d'infos : http://convivialite-espaces-discrets.net ;)")
  112. else:
  113. self.send_msg(f, "humm ...")
  114. self.send_msg(f, "J'ai l'impression que vous m'avez posé une question")
  115. self.send_msg(f, "mais je ne suis pas (encore) capable d'y répondre ... :/")
  116. self.send_msg(f, "Je ne suis qu'un bot après tout ¯\_(ツ)_/¯")
  117. self.send_msg(f, "mais je vais essayer d'en apprendre plus pour pouvoir vous répondre")
  118. self.send_msg(f, "revenez plus tard avec la même question")
  119. # self.send_msg(f, "i'll tell you when i'm ready :)")
  120. self.learn(msg['body'], msg['mucnick'])
  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. Arguments:
  128. presence -- The received presence stanza. See the
  129. documentation for the Presence stanza
  130. to see how else it may be used.
  131. """
  132. if presence['muc']['nick'] != self.nick and presence['muc']['nick'] != 'bachir':
  133. f = presence['from'].bare
  134. print('------ from : %s' % f)
  135. self.send_msg(f, 'Salut {0}'.format(presence['muc']['nick']))
  136. if __name__ == '__main__':
  137. # Setup the command line arguments.
  138. optp = OptionParser()
  139. # Output verbosity options.
  140. optp.add_option('-q', '--quiet', help='set logging to ERROR',
  141. action='store_const', dest='loglevel',
  142. const=logging.ERROR, default=logging.INFO)
  143. optp.add_option('-d', '--debug', help='set logging to DEBUG',
  144. action='store_const', dest='loglevel',
  145. const=logging.DEBUG, default=logging.INFO)
  146. optp.add_option('-v', '--verbose', help='set logging to COMM',
  147. action='store_const', dest='loglevel',
  148. const=5, default=logging.INFO)
  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. opts, args = optp.parse_args()
  159. # Setup logging.
  160. logging.basicConfig(level=opts.loglevel,
  161. format='%(levelname)-8s %(message)s')
  162. if opts.jid is None:
  163. opts.jid = raw_input("Username: ")
  164. if opts.password is None:
  165. opts.password = getpass.getpass("Password: ")
  166. if opts.room is None:
  167. opts.room = raw_input("MUC room: ")
  168. if opts.nick is None:
  169. opts.nick = raw_input("MUC nickname: ")
  170. # Setup the MUCBot and register plugins. Note that while plugins may
  171. # have interdependencies, the order in which you register them does
  172. # not matter.
  173. xmpp = MUCBot(opts.jid, opts.password, opts.room, opts.nick)
  174. xmpp.register_plugin('xep_0030') # Service Discovery
  175. xmpp.register_plugin('xep_0045') # Multi-User Chat
  176. xmpp.register_plugin('xep_0199') # XMPP Ping
  177. # Connect to the XMPP server and start processing XMPP stanzas.
  178. if xmpp.connect():
  179. # If you do not have the dnspython library installed, you will need
  180. # to manually specify the name of the server if it does not match
  181. # the one in the JID. For example, to use Google Talk you would
  182. # need to use:
  183. #
  184. # if xmpp.connect(('talk.google.com', 5222)):
  185. # ...
  186. xmpp.process(block=True)
  187. print("Done")
  188. else:
  189. print("Unable to connect.")