Skip to content

Instantly share code, notes, and snippets.

@darrenparkinson
Created January 18, 2017 14:43
Show Gist options
  • Save darrenparkinson/1700a320428b071904e4d1cc26a6b566 to your computer and use it in GitHub Desktop.
Save darrenparkinson/1700a320428b071904e4d1cc26a6b566 to your computer and use it in GitHub Desktop.
Jabber BOT Demo using Node.js
'use strict'
const Client = require('node-xmpp-client');
const ltx = require('node-xmpp-core').ltx;
const bunyan = require('bunyan');
const log = bunyan.createLogger({ name: 'jabber-bot' });
const weather = require('./weather');
const tube = require('./tube');
const jabberpassword = process.env.jabberPassword || "";
if (jabberpassword == "") {
log.error('Password not set');
process.exit(0);
}
let client = new Client({
host: 'cup.yourdomain.com',
jid: 'bot@yourdomain.com',
password: jabberpassword
})
client.on('online', function (data) {
log.info(`Online. Connected as ${data.jid.user}@${data.jid.domain}/${data.jid.resource}`)
log.info('Sending Presence');
client.send('<presence/>'); // Important to show as online and respond to chats.
})
client.on('offline', function () {
log.info("Client is Offline");
})
client.on('stanza', function (stanza) {
log.info(`Incoming Stanza: ${stanza.attrs.type}`);
// *** Look at ltx/lib/Element for a list of stanza functions
if (stanza.is('message') && stanza.attrs.type === 'chat' && !stanza.getChild('composing')) {
let msg = stanza.getChildText('body');
let reply = new Client.Stanza('message', {
to: stanza.attrs.from,
from: stanza.attrs.to,
type: 'chat'
})
if (msg) {
switch (msg.toLowerCase()) {
case 'sup':
case 'hello':
case 'hi':
case 'good afternoon':
reply.c('body').t('Hi there, how are you this fine day?');
client.send(reply);
break;
case 'weather':
weather.run("London").then(result => {
reply.c('body').t(result);
client.send(reply);
})
break;
case 'tube':
tube.run().then(result => {
reply.c('body').t(result);
client.send(reply);
})
break;
case 'away':
client.send(new ltx.Element('presence', {})
.c('show').t('away').up() // away
.c('status').t('Presence Status Updated Programmatically')
)
break;
case 'dnd':
client.send(new ltx.Element('presence', {})
.c('show').t('dnd').up() // dnd
.c('status').t('Really Busy')
)
break;
case 'reset':
client.send(new ltx.Element('presence', {})
.c('show').t('chat').up() // Available
.c('status').t('Available')
)
break;
default:
break;
}
}
}
})
client.on('connect', function () {
log.info("Client Connected");
})
client.on('reconnect', function () {
log.info("Client Reconnect");
})
client.on('disconnect', function (e) {
log.info(`Client is disconnected ${client.connection.reconnect} ${e}`);
})
client.on('error', function (e) {
log.error(e)
process.exit(1);
});
process.on('exit', function () {
client.end();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment