forked from manix84/discord_gmod_bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.js
345 lines (323 loc) · 8.91 KB
/
web.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
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
require('dotenv-flow').config({
silent: true
});
const Discord = require('discord.js');
const http = require('http');
const https = require('https');
const chalk = require('chalk');
const packageData = require('./package');
const VERSION = String(packageData.version);
const DEBUG = Boolean(process.env.DEBUG == 1);
const PORT = Number(process.env.PORT) || 37405; //unused port and since now the OFFICIAL ttt_discord_bot port ;)
const DISCORD_GUILD = String(process.env.DISCORD_GUILD);
const DISCORD_CHANNEL = String(process.env.DISCORD_CHANNEL);
const DISCORD_TOKEN = String(process.env.DISCORD_TOKEN);
const KEEPALIVE_HOST = String(process.env.KEEPALIVE_HOST);
const KEEPALIVE_PORT = Number(process.env.KEEPALIVE_PORT) || PORT;
const KEEPALIVE_ENABLED = Boolean(process.env.KEEPALIVE_ENABLED == 1);
const API_KEY = String(process.env.API_KEY) || false;
// Secure logging (for initial log of information)
const slog = (...msgs) => {
if (!DEBUG) return;
console.log(chalk.blue(...msgs));
}
// Regular logging (for requests/responses)
const log = (...msgs) => {
if (!DEBUG) return;
console.log(...msgs.map((m) => {
if (typeof m === 'string') {
return m.replace(API_KEY, "API_KEY_OBFUSCATED");
}
return m;
}));
};
const error = (...msgs) => console.error(chalk.red(...msgs));
const br = newLine = () => console.log();
slog('Constants: ');
slog(` VERSION: ${chalk.bold(VERSION)} (${typeof VERSION})`);
slog(` DEBUG: ${chalk.bold(DEBUG)} (${typeof DEBUG})`);
slog(` PORT: ${chalk.bold(PORT)} (${typeof PORT})`);
slog(` DISCORD_GUILD: ${chalk.bold(DISCORD_GUILD)} (${typeof DISCORD_GUILD})`);
slog(` DISCORD_CHANNEL: ${chalk.bold(DISCORD_CHANNEL)} (${typeof DISCORD_CHANNEL})`);
slog(` DISCORD_TOKEN: ${chalk.bold(DISCORD_TOKEN)} (${typeof DISCORD_TOKEN})`);
slog(` KEEPALIVE_HOST: ${chalk.bold(KEEPALIVE_HOST)} (${typeof KEEPALIVE_HOST})`);
slog(` KEEPALIVE_PORT: ${chalk.bold(KEEPALIVE_PORT)} (${typeof KEEPALIVE_PORT})`);
slog(` KEEPALIVE_ENABLED: ${chalk.bold(KEEPALIVE_ENABLED)} (${typeof KEEPALIVE_ENABLED})`);
slog(` API_KEY: ${chalk.bold(API_KEY)} (${typeof API_KEY})`);
br(); // New Line
let discordGuild;
const requests = [];
//create discord client
const bot = new Discord.Client();
bot.login(DISCORD_TOKEN);
let isBotReady = false;
bot.on('ready', () => {
bot.guilds.fetch(DISCORD_GUILD).then(data => {
discordGuild = data;
isBotReady = true;
log(chalk.green('Bot is ready to mute them all! :)'));
br();
});
});
bot.on('error', (err) => {
error(err)
})
bot.on('voiceStateUpdate', (oldState, newState) => {
if (newState.channelID !== oldState.channelID) {
if (newState.channelID === null) {
log(chalk.yellow(`${oldState.member.displayName} (${oldState.member.id}) left voice channels.`));
}
else {
log(chalk.yellow(`${newState.member.displayName} (${newState.member.id}) joined "${newState.channel.name}" (${newState.channel.id})${(newState.channelID === DISCORD_CHANNEL) ? ' [Muter Channel]' : ''}.`));
}
}
});
requests['connect'] = (params, ret) => {
let tag_utf8 = params.tag.split(" ");
let tag = "";
tag_utf8.forEach((char) => {
tag = tag + String.fromCharCode(char);
});
log(
"[Connect][Requesting]",
`Searching for "${tag}" (utf8: "${params.tag}")`
);
const found = discordGuild.members.cache.find(user =>
(user.id === tag || user.displayName.match(new RegExp(`.*${tag}.*`))) || false
);
if (!found) {
ret({
answer: 0 //no found
});
error(
"[Connect][Error]",
`0 users found with tag "${tag}".`
);
} else {
ret({
tag: found.displayName,
id: found.id
});
log(chalk.green(
"[Connect][Success]",
`Connecting ${found.displayName} (${found.id})`
));
}
};
requests['mute'] = (params, ret) => {
let id = params.id;
let mute = params.mute;
if (typeof id !== 'string' || typeof mute !== 'boolean') {
ret({
success: false,
error: "ID or Mute value missing", //legacy
errorMsg: "ID or Mute value missing",
errorId: "INVALID_PARAMS"
});
error(
"[Mute][Missing Params]",
`id: "${id}" (${typeof id}),`,
`mute: "${mute}" (${typeof mute})`
);
return;
}
log(
"[Mute][Requesting]",
params
);
discordGuild.members.fetch(id)
.then((member) => {
if (!member.voice.serverMute && mute) {
member.voice.setMute(true, "dead players can't talk!").then(() => {
ret({
success: true
});
log(
"[Mute][Discord:SetMute][Success]",
`Muted ${id}`
);
}).catch((err) => {
ret({
success: false,
error: err, //Legacy
errorMsg: err,
errorId: "DISCORD_ERROR"
});
error(
"[Mute][Discord:SetMute][Error]",
`Mute: ${id} - ${err}`
);
});
}
if (member.voice.serverMute && !mute) {
member.voice.setMute(false).then(() => {
ret({
success: true
});
log(
"[Mute][Discord:SetMute][Success]",
`Unmuted ${id}`
);
}).catch((err) => {
ret({
success: false,
error: err, //Legacy
errorMsg: err,
errorId: "DISCORD_ERROR"
});
error(
"[Mute][Discord:SetMute][Error]",
`Unmute: ${id} - ${err}`
);
});
}
})
.catch((err) => {
ret({
success: false,
error: "member not in voice channel", //legacy
errorMsg: "member not in voice channel",
errorId: "DISCORD_MEMBER_NOT_IN_CHANNEL"
});
error(
"[Mute][Error]",
err
);
});
};
requests['keep_alive'] = (params, ret) => {
ret({
success: true,
});
log(
"[KeepAlive][Request]",
params
);
};
requests['sync'] = (params, ret) => {
ret({
success: true,
version: VERSION,
debugMode: DEBUG,
discordGuild: DISCORD_GUILD,
discordChannel: DISCORD_CHANNEL
});
log(
"[Sync][Request]",
params
);
};
const keepAliveReq = () => {
const options = {
host: KEEPALIVE_HOST,
port: KEEPALIVE_PORT,
path: '/keep_alive',
headers: {
req: 'keep_alive',
params: '{}',
authorization: `Basic ${API_KEY}`
},
timeout: 5 * 1000 // 5 second request timeout.
};
log(
"[KeepAlive][Requesting]",
options
);
https.get(options, (res) => {
const { statusCode } = res;
if (statusCode === 200) {
log(
"[KeepAlive][Success]",
`Request successful`
);
} else {
error(
"[KeepAlive][Error]",
`Request Failed Status Code: ${statusCode}`
);
}
});
};
http.createServer((req, res) => {
if (!isBotReady) {
error('bot still loading');
return;
}
if (
typeof req.headers.params === 'string' &&
typeof req.headers.req === 'string' &&
typeof requests[req.headers.req] === 'function' &&
typeof API_KEY === 'string' && req.headers.authorization === `Basic ${API_KEY}`
) {
try {
let params = JSON.parse(req.headers.params);
requests[req.headers.req](
params,
(ret) => res.end(
JSON.stringify(ret)
)
);
} catch (err) {
res.end(err.msg);
error(
"[ERROR][Request]",
err
);
error(
"[ERROR][Request Headers]",
JSON.stringify(req.headers)
)
}
} else {
error(
"[ERROR][Request Headers]",
req.headers
)
if (typeof API_KEY === 'string' && req.headers.authorization !== `Basic ${API_KEY}`) {
res.writeHead(401);
res.end(JSON.stringify({
error: "Authorisation Miss-Match", //Legacy
errorMsg: "Authorisation Miss-Match",
errorId: "AUTHORIZATION_MISSMATCH"
}));
error(
"[ERROR][Authorisation]",
`"${req.headers.authorization}" !== "Basic ${API_KEY}"`
);
} else if (requests[req.headers.req] !== 'function') {
res.writeHead(400);
res.end(JSON.stringify({
error: `Unknown request "${req.headers.req}"`, //Legacy
errorMsg: `Unknown request "${req.headers.req}"`,
errorId: "UNKNOWN_REQUEST"
}));
error(
"[ERROR][Request]",
`Unknown request "${req.headers.req}"`
);
} else {
res.writeHead(400);
res.end(JSON.stringify({
error: `Unknown`, //Legacy
errorMsg: `Unknown`,
errorId: "UNKNOWN_ERROR"
}));
error(
"[ERROR][Request]",
`Unknown request "${req.headers.req}"`
);
}
}
}).listen({
port: PORT
}, () => {
log(chalk.green(`Bot endpoint is running: https://${KEEPALIVE_HOST}:${KEEPALIVE_PORT || PORT}`));
if (KEEPALIVE_ENABLED) {
log(
"[KeepAlive][Startup]",
`Initialisation`
);
setInterval(keepAliveReq, 20 * 60 * 1000); // load every 20 minutes
setTimeout(keepAliveReq, 3 * 1000); // load first attempt after 3 seconds.
}
});