2 # -*- coding: utf-8 -*-
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.
15 from optparse
import OptionParser
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
23 if sys
.version_info
< (3, 0):
24 from slixmpp
.util
.misc_ops
import setdefaultencoding
25 setdefaultencoding('utf8')
30 class AdminCommands(slixmpp
.ClientXMPP
):
33 A simple Slixmpp bot that uses admin commands to
34 add a new user to a server.
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
):
46 Process the session_start event.
48 Typical actions for the session_start event are
49 requesting the roster and broadcasting an initial
53 event -- An empty dictionary. The session_start
54 event does not provide any additional
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
)
71 def command_error(iq
, session
):
72 print('Error completing command')
73 print('%s: %s' % (iq
['error']['condition'],
75 self
['xep_0050'].terminate_command(session
)
78 def process_form(iq
, session
):
79 form
= iq
['command']['form']
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'):
90 answers
[var
] = raw_input('%s: ' % field
['label'])
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)
109 'next': process_form
,
110 'error': command_error
113 print('Invalid command name: %s' % self
.command
)
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",
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()
143 logging
.basicConfig(level
=opts
.loglevel
,
144 format
='%(levelname)-8s %(message)s')
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
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.
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
173 # if xmpp.connect(('talk.google.com', 5222)):
175 xmpp
.process(block
=True)
178 print("Unable to connect.")