From 97378998a5f8c031444fd7a0c1b1007e9282df4d Mon Sep 17 00:00:00 2001 From: Lance Stout Date: Thu, 5 Jan 2012 11:31:54 -0500 Subject: Break the docs out into their own branch. --- docs/getting_started/component.rst | 75 +++++++ docs/getting_started/echobot.rst | 390 ++++++++++++++++++++++++++++++++++++ docs/getting_started/iq.rst | 182 +++++++++++++++++ docs/getting_started/muc.rst | 2 + docs/getting_started/presence.rst | 2 + docs/getting_started/proxy.rst | 42 ++++ docs/getting_started/scheduler.rst | 2 + docs/getting_started/sendlogout.rst | 94 +++++++++ 8 files changed, 789 insertions(+) create mode 100644 docs/getting_started/component.rst create mode 100644 docs/getting_started/echobot.rst create mode 100644 docs/getting_started/iq.rst create mode 100644 docs/getting_started/muc.rst create mode 100644 docs/getting_started/presence.rst create mode 100644 docs/getting_started/proxy.rst create mode 100644 docs/getting_started/scheduler.rst create mode 100644 docs/getting_started/sendlogout.rst (limited to 'docs/getting_started') diff --git a/docs/getting_started/component.rst b/docs/getting_started/component.rst new file mode 100644 index 00000000..ce548ba4 --- /dev/null +++ b/docs/getting_started/component.rst @@ -0,0 +1,75 @@ +.. _echocomponent: + +================================= +Create and Run a Server Component +================================= + +.. note:: + + If you have any issues working through this quickstart guide + or the other tutorials here, please either send a message to the + `mailing list `_ + or join the chat room at `sleek@conference.jabber.org + `_. + +If you have not yet installed SleekXMPP, do so now by either checking out a version +from `Github `_, or installing it using ``pip`` +or ``easy_install``. + +.. code-block:: sh + + pip install sleekxmpp # Or: easy_install sleekxmpp + + +Many XMPP applications eventually graduate to requiring to run as a server +component in order to meet scalability requirements. To demonstrate how to +turn an XMPP client bot into a component, we'll turn the echobot example +(:ref:`echobot`) into a component version. + +The first difference is that we will add an additional import statement: + +.. code-block:: python + + from sleekxmpp.componentxmpp import ComponentXMPP + +Likewise, we will change the bot's class definition to match: + +.. code-block:: python + + class EchoComponent(ComponentXMPP): + + def __init__(self, jid, secret, server, port): + ComponentXMPP.__init__(self, jid, secret, server, port) + +A component instance requires two extra parameters compared to a client +instance: ``server`` and ``port``. These specifiy the name and port of +the XMPP server that will be accepting the component. For example, for +a MUC component, the following could be used: + +.. code-block:: python + + muc = ComponentXMPP('muc.sleekxmpp.com', '******', 'sleekxmpp.com', 5555) + +.. note:: + + The ``server`` value is **NOT** derived from the provided JID for the + component, unlike with client connections. + +One difference with the component version is that we do not have +to handle the :term:`session_start` event if we don't wish to deal +with presence. + +The other, main difference with components is that the +``'from'`` value for every stanza must be explicitly set, since +components may send stanzas from multiple JIDs. To do so, +the :meth:`~sleekxmpp.basexmpp.BaseXMPP.send_message()` and +:meth:`~sleekxmpp.basexmpp.BaseXMPP.send_presence()` accept the parameters +``mfrom`` and ``pfrom``, respectively. For any method that uses +:class:`~sleekxmpp.stanza.iq.Iq` stanzas, ``ifrom`` may be used. + + +Final Product +------------- + +.. include:: ../../examples/echo_component.py + :literal: diff --git a/docs/getting_started/echobot.rst b/docs/getting_started/echobot.rst new file mode 100644 index 00000000..053a76f2 --- /dev/null +++ b/docs/getting_started/echobot.rst @@ -0,0 +1,390 @@ +.. _echobot: + +=============================== +SleekXMPP Quickstart - Echo Bot +=============================== + +.. note:: + + If you have any issues working through this quickstart guide + or the other tutorials here, please either send a message to the + `mailing list `_ + or join the chat room at `sleek@conference.jabber.org + `_. + +If you have not yet installed SleekXMPP, do so now by either checking out a version +from `Github `_, or installing it using ``pip`` +or ``easy_install``. + +.. code-block:: sh + + pip install sleekxmpp # Or: easy_install sleekxmpp + + +As a basic starting project, we will create an echo bot which will reply to any +messages sent to it. We will also go through adding some basic command line configuration +for enabling or disabling debug log outputs and setting the username and password +for the bot. + +For the command line options processing, we will use the built-in ``optparse`` +module and the ``getpass`` module for reading in passwords. + +TL;DR Just Give Me the Code +--------------------------- +As you wish: :ref:`the completed example `. + +Overview +-------- + +To get started, here is a brief outline of the structure that the final project will have: + +.. code-block:: python + + #!/usr/bin/env python + # -*- coding: utf-8 -*- + + import sys + import logging + import getpass + from optparse import OptionParser + + import sleekxmpp + + '''Here we will create out echo bot class''' + + if __name__ == '__main__': + '''Here we will configure and read command line options''' + + '''Here we will instantiate our echo bot''' + + '''Finally, we connect the bot and start listening for messages''' + +Default Encoding +---------------- +XMPP requires support for UTF-8 and so SleekXMPP must use UTF-8 as well. In +Python3 this is simple because Unicode is the default string type. For Python2.6+ +the situation is not as easy because standard strings are simply byte arrays and +use ASCII. We can get Python to use UTF-8 as the default encoding by including: + +.. code-block:: python + + if sys.version_info < (3, 0): + reload(sys) + sys.setdefaultencoding('utf8') + +.. warning:: + + Until we are able to ensure that SleekXMPP will always use Unicode in Python2.6+, this + may cause issues embedding SleekXMPP into other applications which assume ASCII encoding. + +Creating the EchoBot Class +-------------------------- + +There are three main types of entities within XMPP — servers, components, and +clients. Since our echo bot will only be responding to a few people, and won't need +to remember thousands of users, we will use a client connection. A client connection +is the same type that you use with your standard IM client such as Pidgin or Psi. + +SleekXMPP comes with a :class:`ClientXMPP ` class +which we can extend to add our message echoing feature. :class:`ClientXMPP ` +requires the parameters ``jid`` and ``password``, so we will let our ``EchoBot`` class accept those +as well. + +.. code-block:: python + + class EchoBot(sleekxmpp.ClientXMPP): + + def __init__(self, jid, password): + super(EchoBot, self).__init__(jid, password) + +Handling Session Start +~~~~~~~~~~~~~~~~~~~~~~ +The XMPP spec requires clients to broadcast its presence and retrieve its roster (buddy list) once +it connects and establishes a session with the XMPP server. Until these two tasks are completed, +some servers may not deliver or send messages or presence notifications to the client. So we now +need to be sure that we retrieve our roster and send an initial presence once the session has +started. To do that, we will register an event handler for the :term:`session_start` event. + +.. code-block:: python + + def __init__(self, jid, password): + super(EchoBot, self).__init__(jid, password) + + self.add_event_handler('session_start', self.start) + + +Since we want the method ``self.start`` to execute when the :term:`session_start` event is triggered, +we also need to define the ``self.start`` handler. + +.. code-block:: python + + def start(self, event): + self.send_presence() + self.get_roster() + +.. warning:: + + Not sending an initial presence and retrieving the roster when using a client instance can + prevent your program from receiving presence notifications or messages depending on the + XMPP server you have chosen. + +Our event handler, like every event handler, accepts a single parameter which typically is the stanza +that was received that caused the event. In this case, ``event`` will just be an empty dictionary since +there is no associated data. + +Our first task of sending an initial presence is done using :meth:`send_presence `. +Calling :meth:`send_presence ` without any arguments will send the simplest +stanza allowed in XMPP: + +.. code-block:: xml + + + + +The second requirement is fulfilled using :meth:`get_roster `, which +will send an IQ stanza requesting the roster to the server and then wait for the response. You may be wondering +what :meth:`get_roster ` returns since we are not saving any return +value. The roster data is saved by an internal handler to ``self.roster``, and in the case of a :class:`ClientXMPP +` instance to ``self.client_roster``. (The difference between ``self.roster`` and +``self.client_roster`` is that ``self.roster`` supports storing roster information for multiple JIDs, which is useful +for components, whereas ``self.client_roster`` stores roster data for just the client's JID.) + +It is possible for a timeout to occur while waiting for the server to respond, which can happen if the +network is excessively slow or the server is no longer responding. In that case, an :class:`IQTimeout +` is raised. Similarly, an :class:`IQError ` exception can +be raised if the request contained bad data or requested the roster for the wrong user. In either case, you can wrap the +``get_roster()`` call in a ``try``/``except`` block to retry the roster retrieval process. + +The XMPP stanzas from the roster retrieval process could look like this: + +.. code-block:: xml + + + + + + + + + + + +Responding to Messages +~~~~~~~~~~~~~~~~~~~~~~ +Now that an ``EchoBot`` instance handles :term:`session_start`, we can begin receiving and +responding to messages. Now we can register a handler for the :term:`message` event that is raised +whenever a messsage is received. + +.. code-block:: python + + def __init__(self, jid, password): + super(EchoBot, self).__init__(jid, password) + + self.add_event_handler('session_start', self.start) + self.add_event_handler('message', self.message) + + +The :term:`message` event is fired whenever a ```` stanza is received, including for +group chat messages, errors, etc. Properly responding to messages thus requires checking the +``'type'`` interface of the message :term:`stanza object`. For responding to only messages +addressed to our bot (and not from a chat room), we check that the type is either ``normal`` +or ``chat``. (Other potential types are ``error``, ``headline``, and ``groupchat``.) + +.. code-block:: python + + def message(self, msg): + if msg['type'] in ('normal', 'chat'): + msg.reply("Thanks for sending:\n%s" % msg['body']).send() + +Let's take a closer look at the ``.reply()`` method used above. For message stanzas, +``.reply()`` accepts the parameter ``body`` (also as the first positional argument), +which is then used as the value of the ```` element of the message. +Setting the appropriate ``to`` JID is also handled by ``.reply()``. + +Another way to have sent the reply message would be to use :meth:`send_message `, +which is a convenience method for generating and sending a message based on the values passed to it. If we were to use +this method, the above code would look as so: + +.. code-block:: python + + def message(self, msg): + if msg['type'] in ('normal', 'chat'): + self.send_message(mto=msg['from'], + mbody='Thanks for sending:\n%s' % msg['body']) + +Whichever method you choose to use, the results in action will look like this: + +.. code-block:: xml + + + Hej! + + + + Thanks for sending: + Hej! + + +.. note:: + XMPP does not require stanzas sent by a client to include a ``from`` attribute, and + leaves that responsibility to the XMPP server. However, if a sent stanza does + include a ``from`` attribute, it must match the full JID of the client or some + servers will reject it. SleekXMPP thus leaves out the ``from`` attribute when replying + using a client connection. + +Command Line Arguments and Logging +---------------------------------- + +While this isn't part of SleekXMPP itself, we do want our echo bot program to be able +to accept a JID and password from the command line instead of hard coding them. We will +use the ``optparse`` module for this, though there are several alternative methods, including +the newer ``argparse`` module. + +We want to accept three parameters: the JID for the echo bot, its password, and a flag for +displaying the debugging logs. We also want these to be optional parameters, since passing +a password directly through the command line can be a security risk. + +.. code-block:: python + + if __name__ == '__main__': + optp = OptionParser() + + optp.add_option('-d', '--debug', help='set logging to DEBUG', + action='store_const', dest='loglevel', + const=logging.DEBUG, default=logging.INFO) + optp.add_option("-j", "--jid", dest="jid", + help="JID to use") + optp.add_option("-p", "--password", dest="password", + help="password to use") + + opts, args = optp.parse_args() + + if opts.jid is None: + opts.jid = raw_input("Username: ") + if opts.password is None: + opts.password = getpass.getpass("Password: ") + +Since we included a flag for enabling debugging logs, we need to configure the +``logging`` module to behave accordingly. + +.. code-block:: python + + if __name__ == '__main__': + + # .. option parsing from above .. + + logging.basicConfig(level=opts.loglevel, + format='%(levelname)-8s %(message)s') + + +Connecting to the Server and Processing +--------------------------------------- +There are three steps remaining until our echo bot is complete: + 1. We need to instantiate the bot. + 2. The bot needs to connect to an XMPP server. + 3. We have to instruct the bot to start running and processing messages. + +Creating the bot is straightforward, but we can also perform some configuration +at this stage. For example, let's say we want our bot to support `service discovery +`_ and `pings `_: + +.. code-block:: python + + if __name__ == '__main__': + + # .. option parsing and logging steps from above + + xmpp = EchoBot(opts.jid, opts.password) + xmpp.register_plugin('xep_0030') # Service Discovery + xmpp.register_plugin('xep_0199') # Ping + +If the ``EchoBot`` class had a hard dependency on a plugin, we could register that plugin in +the ``EchoBot.__init__`` method instead. + +.. note:: + + If you are using the OpenFire server, you will need to include an additional + configuration step. OpenFire supports a different version of SSL than what + most servers and SleekXMPP support. + + .. code-block:: python + + import ssl + xmpp.ssl_version = ssl.PROTOCOL_SSLv3 + +Now we're ready to connect and begin echoing messages. If you have the package +``dnspython`` installed, then the :meth:`sleekxmpp.clientxmpp.ClientXMPP` method +will perform a DNS query to find the appropriate server to connect to for the +given JID. If you do not have ``dnspython``, then SleekXMPP will attempt to +connect to the hostname used by the JID, unless an address tuple is supplied +to :meth:`sleekxmpp.clientxmpp.ClientXMPP`. + +.. code-block:: python + + if __name__ == '__main__': + + # .. option parsing & echo bot configuration + + if xmpp.connect(): + xmpp.process(block=True) + else: + print('Unable to connect') + +.. note:: + + For Google Talk users withouth ``dnspython`` installed, the above code + should look like: + + .. code-block:: python + + if __name__ == '__main__': + + # .. option parsing & echo bot configuration + + if xmpp.connect(('talk.google.com', 5222)): + xmpp.process(block=True) + else: + print('Unable to connect') + +To begin responding to messages, you'll see we called :meth:`sleekxmpp.basexmpp.BaseXMPP.process` +which will start the event handling, send queue, and XML reader threads. It will also call +the :meth:`sleekxmpp.plugins.base.base_plugin.post_init` method on all registered plugins. By +passing ``block=True`` to :meth:`sleekxmpp.basexmpp.BaseXMPP.process` we are running the +main processing loop in the main thread of execution. The :meth:`sleekxmpp.basexmpp.BaseXMPP.process` +call will not return until after SleekXMPP disconnects. If you need to run the client in the background +for another program, use ``block=False`` to spawn the processing loop in its own thread. + +.. note:: + + Before 1.0, controlling the blocking behaviour of :meth:`sleekxmpp.basexmpp.BaseXMPP.process` was + done via the ``threaded`` argument. This arrangement was a source of confusion because some users + interpreted that as controlling whether or not SleekXMPP used threads at all, instead of how + the processing loop itself was spawned. + + The statements ``xmpp.process(threaded=False)`` and ``xmpp.process(block=True)`` are equivalent. + + +.. _echobot_complete: + +The Final Product +----------------- + +Here then is what the final result should look like after working through the guide above. The code +can also be found in the SleekXMPP `examples directory `_. + +.. compound:: + + You can run the code using: + + .. code-block:: sh + + python echobot.py -d -j echobot@example.com + + which will prompt for the password and then begin echoing messages. To test, open + your regular IM client and start a chat with the echo bot. Messages you send to it should + be mirrored back to you. Be careful if you are using the same JID for the echo bot that + you also have logged in with another IM client. Messages could be routed to your IM client instead + of the bot. + +.. include:: ../../examples/echo_client.py + :literal: diff --git a/docs/getting_started/iq.rst b/docs/getting_started/iq.rst new file mode 100644 index 00000000..98e0bdaf --- /dev/null +++ b/docs/getting_started/iq.rst @@ -0,0 +1,182 @@ +Send/Receive IQ Stanzas +======================= + +Unlike :class:`~sleekxmpp.stanza.message.Message` and +:class:`~sleekxmpp.stanza.presence.Presence` stanzas which only use +text data for basic usage, :class:`~sleekxmpp.stanza.iq.Iq` stanzas +require using XML payloads, and generally entail creating a new +SleekXMPP plugin to provide the necessary convenience methods to +make working with them easier. + +Basic Use +--------- + +XMPP's use of :class:`~sleekxmpp.stanza.iq.Iq` stanzas is built around +namespaced ```` elements. For clients, just sending the +empty ```` element will suffice for retrieving information. For +example, a very basic implementation of service discovery would just +need to be able to send: + +.. code-block:: xml + + + + + +Creating Iq Stanzas +~~~~~~~~~~~~~~~~~~~ + +SleekXMPP provides built-in support for creating basic :class:`~sleekxmpp.stanza.iq.Iq` +stanzas this way. The relevant methods are: + +* :meth:`~sleekxmpp.basexmpp.BaseXMPP.make_iq` +* :meth:`~sleekxmpp.basexmpp.BaseXMPP.make_iq_get` +* :meth:`~sleekxmpp.basexmpp.BaseXMPP.make_iq_set` +* :meth:`~sleekxmpp.basexmpp.BaseXMPP.make_iq_result` +* :meth:`~sleekxmpp.basexmpp.BaseXMPP.make_iq_error` +* :meth:`~sleekxmpp.basexmpp.BaseXMPP.make_iq_query` + +These methods all follow the same pattern: create or modify an existing +:class:`~sleekxmpp.stanza.iq.Iq` stanza, set the ``'type'`` value based +on the method name, and finally add a ```` element with the given +namespace. For example, to produce the query above, you would use: + +.. code-block:: python + + self.make_iq_get(queryxmlns='http://jabber.org/protocol/disco#info', + ito='user@example.com') + + +Sending Iq Stanzas +~~~~~~~~~~~~~~~~~~ + +Once an :class:`~sleekxmpp.stanza.iq.Iq` stanza is created, sending it +over the wire is done using its :meth:`~sleekxmpp.stanza.iq.Iq.send()` +method, like any other stanza object. However, there are a few extra +options to control how to wait for the query's response. + +These options are: + +* ``block``: The default behaviour is that :meth:`~sleekxmpp.stanza.iq.Iq.send()` + will block until a response is received and the response stanza will be the + return value. Setting ``block`` to ``False`` will cause the call to return + immediately. In which case, you will need to arrange some way to capture + the response stanza if you need it. + +* ``timeout``: When using the blocking behaviour, the call will eventually + timeout with an error. The default timeout is 30 seconds, but this may + be overidden two ways. To change the timeout globally, set: + + .. code-block:: python + + self.response_timeout = 10 + + To change the timeout for a single call, the ``timeout`` parameter works: + + .. code-block:: python + + iq.send(timeout=60) + +* ``callback``: When not using a blocking call, using the ``callback`` + argument is a simple way to register a handler that will execute + whenever a response is finally received. Using this method, there + is no timeout limit. In case you need to remove the callback, the + name of the newly created callback is returned. + + .. code-block:: python + + cb_name = iq.send(callback=self.a_callback) + + # ... later if we need to cancel + self.remove_handler(cb_name) + +Properly working with :class:`~sleekxmpp.stanza.iq.Iq` stanzas requires +handling the intended, normal flow, error responses, and timed out +requests. To make this easier, two exceptions may be thrown by +:meth:`~sleekxmpp.stanza.iq.Iq.send()`: :exc:`~sleekxmpp.exceptions.IqError` +and :exc:`~sleekxmpp.exceptions.IqTimeout`. These exceptions only +apply to the default, blocking calls. + +.. code-block:: python + + try: + resp = iq.send() + # ... do stuff with expected Iq result + except IqError as e: + err_resp = e.iq + # ... handle error case + except IqTimeout: + # ... no response received in time + pass + +If you do not care to distinguish between errors and timeouts, then you +can combine both cases with a generic :exc:`~sleekxmpp.exceptions.XMPPError` +exception: + +.. code-block:: python + + try: + resp = iq.send() + except XMPPError: + # ... Don't care about the response + pass + +Advanced Use +------------ + +Going beyond the basics provided by SleekXMPP requires building at least a +rudimentary SleekXMPP plugin to create a :term:`stanza object` for +interfacting with the :class:`~sleekxmpp.stanza.iq.Iq` payload. + +.. seealso:: + + * :ref:`create-plugin` + * :ref:`work-with-stanzas` + * :ref:`using-handlers-matchers` + + +The typical way to respond to :class:`~sleekxmpp.stanza.iq.Iq` requests is +to register stream handlers. As an example, suppose we create a stanza class +named ``CustomXEP`` which uses the XML element ````, +and has a :attr:`~sleekxmpp.xmlstream.stanzabase.ElementBase.plugin_attrib` value +of ``custom_xep``. + +There are two types of incoming :class:`~sleekxmpp.stanza.iq.Iq` requests: +``get`` and ``set``. You can register a handler that will accept both and then +filter by type as needed, as so: + +.. code-block:: python + + self.register_handler(Callback( + 'CustomXEP Handler', + StanzaPath('iq/custom_xep'), + self._handle_custom_iq)) + + # ... + + def _handle_custom_iq(self, iq): + if iq['type'] == 'get': + # ... + pass + elif iq['type'] == 'set': + # ... + pass + else: + # ... This will capture error responses too + pass + +If you want to filter out query types beforehand, you can adjust the matching +filter by using ``@type=get`` or ``@type=set`` if you are using the recommended +:class:`~sleekxmpp.xmlstream.matcher.stanzapath.StanzaPath` matcher. + +.. code-block:: python + + self.register_handler(Callback( + 'CustomXEP Handler', + StanzaPath('iq@type=get/custom_xep'), + self._handle_custom_iq_get)) + + # ... + + def _handle_custom_iq_get(self, iq): + assert(iq['type'] == 'get') diff --git a/docs/getting_started/muc.rst b/docs/getting_started/muc.rst new file mode 100644 index 00000000..08f721f7 --- /dev/null +++ b/docs/getting_started/muc.rst @@ -0,0 +1,2 @@ +Mulit-User Chat (MUC) Bot +========================= diff --git a/docs/getting_started/presence.rst b/docs/getting_started/presence.rst new file mode 100644 index 00000000..e070e812 --- /dev/null +++ b/docs/getting_started/presence.rst @@ -0,0 +1,2 @@ +Manage Presence Subscriptions +============================= diff --git a/docs/getting_started/proxy.rst b/docs/getting_started/proxy.rst new file mode 100644 index 00000000..60d521c5 --- /dev/null +++ b/docs/getting_started/proxy.rst @@ -0,0 +1,42 @@ +.. _proxy: + +========================= +Enable HTTP Proxy Support +========================= + +.. note:: + + If you have any issues working through this quickstart guide + or the other tutorials here, please either send a message to the + `mailing list `_ + or join the chat room at `sleek@conference.jabber.org + `_. + +In some instances, you may wish to route XMPP traffic through +an HTTP proxy, probably to get around restrictive firewalls. +SleekXMPP provides support for basic HTTP proxying with DIGEST +authentication. + +Enabling proxy support is done in two steps. The first is to instruct SleekXMPP +to use a proxy, and the second is to configure the proxy details: + +.. code-block:: python + + xmpp = ClientXMPP(...) + xmpp.use_proxy = True + xmpp.proxy_config = { + 'host': 'proxy.example.com', + 'port': 5555, + 'username': 'example_user', + 'password': '******' + } + +The ``'username'`` and ``'password'`` fields are optional if the proxy does not +require authentication. + + +The Final Product +----------------- + +.. include:: ../../examples/proxy_echo_client.py + :literal: diff --git a/docs/getting_started/scheduler.rst b/docs/getting_started/scheduler.rst new file mode 100644 index 00000000..a9263a11 --- /dev/null +++ b/docs/getting_started/scheduler.rst @@ -0,0 +1,2 @@ +Send a Message Every 5 Minutes +============================== diff --git a/docs/getting_started/sendlogout.rst b/docs/getting_started/sendlogout.rst new file mode 100644 index 00000000..a1352db9 --- /dev/null +++ b/docs/getting_started/sendlogout.rst @@ -0,0 +1,94 @@ +Sign in, Send a Message, and Disconnect +======================================= + +.. note:: + + If you have any issues working through this quickstart guide + or the other tutorials here, please either send a message to the + `mailing list `_ + or join the chat room at `sleek@conference.jabber.org + `_. + +A common use case for SleekXMPP is to send one-off messages from +time to time. For example, one use case could be sending out a notice when +a shell script finishes a task. + +We will create our one-shot bot based on the pattern explained in :ref:`echobot`. To +start, we create a client class based on :class:`ClientXMPP ` and +register a handler for the :term:`session_start` event. We will also accept parameters +for the JID that will receive our message, and the string content of the message. + +.. code-block:: python + + import sleekxmpp + + + class SendMsgBot(sleekxmpp.ClientXMPP): + + def __init__(self, jid, password, recipient, msg): + super(SendMsgBot, self).__init__(jid, password) + + self.recipient = recipient + self.msg = msg + + self.add_event_handler('session_start', self.start) + + def start(self, event): + self.send_presence() + self.get_roster() + +Note that as in :ref:`echobot`, we need to include send an initial presence and request +the roster. Next, we want to send our message, and to do that we will use :meth:`send_message `. + +.. code-block:: python + + def start(self, event): + self.send_presence() + self.get_roster() + + self.send_message(mto=self.recipient, mbody=self.msg) + +Finally, we need to disconnect the client using :meth:`disconnect `. +Now, sent stanzas are placed in a queue to pass them to the send thread. If we were to call +:meth:`disconnect ` without any parameters, then it is possible +for the client to disconnect before the send queue is processed and the message is actually +sent on the wire. To ensure that our message is processed, we use +:meth:`disconnect(wait=True) `. + +.. code-block:: python + + def start(self, event): + self.send_presence() + self.get_roster() + + self.send_message(mto=self.recipient, mbody=self.msg) + + self.disconnect(wait=True) + +.. warning:: + + If you happen to be adding stanzas to the send queue faster than the send thread + can process them, then :meth:`disconnect(wait=True) ` + will block and not disconnect. + +Final Product +------------- + +.. compound:: + + The final step is to create a small runner script for initialising our ``SendMsgBot`` class and adding some + basic configuration options. By following the basic boilerplate pattern in :ref:`echobot`, we arrive + at the code below. To experiment with this example, you can use: + + .. code-block:: sh + + python send_client.py -d -j oneshot@example.com -t someone@example.net -m "This is a message" + + which will prompt for the password and then log in, send your message, and then disconnect. To test, open + your regular IM client with the account you wish to send messages to. When you run the ``send_client.py`` + example and instruct it to send your IM client account a message, you should receive the message you + gave. If the two JIDs you use also have a mutual presence subscription (they're on each other's buddy lists) + then you will also see the ``SendMsgBot`` client come online and then go offline. + +.. include:: ../../examples/send_client.py + :literal: -- cgit v1.2.3