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 CommandUserBot(slixmpp
.ClientXMPP
):
33 A simple Slixmpp bot that uses the adhoc command
34 provided by the adhoc_provider.py example.
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
48 self
.add_event_handler("session_start", self
.start
)
49 self
.add_event_handler("message", self
.message
)
51 def start(self
, event
):
53 Process the session_start event.
55 Typical actions for the session_start event are
56 requesting the roster and broadcasting an initial
60 event -- An empty dictionary. The session_start
61 event does not provide any additional
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
,
81 def message(self
, msg
):
83 Process incoming message stanzas.
86 msg -- The received message stanza.
88 logging
.info(msg
['body'])
90 def _command_start(self
, iq
, session
):
92 Process the initial command result.
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.
101 # The greeting command provides a form with a single field:
102 # <x xmlns="jabber:x:data" type="form">
103 # <field var="greeting"
105 # label="Your greeting" />
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.
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
)
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",
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",
168 opts
, args
= optp
.parse_args()
171 logging
.basicConfig(level
=opts
.loglevel
,
172 format
='%(levelname)-8s %(message)s')
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
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.
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
205 # if xmpp.connect(('talk.google.com', 5222)):
207 xmpp
.process(block
=True)
210 print("Unable to connect.")