xmpp.js
1.66 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const xmpp = require("simple-xmpp");
const strftime = require("strftime");
const config = require("./config");
const logger = require("./logger");
const core = require("./core");
const messageTail = require("./message-tail");
logger.verbose("Initializing xmpp bot");
logger.info("Connecting to xmpp server", {jabber_id: config.jabber_id});
function onOnline(data) {
logger.info("XMPP connected", {data: data});
xmpp.getRoster();
core.onOnline();
}
xmpp.on("online", onOnline);
function onError(err) {
logger.warn('XMPP error', {err: err});
setTimeout(function() {
process.exit(1);
}, 5000)
}
xmpp.on("error", onError);
function onSubscribe(from) {
logger.info('Receive subscription request from ' + from);
xmpp.acceptSubscription(from);
logger.info('Subscribe back ' + from);
xmpp.subscribe(from);
}
xmpp.on('subscribe', onSubscribe);
function onChat(from, msg) {
logger.info('Incoming XMPP message', {from: from, msg: msg});
messageTail.add({
ts: strftime('%F %T'),
direction: 'in',
partner: from,
msg: msg
});
core.onMessage(from, msg);
}
xmpp.on('chat', onChat);
function connect() {
xmpp.connect({
jid: config.jabber_id,
password: config.jabber_password
});
}
connect();
function sendMessage(to, msg) {
logger.info("Sending XMPP message", {to: to, msg: msg});
messageTail.add({
ts: strftime('%F %T'),
direction: 'out',
partner: to,
msg: msg
});
try {
xmpp.send(to, msg);
}
catch(e) {
logger.warn('Exception on sending XMPP message', {err: e});
}
}
exports.sendMessage = sendMessage;