Rename to slixmpp
[slixmpp.git] / examples / admin_commands.py
blobed81b88565001397f6736e48c7335fb2ca18c737
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 AdminCommands(slixmpp.ClientXMPP):
32 """
33 A simple Slixmpp bot that uses admin commands to
34 add a new user to a server.
35 """
37 def __init__(self, jid, password, command):
38 slixmpp.ClientXMPP.__init__(self, jid, password)
40 self.command = command
42 self.add_event_handler("session_start", self.start)
44 def start(self, event):
45 """
46 Process the session_start event.
48 Typical actions for the session_start event are
49 requesting the roster and broadcasting an initial
50 presence stanza.
52 Arguments:
53 event -- An empty dictionary. The session_start
54 event does not provide any additional
55 data.
56 """
57 self.send_presence()
58 self.get_roster()
60 def command_success(iq, session):
61 print('Command completed')
62 if iq['command']['form']:
63 for var, field in iq['command']['form']['fields'].items():
64 print('%s: %s' % (var, field['value']))
65 if iq['command']['notes']:
66 print('Command Notes:')
67 for note in iq['command']['notes']:
68 print('%s: %s' % note)
69 self.disconnect()
71 def command_error(iq, session):
72 print('Error completing command')
73 print('%s: %s' % (iq['error']['condition'],
74 iq['error']['text']))
75 self['xep_0050'].terminate_command(session)
76 self.disconnect()
78 def process_form(iq, session):
79 form = iq['command']['form']
80 answers = {}
81 for var, field in form['fields'].items():
82 if var != 'FORM_TYPE':
83 if field['type'] == 'boolean':
84 answers[var] = raw_input('%s (y/n): ' % field['label'])
85 if answers[var].lower() in ('1', 'true', 'y', 'yes'):
86 answers[var] = '1'
87 else:
88 answers[var] = '0'
89 else:
90 answers[var] = raw_input('%s: ' % field['label'])
91 else:
92 answers['FORM_TYPE'] = field['value']
93 form['type'] = 'submit'
94 form['values'] = answers
96 session['next'] = command_success
97 session['payload'] = form
99 self['xep_0050'].complete_command(session)
101 session = {'next': process_form,
102 'error': command_error}
104 command = self.command.replace('-', '_')
105 handler = getattr(self['xep_0133'], command, None)
107 if handler:
108 handler(session={
109 'next': process_form,
110 'error': command_error
112 else:
113 print('Invalid command name: %s' % self.command)
114 self.disconnect()
117 if __name__ == '__main__':
118 # Setup the command line arguments.
119 optp = OptionParser()
121 # Output verbosity options.
122 optp.add_option('-q', '--quiet', help='set logging to ERROR',
123 action='store_const', dest='loglevel',
124 const=logging.ERROR, default=logging.INFO)
125 optp.add_option('-d', '--debug', help='set logging to DEBUG',
126 action='store_const', dest='loglevel',
127 const=logging.DEBUG, default=logging.INFO)
128 optp.add_option('-v', '--verbose', help='set logging to COMM',
129 action='store_const', dest='loglevel',
130 const=5, default=logging.INFO)
132 # JID and password options.
133 optp.add_option("-j", "--jid", dest="jid",
134 help="JID to use")
135 optp.add_option("-p", "--password", dest="password",
136 help="password to use")
137 optp.add_option("-c", "--command", dest="command",
138 help="admin command to use")
140 opts, args = optp.parse_args()
142 # Setup logging.
143 logging.basicConfig(level=opts.loglevel,
144 format='%(levelname)-8s %(message)s')
146 if opts.jid is None:
147 opts.jid = raw_input("Username: ")
148 if opts.password is None:
149 opts.password = getpass.getpass("Password: ")
150 if opts.command is None:
151 opts.command = raw_input("Admin command: ")
153 # Setup the CommandBot and register plugins. Note that while plugins may
154 # have interdependencies, the order in which you register them does
155 # not matter.
156 xmpp = AdminCommands(opts.jid, opts.password, opts.command)
157 xmpp.register_plugin('xep_0133') # Service Administration
159 # If you are working with an OpenFire server, you may need
160 # to adjust the SSL version used:
161 # xmpp.ssl_version = ssl.PROTOCOL_SSLv3
163 # If you want to verify the SSL certificates offered by a server:
164 # xmpp.ca_certs = "path/to/ca/cert"
166 # Connect to the XMPP server and start processing XMPP stanzas.
167 if xmpp.connect():
168 # If you do not have the dnspython library installed, you will need
169 # to manually specify the name of the server if it does not match
170 # the one in the JID. For example, to use Google Talk you would
171 # need to use:
173 # if xmpp.connect(('talk.google.com', 5222)):
174 # ...
175 xmpp.process(block=True)
176 print("Done")
177 else:
178 print("Unable to connect.")