Remove google modules from setup.py file
[slixmpp.git] / examples / pubsub_client.py
blob56135ec10bb540c405540d968ce78a73a2a4b0ac
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
13 # Python versions before 3.0 do not use UTF-8 encoding
14 # by default. To ensure that Unicode is handled properly
15 # throughout Slixmpp, we will set the default encoding
16 # ourselves to UTF-8.
17 if sys.version_info < (3, 0):
18 from slixmpp.util.misc_ops import setdefaultencoding
19 setdefaultencoding('utf8')
20 else:
21 raw_input = input
24 class PubsubClient(slixmpp.ClientXMPP):
26 def __init__(self, jid, password, server,
27 node=None, action='list', data=''):
28 super(PubsubClient, self).__init__(jid, password)
30 self.register_plugin('xep_0030')
31 self.register_plugin('xep_0059')
32 self.register_plugin('xep_0060')
34 self.actions = ['nodes', 'create', 'delete',
35 'publish', 'get', 'retract',
36 'purge', 'subscribe', 'unsubscribe']
38 self.action = action
39 self.node = node
40 self.data = data
41 self.pubsub_server = server
43 self.add_event_handler('session_start', self.start, threaded=True)
45 def start(self, event):
46 self.get_roster()
47 self.send_presence()
49 try:
50 getattr(self, self.action)()
51 except:
52 logging.error('Could not execute: %s' % self.action)
53 self.disconnect()
55 def nodes(self):
56 try:
57 result = self['xep_0060'].get_nodes(self.pubsub_server, self.node)
58 for item in result['disco_items']['items']:
59 print(' - %s' % str(item))
60 except:
61 logging.error('Could not retrieve node list.')
63 def create(self):
64 try:
65 self['xep_0060'].create_node(self.pubsub_server, self.node)
66 except:
67 logging.error('Could not create node: %s' % self.node)
69 def delete(self):
70 try:
71 self['xep_0060'].delete_node(self.pubsub_server, self.node)
72 print('Deleted node: %s' % self.node)
73 except:
74 logging.error('Could not delete node: %s' % self.node)
76 def publish(self):
77 payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data)
78 try:
79 result = self['xep_0060'].publish(self.pubsub_server, self.node, payload=payload)
80 id = result['pubsub']['publish']['item']['id']
81 print('Published at item id: %s' % id)
82 except:
83 logging.error('Could not publish to: %s' % self.node)
85 def get(self):
86 try:
87 result = self['xep_0060'].get_item(self.pubsub_server, self.node, self.data)
88 for item in result['pubsub']['items']['substanzas']:
89 print('Retrieved item %s: %s' % (item['id'], tostring(item['payload'])))
90 except:
91 logging.error('Could not retrieve item %s from node %s' % (self.data, self.node))
93 def retract(self):
94 try:
95 result = self['xep_0060'].retract(self.pubsub_server, self.node, self.data)
96 print('Retracted item %s from node %s' % (self.data, self.node))
97 except:
98 logging.error('Could not retract item %s from node %s' % (self.data, self.node))
100 def purge(self):
101 try:
102 result = self['xep_0060'].purge(self.pubsub_server, self.node)
103 print('Purged all items from node %s' % self.node)
104 except:
105 logging.error('Could not purge items from node %s' % self.node)
107 def subscribe(self):
108 try:
109 result = self['xep_0060'].subscribe(self.pubsub_server, self.node)
110 print('Subscribed %s to node %s' % (self.boundjid.bare, self.node))
111 except:
112 logging.error('Could not subscribe %s to node %s' % (self.boundjid.bare, self.node))
114 def unsubscribe(self):
115 try:
116 result = self['xep_0060'].unsubscribe(self.pubsub_server, self.node)
117 print('Unsubscribed %s from node %s' % (self.boundjid.bare, self.node))
118 except:
119 logging.error('Could not unsubscribe %s from node %s' % (self.boundjid.bare, self.node))
124 if __name__ == '__main__':
125 # Setup the command line arguments.
126 optp = OptionParser()
127 optp.version = '%%prog 0.1'
128 optp.usage = "Usage: %%prog [options] <jid> " + \
129 'nodes|create|delete|purge|subscribe|unsubscribe|publish|retract|get' + \
130 ' [<node> <data>]'
132 optp.add_option('-q','--quiet', help='set logging to ERROR',
133 action='store_const',
134 dest='loglevel',
135 const=logging.ERROR,
136 default=logging.ERROR)
137 optp.add_option('-d','--debug', help='set logging to DEBUG',
138 action='store_const',
139 dest='loglevel',
140 const=logging.DEBUG,
141 default=logging.ERROR)
142 optp.add_option('-v','--verbose', help='set logging to COMM',
143 action='store_const',
144 dest='loglevel',
145 const=5,
146 default=logging.ERROR)
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 opts,args = optp.parse_args()
155 # Setup logging.
156 logging.basicConfig(level=opts.loglevel,
157 format='%(levelname)-8s %(message)s')
159 if len(args) < 2:
160 optp.print_help()
161 exit()
163 if opts.jid is None:
164 opts.jid = raw_input("Username: ")
165 if opts.password is None:
166 opts.password = getpass.getpass("Password: ")
168 if len(args) == 2:
169 args = (args[0], args[1], '', '', '')
170 elif len(args) == 3:
171 args = (args[0], args[1], args[2], '', '')
172 elif len(args) == 4:
173 args = (args[0], args[1], args[2], args[3], '')
176 # Setup the Pubsub client
177 xmpp = PubsubClient(opts.jid, opts.password,
178 server=args[0],
179 node=args[2],
180 action=args[1],
181 data=args[3])
183 # If you are working with an OpenFire server, you may need
184 # to adjust the SSL version used:
185 # xmpp.ssl_version = ssl.PROTOCOL_SSLv3
187 # If you want to verify the SSL certificates offered by a server:
188 # xmpp.ca_certs = "path/to/ca/cert"
190 # Connect to the XMPP server and start processing XMPP stanzas.
191 if xmpp.connect():
192 # If you do not have the dnspython library installed, you will need
193 # to manually specify the name of the server if it does not match
194 # the one in the JID. For example, to use Google Talk you would
195 # need to use:
197 # if xmpp.connect(('talk.google.com', 5222)):
198 # ...
199 xmpp.process(block=True)
200 else:
201 print("Unable to connect.")