The following example creates a very simple bot which reacts to incoming messages with a simple “Hello World”. The main class to use is the Client class. However, the bot’s source code as shown below is not complete. In recent versions of gloox you have to install a ConnectionListener and reimplement at least the virtual onTLSConnect() if you want to connect to TLS-enabled servers. This is because gloox presents the result of the remote server’s TLS certificate verification and drops the connection if the cert info is not approved. Check the API docs on ConnectionListener for more info. The code below is based on the gloox 1.0 API.
Compiling examples can be found in the src/examples/ directory in the source distribution.
Derive an object from MessageHandler and register it with the Client:
#include <gloox/client.h> #include <gloox/messagehandler.h> using namespace gloox; class Bot : public MessageHandler { public: Bot() { JID jid( "bot@server/resource" ); j = new Client( jid, "password" ); j->registerMessageHandler( this ); j->connect(); }
Note: connect() without parameter blocks for the duration of the connection. To not block, call connect( false ). Everything within gloox is event driven.
Re-implement the virtual handleMessage():
virtual void handleMessage( const Message& stanza, MessageSession* session = 0 ) { Message msg( stanza.from(), "hello world" ); j->send( msg ); } private: Client* j; };
Now use your shiny little Jabber/XMPP client:
int main( int argc, char* argv[] ) { Bot b; }
This bot answers to any message sent to it, regardless of content or sender. It is important to register the *Handler-derived objects with the Client to receive events.