forked from LakeYS/Discord-Trivia-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
283 lines (241 loc) · 8.86 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
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
const pjson = require("./package.json");
const fs = require("fs");
const { ShardingManager } = require("discord.js");
process.title = `TriviaBot ${pjson.version}`;
// # Art Display # //
// process.stdout.columns returns "undefined" in certain situations
var strArray = [ `\x1b[7m TriviaBot Version ${pjson.version} `,
"\x1b[7m Copyright (c) 2018-2020 Lake Y \x1b[0m",
"\x1b[7m https://lakeys.net \x1b[0m" ];
// Adjust length of the first line
strArray[0] = strArray[0].padEnd(31," ") + "\x1b[0m";
var strSide = ["", "", ""];
var strBottom = "";
if(process.stdout.columns > 61) {
strSide = strArray;
}
else {
strBottom = `\n${strArray[0]}\n${strArray[1]}\n${strArray[2]}`;
}
// See here for an example of how this looks when the application is running:
// http://lakeys.net/triviabot/console.png
console.log(`\
########
##################
### ####### ###
### ############### ###
### #################### ###
### ######### ######## ###
### ######## ######## ###
### ##### ######## ###
### ########## ### ${strSide[0]}
### ########### ### ${strSide[1]}
### ######### ### ${strSide[2]}
### ######## ###
### ###### ###
### #### ###
### ###### ###
### ####### ###
##### #### #####
############
######${strBottom}`);
// # Initialize Config Args # //
var configFile;
for(var i = 0; i <= process.argv.length; i++) {
if(typeof process.argv[i] !== "undefined" && process.argv[i].startsWith("--configfile=")) {
configFile = process.argv[i].replace("--configfile=", "");
}
}
var Config = require("./lib/config.js")(configFile, true).config;
// # Requirements/Init # //
const configPrivate = {
githubAuthor: "LakeYS",
githubName: "Discord-Trivia-Bot"
};
require("./lib/init.js")(pjson, Config, configPrivate);
if(Config["allow-eval"] === true) {
process.stdin.resume();
process.stdin.setEncoding("utf8");
}
// # Discord # //
var token = Config.token;
const manager = new ShardingManager(`${__dirname}/shard.js`, {
totalShards: Config["shard-count"],
token,
shardArgs: [configFile]
});
// # Custom Package Loading # //
if(typeof Config["additional-packages-root"] !== "undefined") {
Config["additional-packages-root"].forEach((key) => {
require(key)(Config, manager);
});
}
// # Stats # //
var stats;
try {
stats = JSON.parse(fs.readFileSync(Config["stat-file"]));
} catch(error) {
if(typeof error.code !== "undefined" && error.code === "ENOENT") {
console.warn("No stats file found; one will be created.");
}
else {
// If an error occurs, don't overwrite the old stats.
Config["stat-file"] = Config["stat-file"] + ".1";
stats = {};
console.log(`Failed to load stats file, stats will be saved to ${Config["stat-file"]}. Received error:\n${error}`);
}
}
// # File Handling # //
// ## refreshGameExports() ##
// Renames all exported game files to match their corresponding shards.
// The files will be renamed, merged, and split where necessary.
// This must be called before importing if the shard count has changed, or games will NOT import.
// WARNING: There MUST be a complete sequence of exported files; if a number is skipped, this
// will not work properly.
function refreshGameExports() {
var i = 0;
var gameExports = {};
var games;
while(fs.existsSync("./game." + i + ".json.bak")) {
try {
games = JSON.parse(fs.readFileSync("./game." + i + ".json.bak"));
} catch(error) {
console.log(`refreshGameExports - Failed to import file for shard ${i}: ${error.message}`);
i++;
continue;
}
var shardId;
// We only need to sample one guild ID in the file to determine its corresponding shard.
if(typeof Object.values(games)[0] !== "undefined") {
if(manager.totalShards === "auto") {
console.error("ERROR: manager.totalShards must be a number in order to import properly.");
return;
}
// We'll use Discord's sharding formula to determine the corresponding shard.
shardId = parseInt((Object.values(games)[0].guildId/2**22) % manager.totalShards);
if(isNaN(shardId)) {
console.error(`ERROR: Shard ID (${Object.values(games)[0].guildId/2**22} % ${manager.totalShards}) is NaN, defaulting to ${i}`);
shardId = i;
}
console.log(`Contents of file "game.${i}.json.bak" belong to shard ${shardId}`);
}
else {
shardId = i;
console.log(`Contents of file "game.${i}.json.bak" are empty, defaulting to shard ${i}`);
}
// Initialize the shard in preparation for exporting
gameExports[shardId] = gameExports[shardId] || {};
// Define the old shard if it does not exist yet.
gameExports[i] = gameExports[i] || {};
Object.keys(games).forEach((key) => {
gameExports[shardId][key] = games[key];
});
i++;
}
// Now, we re-export the data.
Object.keys(gameExports).forEach((key) => {
var file = "./game." + key + ".json.bak";
try {
fs.writeFileSync(file, JSON.stringify(gameExports[key], null, "\t"), "utf8");
console.log(`Exported ${Object.keys(gameExports[key]).length} game(s) to ${file}`);
}
catch(err) {
console.error(`Failed to rewrite to game.json.bak with the following err:\n ${err}`);
}
});
}
// # ShardingManager # //
manager.spawn()
.catch((err) => {
var warning = "";
if(err.message.includes("401 Unauthorized")) {
if(token === "yourtokenhere") {
warning = "\nIt appears that you have not yet added a token. Please replace \"yourtokenhere\" with a valid token in the config file.";
}
else {
warning += "\nPlease double-check your token and try again.";
if(token.length < 50) {
warning = "\nIt appears that you have entered a client secret or other invalid string. Please ensure that you have entered a token and try again.";
}
}
}
console.error(`Discord client login failed - ${err}${warning}`);
process.exit();
});
manager.on("launch", (shard) => {
console.log(`Successfully launched shard ${shard.id} of ${manager.totalShards-1}`);
if(shard.id === 0) {
// Refresh exports before the first shard spawns.
// This is done on launch because it requires totalShards to be a number.
refreshGameExports();
}
// TODO: Rate limit this to prevent API flooding
shard.on("death", (process) => {
console.error("Shard " + shard.id + " closed unexpectedly! PID: " + process.pid + "; Exit code: " + process.exitCode + ".");
if(process.exitCode === null)
{
console.warn("WARNING: Shard " + shard.id + " exited with NULL error code. This may be a result of a lack of available system memory. Ensure that there is enough memory allocated to continue.");
}
});
shard.on("disconnect", (event) => {
console.warn("Shard " + shard.id + " disconnected. Dumping socket close event...");
console.log(event);
});
//shard.on("reconnecting", () => {
// console.warn("Shard " + shard.id + " is reconnecting...");
//});
});
// ## Manager Messages ## //
manager.on("message", (shard, input) => {
if(typeof input.evalStr !== "undefined") {
// Eval
eval(input.evalStr);
}
else if(typeof input.stats !== "undefined") {
// Update stats
// Example: client.shard.send({stats: { test: 123 }});
if(Config["fallback-mode"] !== true) {
Object.keys(input.stats).forEach((stat) => {
stats = stats || {};
if(typeof stats[stat] !== "number") {
// This stat doesn't exist, initialize it.
stats[stat] = input.stats[stat];
}
else {
// Increase the stat
stats[stat] += input.stats[stat];
}
});
fs.writeFile(Config["stat-file"], JSON.stringify(stats, null, "\t"), "utf8", (err) => {
if(err) {
console.error(`Failed to save stats.json with the following err:\n${err}\nMake sure stats.json is not read-only or missing.`);
}
});
}
}
});
// # Console Functions # //
const evalCmds = require("./lib/eval_cmds.js")(manager);
manager.eCmds = evalCmds;
if(Config["allow-eval"] === true) {
process.stdin.on("data", (text) => {
// Cut newlines, split the command by spaces to represent arguments.
var cmdFull = text.replace("\r","").replace("\n","").split(" ");
var cmdFunction = cmdFull[0];
if(typeof evalCmds[cmdFunction] === "function") {
// Remove the first word (the command itself) before pasing it
cmdFull.shift(1);
// Execute the command with any further parameters as an array
evalCmds[cmdFunction](cmdFull);
}
else {
console.log("Eval:");
try {
eval(text.toString());
}
catch(err) {
console.log(err);
}
}
});
}