-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (71 loc) · 2.87 KB
/
index.js
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
78
79
80
81
82
83
84
85
86
const { Client } = require("matrix-org-irc");
const mqtt = require("mqtt");
require('dotenv').config();
function updateIRCTopic(open) {
const client = new Client(process.env.IRC_SERVER_HOSTNAME, process.env.IRC_CLIENT_NICKNAME, {
port: Number(process.env.IRC_SERVER_PORT || 6697),
secure: true,
sasl: true,
userName: process.env.IRC_CLIENT_SASL_USERNAME,
password: process.env.IRC_CLIENT_SASL_PASSWORD,
realName: process.env.IRC_CLIENT_REALNAME,
channels: [process.env.IRC_TARGET_CHANNEL],
autoConnect: true,
debug: true
});
const IRC_TOPIC_MESSAGE_PATTERN = new RegExp(process.env.IRC_TOPIC_MESSAGE_PATTERN);
client.on("topic", async (channel, topic) => {
console.info(`Topic for ${channel} is "${topic}"`);
if (channel !== process.env.IRC_TARGET_CHANNEL) return;
let newTopic;
if (IRC_TOPIC_MESSAGE_PATTERN.test(topic)) {
newTopic = topic.replace(IRC_TOPIC_MESSAGE_PATTERN, open ? process.env.IRC_TOPIC_MESSAGE_OPEN : process.env.IRC_TOPIC_MESSAGE_CLOSED);
} else {
newTopic = `${topic} | ${open ? process.env.IRC_TOPIC_MESSAGE_OPEN : process.env.IRC_TOPIC_MESSAGE_CLOSED}`;
}
if (topic !== newTopic) {
console.info(`Setting topic to "${newTopic}"`);
await client.say("ChanServ", `TOPIC ${channel} ${newTopic}`);
} else {
client.disconnect();
}
});
// automatically disconnect after 1 minute in case something happens
setTimeout(() => { client.disconnect(); }, 60 * 1000);
}
const client = mqtt.connect(process.env.MQTT_URL, {
clientId: process.env.MQTT_CLIENT_ID,
will: {
topic: `heartbeat/${process.env.MQTT_CLIENT_ID}`,
payload: new Uint8Array([0]),
qos: 2,
retain: true,
},
});
client.on("connect", () => {
client.publish(`heartbeat/${process.env.MQTT_CLIENT_ID}`, new Uint8Array([1]), { qos: 2, retain: true }, (err) => {
if (err) console.error("Error publishing heartbeat", err);
});
client.subscribe("club/status", (err) => {
if (err) console.error("Error subscribing to club/status", err);
});
});
/**
* Will be null at the start resulting in ignoring the first status message.
* This is an object in case we want to implement stuff like the club status message.
* @type {{open: boolean}|null}
*/
let lastStatus = null;
client.on("message", (topic, message) => {
if (topic === "club/status") {
console.debug("Got club/status message");
const open = message.readUInt8(0) === 1;
console.log(`Space is ${open ? "open" : "closed"}`);
if (lastStatus && lastStatus.open !== open) {
console.info("Status changed, updating IRC topic");
updateIRCTopic(open);
}
lastStatus = { ...lastStatus, open };
}
});
console.info("Starting...");