Openfire Bot / Listener Plugin Tutorial

If you want to create an openfire plugin which is listening for some packets / messages and should react based on message content e.g. Bot. In my example plugin I want to listen for a message which contains packet extensions and parse the data from XML.

The message looks like:

1
2
3
4
5
<message id="ri1KL-7" to="username@servername.com" type="chat">
<body>Hello World :)</body>
<BotCommand xmlns="https://rmsol.de"><action>google</action>
<data>Openfire Bot Plugin</data></BotCommand>
</message>

And the Openfire Plugin code to log the data looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package org.jivesoftware.openfire.plugin.rest;

import java.io.File;

import org.dom4j.Element;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import org.jivesoftware.openfire.interceptor.InterceptorManager;
import org.jivesoftware.openfire.interceptor.PacketInterceptor;
import org.jivesoftware.openfire.interceptor.PacketRejectedException;
import org.jivesoftware.openfire.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import org.xmpp.packet.PacketExtension;

public class BotPlugin implements Plugin, PacketInterceptor {

private static Logger LOG = LoggerFactory.getLogger(BotPlugin.class);
private InterceptorManager interceptorManager;

public void initializePlugin(PluginManager manager, File pluginDirectory) {
// Add packet interceptor
interceptorManager = InterceptorManager.getInstance();
interceptorManager.addInterceptor(this);
}

@Override
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException {
// Skip already processed packets
if (processed) {
return;
}

if (packet instanceof Message) {
PacketExtension extension = packet.getExtension("BotCommand", "https://rmsol.de");
if (extension != null) {
Element rootElement = extension.getElement();

Element action = rootElement.element("action");
if (action != null) {
LOG.info("action value: " + action.getStringValue());
}

Element data = rootElement.element("data");
if (data != null) {
LOG.info("data value: " + data.getStringValue());
}
}
}
}

@Override
public void destroyPlugin() {
// Remove the interceptor if the plugin will be destroyed/removed
interceptorManager.removeInterceptor(this);
}
}