Skip to content

Basic documentation

CyrilPeponnet edited this page Sep 23, 2014 · 2 revisions

Basic

This documents topic is for people who want to quickly try xmpppy for a simple task, like writing a command-line script for sending a single message.

Writing a simple script

This example demonstrates a simple script that sends message to one recipient.

Example: xsend [email protected] Hello there!

First - we declare ourself as a python script and importing needed modules:

#!/usr/bin/python
import sys,os,xmpp

Check if we have enough arguments on the command-line:

if len(sys.argv) < 2:
    print "Syntax: xsend JID text"
    sys.exit(0)

Decode arguments. Omitting all checks to simplify our script:

tojid=sys.argv[1]
text=' '.join(sys.argv[2:])

Get our Jabber ID and login details. Presuming that all info stored in ~/.xsend file:

jidparams={}
if os.access(os.environ['HOME']+'/.xsend',os.R_OK):
    for ln in open(os.environ['HOME']+'/.xsend').readlines():
        key,val=ln.strip().split('=',1)
        jidparams[key.lower()]=val
for mandatory in ['jid','password']:
    if mandatory not in jidparams.keys():
        open(os.environ['HOME']+'/.xsend','w').write('#[email protected]\n#PASSWORD=juliet\n')
        print 'Please ensure the ~/.xsend file has valid JID for sending messages.'
        sys.exit(0)

From now on we have to:

  • connect to jabber server
  • authenticate ourselves
  • submit a message

Calculating our server name and creating Client class instance for it:

jid=xmpp.protocol.JID(jidparams['jid'])
cl=xmpp.Client(jid.getDomain(),debug=[])

Connect and authenticate with credentials from the config file.

cl.connect()
cl.auth(jid.getNode(),jidparams['password'])

Go online now (by sending the inital presence) and send a message now!

#cl.sendInitialPresence()
cl.send(xmpp.protocol.Message(tojid,text))

We're done! The session must now be closed but since we have not registered disconnect handler we will just leave it to python and TCP/IP layer. All jabber servers that I know handle such disconnects correctly.

You can see the final script from here xsend.py