Remove google modules from setup.py file
[slixmpp.git] / examples / pubsub_events.py
blob679112af9deb5e69a26e0682b1694b577bb2c5a0
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
4 import sys
5 import logging
6 import getpass
7 from optparse import OptionParser
9 import slixmpp
10 from slixmpp.xmlstream import ET, tostring
11 from slixmpp.xmlstream.matcher import StanzaPath
12 from slixmpp.xmlstream.handler import Callback
15 # Python versions before 3.0 do not use UTF-8 encoding
16 # by default. To ensure that Unicode is handled properly
17 # throughout Slixmpp, we will set the default encoding
18 # ourselves to UTF-8.
19 if sys.version_info < (3, 0):
20 from slixmpp.util.misc_ops import setdefaultencoding
21 setdefaultencoding('utf8')
22 else:
23 raw_input = input
26 class PubsubEvents(slixmpp.ClientXMPP):
28 def __init__(self, jid, password):
29 super(PubsubEvents, self).__init__(jid, password)
31 self.register_plugin('xep_0030')
32 self.register_plugin('xep_0059')
33 self.register_plugin('xep_0060')
35 self.add_event_handler('session_start', self.start)
37 # Some services may require configuration to allow
38 # sending delete, configuration, or subscription events.
39 self.add_event_handler('pubsub_publish', self._publish)
40 self.add_event_handler('pubsub_retract', self._retract)
41 self.add_event_handler('pubsub_purge', self._purge)
42 self.add_event_handler('pubsub_delete', self._delete)
43 self.add_event_handler('pubsub_config', self._config)
44 self.add_event_handler('pubsub_subscription', self._subscription)
46 # Want to use nicer, more specific pubsub event names?
47 # self['xep_0060'].map_node_event('node_name', 'event_prefix')
48 # self.add_event_handler('event_prefix_publish', handler)
49 # self.add_event_handler('event_prefix_retract', handler)
50 # self.add_event_handler('event_prefix_purge', handler)
51 # self.add_event_handler('event_prefix_delete', handler)
53 def start(self, event):
54 self.get_roster()
55 self.send_presence()
57 def _publish(self, msg):
58 """Handle receiving a publish item event."""
59 print('Published item %s to %s:' % (
60 msg['pubsub_event']['items']['item']['id'],
61 msg['pubsub_event']['items']['node']))
62 data = msg['pubsub_event']['items']['item']['payload']
63 if data is not None:
64 print(tostring(data))
65 else:
66 print('No item content')
68 def _retract(self, msg):
69 """Handle receiving a retract item event."""
70 print('Retracted item %s from %s' % (
71 msg['pubsub_event']['items']['retract']['id'],
72 msg['pubsub_event']['items']['node']))
74 def _purge(self, msg):
75 """Handle receiving a node purge event."""
76 print('Purged all items from %s' % (
77 msg['pubsub_event']['purge']['node']))
79 def _delete(self, msg):
80 """Handle receiving a node deletion event."""
81 print('Deleted node %s' % (
82 msg['pubsub_event']['delete']['node']))
84 def _config(self, msg):
85 """Handle receiving a node configuration event."""
86 print('Configured node %s:' % (
87 msg['pubsub_event']['configuration']['node']))
88 print(msg['pubsub_event']['configuration']['form'])
90 def _subscription(self, msg):
91 """Handle receiving a node subscription event."""
92 print('Subscription change for node %s:' % (
93 msg['pubsub_event']['subscription']['node']))
94 print(msg['pubsub_event']['subscription'])
97 if __name__ == '__main__':
98 # Setup the command line arguments.
99 optp = OptionParser()
101 # Output verbosity options.
102 optp.add_option('-q', '--quiet', help='set logging to ERROR',
103 action='store_const', dest='loglevel',
104 const=logging.ERROR, default=logging.INFO)
105 optp.add_option('-d', '--debug', help='set logging to DEBUG',
106 action='store_const', dest='loglevel',
107 const=logging.DEBUG, default=logging.INFO)
108 optp.add_option('-v', '--verbose', help='set logging to COMM',
109 action='store_const', dest='loglevel',
110 const=5, default=logging.INFO)
112 # JID and password options.
113 optp.add_option("-j", "--jid", dest="jid",
114 help="JID to use")
115 optp.add_option("-p", "--password", dest="password",
116 help="password to use")
118 opts, args = optp.parse_args()
120 # Setup logging.
121 logging.basicConfig(level=opts.loglevel,
122 format='%(levelname)-8s %(message)s')
124 if opts.jid is None:
125 opts.jid = raw_input("Username: ")
126 if opts.password is None:
127 opts.password = getpass.getpass("Password: ")
129 logging.info("Run this in conjunction with the pubsub_client.py " + \
130 "example to watch events happen as you give commands.")
132 # Setup the PubsubEvents listener
133 xmpp = PubsubEvents(opts.jid, opts.password)
135 # If you are working with an OpenFire server, you may need
136 # to adjust the SSL version used:
137 # xmpp.ssl_version = ssl.PROTOCOL_SSLv3
139 # If you want to verify the SSL certificates offered by a server:
140 # xmpp.ca_certs = "path/to/ca/cert"
142 # Connect to the XMPP server and start processing XMPP stanzas.
143 if xmpp.connect():
144 # If you do not have the dnspython library installed, you will need
145 # to manually specify the name of the server if it does not match
146 # the one in the JID. For example, to use Google Talk you would
147 # need to use:
149 # if xmpp.connect(('talk.google.com', 5222)):
150 # ...
151 xmpp.process(block=True)
152 print("Done")
153 else:
154 print("Unable to connect.")