This repository was archived by the owner on Jan 2, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
177 lines (158 loc) · 4.65 KB
/
main.js
File metadata and controls
177 lines (158 loc) · 4.65 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import { connect } from "net";
import { Client, ActivityType, GatewayIntentBits } from "discord.js";
import { promises as fs } from "fs";
const DEBUG = false;
const MAX_SEND_ATTEMPTS = 5;
var online = false;
var population = 0;
var buffer = [];
async function getConfig() {
try {
const config_raw = await fs.readFile("config.json");
return JSON.parse(config_raw);
} catch (err) {
console.error("[ERROR] Could not read config file");
exit(1);
}
}
function getAddress(config) {
const ip = config.address;
if (ip.includes(":")) return ip;
return ip + ":8003";
}
function getStatusMessage() {
if (online) {
return `The server is currently **online** :white_check_mark: with **${population}** player${
population != 1 ? "s" : ""
}`;
} else {
return "The server is currently **offline** :no_entry:";
}
}
async function handleInteraction(interaction) {
const { commandName } = interaction;
if (commandName === "check") {
await interaction.reply(getStatusMessage());
}
}
function getListeningTo() {
if (!online) return "nothing";
return population + (population == 1 ? " player" : " players");
}
async function refreshStatus(client) {
const listeningTo = getListeningTo();
try {
await client.user.setActivity(listeningTo, {
type: ActivityType.Listening,
});
} catch (err) {
console.error(`[ERROR] Could not set activity: ${err}`);
}
}
async function login(config) {
const client = new Client({
intents: [GatewayIntentBits.Guilds],
});
client.on("ready", async () => {
await refreshStatus(client);
});
client.on("interactionCreate", handleInteraction);
await client.login(config.token);
return client;
}
async function main() {
const config = await getConfig();
const client = await login(config);
console.log("[INFO] Logged in as " + client.user.tag);
const addr = getAddress(config);
connectToMonitor(client, config, addr);
}
async function onDat(client, config, data) {
const tokens = data.toString().split("\n");
tokens.forEach((e) => {
if (e.length > 0) buffer.push(e);
});
if (buffer.includes("end")) await processBuffer(client, config);
}
async function onEnd(client, config, addr) {
online = false;
await refreshStatus(client);
setTimeout(() => connectToMonitor(client, config, addr), 5000);
}
function connectToMonitor(client, config, addr) {
const options = {
port: addr.split(":")[1],
host: addr.split(":")[0],
};
console.log("[INFO] Connecting to monitor at " + addr + "...");
const socket = connect(options, () => {
console.log("[INFO] Connected to monitor");
online = true;
});
socket.on("end", async () => {
console.log("[WARN] Lost connection to monitor");
onEnd(client, config, addr);
});
socket.on("data", async (data) => onDat(client, config, data));
socket.on("error", async () => onEnd(client, config, addr));
}
function printBuffer(buf) {
console.log("{");
for (let i = 0; i < buf.length; i++) console.log(buf[i]);
console.log("}");
}
async function sendMessage(client, config, message) {
let attempt = 0;
while (attempt < MAX_SEND_ATTEMPTS) {
try {
const channel = await client.channels.fetch(config.channel_id);
await channel.send(message);
return;
} catch (err) {
console.error(`[ERROR] Could not send message: ${err}`);
attempt++;
}
}
}
async function processBuffer(client, config) {
if (DEBUG) printBuffer(buffer);
if (buffer.includes("begin")) {
const queue = buffer.slice(
buffer.indexOf("begin") + 1,
buffer.indexOf("end")
);
population = 0;
for (let i = 0; i < queue.length; i++) {
const tokens = queue[i].split(" ");
switch (tokens[0]) {
case "player":
population++;
break;
case "chat":
const message = queue[i].substring(queue[i].indexOf(" ") + 1);
await sendMessage(client, config, message);
break;
case "email":
const head = queue[i].substring(queue[i].indexOf(" ") + 1);
let body = "\n```\n";
let j = 1;
for (; queue[i + j][0] == "\t"; j++)
body += queue[i + j].substring(1) + "\n";
body += "```";
await sendMessage(client, config, head + body);
if (!queue[i + j].includes("endemail"))
console.log("[WARN] Bad email (no endemail)");
i += j;
break;
default:
console.log(`[WARN] Unknown token: ${tokens[0]}`);
break;
}
}
await refreshStatus(client);
} else {
console.log("[WARN] Bad data (no begin token); ignoring");
}
buffer = buffer.slice(buffer.indexOf("end") + 1, buffer.length);
}
main();