Remove google modules from setup.py file
[slixmpp.git] / examples / adhoc_user.py
blobd4b650bcd67ca77a043113f3815dc0e0cd04e4c0
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
4 """
5 Slixmpp: The Slick XMPP Library
6 Copyright (C) 2010 Nathanael C. Fritz
7 This file is part of Slixmpp.
9 See the file LICENSE for copying permission.
10 """
12 import sys
13 import logging
14 import getpass
15 from optparse import OptionParser
17 import slixmpp
19 # Python versions before 3.0 do not use UTF-8 encoding
20 # by default. To ensure that Unicode is handled properly
21 # throughout Slixmpp, we will set the default encoding
22 # ourselves to UTF-8.
23 if sys.version_info < (3, 0):
24 from slixmpp.util.misc_ops import setdefaultencoding
25 setdefaultencoding('utf8')
26 else:
27 raw_input = input
30 class CommandUserBot(slixmpp.ClientXMPP):
32 """
33 A simple Slixmpp bot that uses the adhoc command
34 provided by the adhoc_provider.py example.
35 """
37 def __init__(self, jid, password, other, greeting):
38 slixmpp.ClientXMPP.__init__(self, jid, password)
40 self.command_provider = other
41 self.greeting = greeting
43 # The session_start event will be triggered when
44 # the bot establishes its connection with the server
45 # and the XML streams are ready for use. We want to
46 # listen for this event so that we we can initialize
47 # our roster.
48 self.add_event_handler("session_start", self.start)
49 self.add_event_handler("message", self.message)
51 def start(self, event):
52 """
53 Process the session_start event.
55 Typical actions for the session_start event are
56 requesting the roster and broadcasting an initial
57 presence stanza.
59 Arguments:
60 event -- An empty dictionary. The session_start
61 event does not provide any additional
62 data.
63 """
64 self.send_presence()
65 self.get_roster()
67 # We first create a session dictionary containing:
68 # 'next' -- the handler to execute on a successful response
69 # 'error' -- the handler to execute if an error occurs
71 # The session may also contain custom data.
73 session = {'greeting': self.greeting,
74 'next': self._command_start,
75 'error': self._command_error}
77 self['xep_0050'].start_command(jid=self.command_provider,
78 node='greeting',
79 session=session)
81 def message(self, msg):
82 """
83 Process incoming message stanzas.
85 Arguments:
86 msg -- The received message stanza.
87 """
88 logging.info(msg['body'])
90 def _command_start(self, iq, session):
91 """
92 Process the initial command result.
94 Arguments:
95 iq -- The iq stanza containing the command result.
96 session -- A dictionary of data relevant to the command
97 session. Additional, custom data may be saved
98 here to persist across handler callbacks.
99 """
101 # The greeting command provides a form with a single field:
102 # <x xmlns="jabber:x:data" type="form">
103 # <field var="greeting"
104 # type="text-single"
105 # label="Your greeting" />
106 # </x>
108 form = self['xep_0004'].makeForm(ftype='submit')
109 form.addField(var='greeting',
110 value=session['greeting'])
112 session['payload'] = form
114 # We don't need to process the next result.
115 session['next'] = None
117 # Other options include using:
118 # continue_command() -- Continue to the next step in the workflow
119 # cancel_command() -- Stop command execution.
121 self['xep_0050'].complete_command(session)
123 def _command_error(self, iq, session):
125 Process an error that occurs during command execution.
127 Arguments:
128 iq -- The iq stanza containing the error.
129 session -- A dictionary of data relevant to the command
130 session. Additional, custom data may be saved
131 here to persist across handler callbacks.
133 logging.error("COMMAND: %s %s" % (iq['error']['condition'],
134 iq['error']['text']))
136 # Terminate the command's execution and clear its session.
137 # The session will automatically be cleared if no error
138 # handler is provided.
139 self['xep_0050'].terminate_command(session)
140 self.disconnect()
143 if __name__ == '__main__':
144 # Setup the command line arguments.
145 optp = OptionParser()
147 # Output verbosity options.
148 optp.add_option('-q', '--quiet', help='set logging to ERROR',
149 action='store_const', dest='loglevel',
150 const=logging.ERROR, default=logging.INFO)
151 optp.add_option('-d', '--debug', help='set logging to DEBUG',
152 action='store_const', dest='loglevel',
153 const=logging.DEBUG, default=logging.INFO)
154 optp.add_option('-v', '--verbose', help='set logging to COMM',
155 action='store_const', dest='loglevel',
156 const=5, default=logging.INFO)
158 # JID and password options.
159 optp.add_option("-j", "--jid", dest="jid",
160 help="JID to use")
161 optp.add_option("-p", "--password", dest="password",
162 help="password to use")
163 optp.add_option("-o", "--other", dest="other",
164 help="JID providing commands")
165 optp.add_option("-g", "--greeting", dest="greeting",
166 help="Greeting")
168 opts, args = optp.parse_args()
170 # Setup logging.
171 logging.basicConfig(level=opts.loglevel,
172 format='%(levelname)-8s %(message)s')
174 if opts.jid is None:
175 opts.jid = raw_input("Username: ")
176 if opts.password is None:
177 opts.password = getpass.getpass("Password: ")
178 if opts.other is None:
179 opts.other = raw_input("JID Providing Commands: ")
180 if opts.greeting is None:
181 opts.greeting = raw_input("Greeting: ")
183 # Setup the CommandBot and register plugins. Note that while plugins may
184 # have interdependencies, the order in which you register them does
185 # not matter.
186 xmpp = CommandUserBot(opts.jid, opts.password, opts.other, opts.greeting)
187 xmpp.register_plugin('xep_0030') # Service Discovery
188 xmpp.register_plugin('xep_0004') # Data Forms
189 xmpp.register_plugin('xep_0050') # Adhoc Commands
191 # If you are working with an OpenFire server, you may need
192 # to adjust the SSL version used:
193 # xmpp.ssl_version = ssl.PROTOCOL_SSLv3
195 # If you want to verify the SSL certificates offered by a server:
196 # xmpp.ca_certs = "path/to/ca/cert"
198 # Connect to the XMPP server and start processing XMPP stanzas.
199 if xmpp.connect():
200 # If you do not have the dnspython library installed, you will need
201 # to manually specify the name of the server if it does not match
202 # the one in the JID. For example, to use Google Talk you would
203 # need to use:
205 # if xmpp.connect(('talk.google.com', 5222)):
206 # ...
207 xmpp.process(block=True)
208 print("Done")
209 else:
210 print("Unable to connect.")