Skip to content

The simplest way to send an xmpp message

Fak3 edited this page Mar 30, 2012 · 2 revisions

The simple API

PyXMPP2, like the older PyXMPP, include the simple API providing the simplest possible way to do simple things. Currently it only provides a single message sending function. Good enough for some use cases.

To send a chat message from Bob's account to Alice just write:

from pyxmpp2.simple import send_message
send_message("[email protected]", "bob's password", "[email protected]", "Hello Alice")

It couldn't be easier.

Of course, there are some costs of this simplicity:

  • A connection is established and closed for each send_message call. That is not efficient for anything more than sending a single message.
  • The default settings are selected 'so it just works' in most cases. These are not the most efficient or most secure settings (e.g. no TLS certificate verification)
  • Non-unicode strings are automatically decoded to Unicode using the Python's guess for the right encoding. This can go wrong.

The (limited) flexibility

The settings may be tuned via the settings argument to the send_message function. This can be even used to automatically provide some command-line options:

#!/usr/bin/python

from pyxmpp2.simple import send_message
from pyxmpp2.settings import XMPPSettings

argparser = XMPPSettings.get_arg_parser(add_help = True)
settings = XMPPSettings()
settings.load_arguments(argparser.parse_args())
from pyxmpp2.simple import send_message
send_message("[email protected]", "bob's password", "[email protected]", "Hello Alice")

Such a script called with a --help option will show us:

usage: test.py [-h] [--starttls] [--tls-cacert-file TLS_CACERT_FILE]
               [--tls-require] [--ipv6] [--tls-verify-peer]
               [--c2s-port C2S_PORT] [--password PASSWORD] [--prefer-ipv6]
               [--server SERVER]

optional arguments:
  -h, --help            show this help message and exit
  --starttls, --no-starttls
                        Enable StartTLS negotiation (Default: False)
  --tls-cacert-file TLS_CACERT_FILE
                        TLS CA certificates file
  --tls-require, --no-tls-require
                        Require TLS stream encryption (Default: False)
  --ipv6, --no-ipv6     Allow IPv6 address lookup
  --tls-verify-peer, --no-tls-verify-peer
                        Verify the peer certificate (Default: True)
  --c2s-port C2S_PORT   Port number for XMPP client connections (Default:
                        5222)
  --password PASSWORD   User password
  --prefer-ipv6, --no-prefer-ipv6
                        Prefer IPv6 (Default: True)
  --server SERVER       Server address. (Default: use SRV lookup)