-
Notifications
You must be signed in to change notification settings - Fork 42
/
master.js
242 lines (199 loc) · 5.98 KB
/
master.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
// Classes requires
const Filter = require("./classes/filter.js");
const Command = require("./classes/command.js");
const User = require("./classes/user.js");
const AwayFromKeyboard = require("./classes/afk.js");
const Banphrase = require("./classes/banphrase.js");
const Channel = require("./classes/channel.js");
const Reminder = require("./classes/reminder.js");
const ChatModule = require("./classes/chat-module.js");
// Singletons requires
const Logger = require("./singletons/logger.js");
const VLCConnector = require("./singletons/vlc-connector.js");
// Platform require
const Platform = require("./platforms/template.js");
const importFileDataModule = async (module, path) => {
if (!config.modules[path]) {
throw new Error(`Missing configuration for ${path}`);
}
const {
disableAll = true,
whitelist = [],
blacklist = []
} = config.modules[path];
if (whitelist.length > 0 && blacklist.length > 0) {
throw new Error(`Cannot combine blacklist and whitelist for ${path}`);
}
else if (disableAll) {
console.warn(`Module ${path} is disabled - will not load`);
return;
}
const identifier = (path === "gots") ? "name" : "Name";
const { definitions } = await import(`./${path}/index.mjs`);
if (blacklist.length > 0) {
await module.importData(definitions.filter(i => !blacklist.includes(i[identifier])));
}
else if (whitelist.length > 0) {
await module.importData(definitions.filter(i => whitelist.includes(i[identifier])));
}
else {
await module.importData(definitions);
}
};
let config;
try {
config = require("./config.json");
}
catch {
throw new Error("No custom configuration found! Copy `config-default.json` as `config.json` and set up your configuration");
}
const databaseModuleInitializeOrder = [
// First batch - no dependencies
[Filter, Command, User, AwayFromKeyboard, Banphrase, Channel, Reminder],
// Second batch - depends on Channel
[ChatModule]
];
const initializeCommands = async (config) => {
if (config.modules.commands.disableAll) {
console.warn("Load commands - skipped due to `disableAll` setting");
return;
}
console.time("Load commands");
const {
blacklist,
whitelist
} = config.modules.commands;
const { loadCommands } = await require("./commands/index.js");
const commands = await loadCommands({
blacklist,
whitelist
});
await Command.importData(commands.definitions);
console.timeEnd("Load commands");
};
(async () => {
const platformsConfig = config.platforms;
if (!platformsConfig || platformsConfig.length === 0) {
console.warn("No platforms configured! Supibot will now exit.");
process.exit(0);
}
console.groupCollapsed("Initialize timers");
console.time("supi-core");
const core = await import("supi-core");
const Query = new core.Query({
user: process.env.MARIA_USER,
password: process.env.MARIA_PASSWORD,
host: process.env.MARIA_HOST,
connectionLimit: process.env.MARIA_CONNECTION_LIMIT
});
globalThis.sb = {
Date: core.Date,
Error: core.Error,
Promise: core.Promise,
Got: core.Got,
Query,
Cache: new core.Cache(process.env.REDIS_CONFIGURATION),
Metrics: new core.Metrics(),
Utils: new core.Utils()
};
console.timeEnd("supi-core");
const platforms = new Set();
for (const definition of platformsConfig) {
const platform = Platform.create(definition.type, definition);
if (platform) {
platforms.add(platform);
}
}
console.time("basic bot modules");
// Initialize bot-specific modules with database-driven data
for (let i = 0; i < databaseModuleInitializeOrder.length; i++) {
console.debug(`Modules batch #${i + 1}`);
const initOrder = databaseModuleInitializeOrder[i];
const promises = initOrder.map(async (module) => {
console.time(`Init ${module.name}`);
await module.initialize();
console.timeEnd(`Init ${module.name}`);
});
if (i === 0) {
await Promise.all([...promises, initializeCommands(config)]);
}
else {
await Promise.all(promises);
}
}
globalThis.sb = {
...sb,
Platform,
Filter,
Command,
User,
AwayFromKeyboard,
Banphrase,
Channel,
Reminder,
ChatModule,
Logger: new Logger(),
VideoLANConnector: VLCConnector.initialize(), // @todo move code from `initialize` here
API: require("./api")
};
console.timeEnd("basic bot modules");
console.time("chat modules");
await Promise.all([
importFileDataModule(ChatModule, "chat-modules"), importFileDataModule(sb.Got, "gots")
]);
console.timeEnd("chat modules");
console.time("crons");
const { initializeCrons } = await import("./crons/index.mjs");
initializeCrons(config.modules.crons);
console.timeEnd("crons");
if (sb.Metrics) {
sb.Metrics.registerCounter({
name: "supibot_messages_sent_total",
help: "Total number of Twitch messages sent by the bot.",
labelNames: ["platform", "channel"]
});
sb.Metrics.registerCounter({
name: "supibot_messages_read_total",
help: "Total number of Twitch messages seen (read) by the bot.",
labelNames: ["platform", "channel"]
});
}
const promises = [];
for (const platform of platforms) {
if (!platform.active) {
console.debug(`Platform ${platform.name} (ID ${platform.ID}) is set to inactive, not connecting`);
continue;
}
platform.checkConfig();
promises.push((async () => {
console.time(`Platform connect: ${platform.name}`);
await platform.connect();
console.timeEnd(`Platform connect: ${platform.name}`);
})());
}
if (promises.length === 0) {
console.warn("No platforms were successfully activated, bot will not connect to any chat service");
}
await Promise.all(promises);
console.debug("Ready!");
console.groupEnd();
process.on("unhandledRejection", async (reason) => {
if (!(reason instanceof Error)) {
return;
}
const origin = (reason.message?.includes("RequestError: Timeout awaiting 'request'"))
? "External"
: "Internal";
try {
await sb.Logger.logError("Backend", reason, {
origin,
context: {
cause: "UnhandledPromiseRejection"
}
});
}
catch (e) {
console.warn("Rejected the promise of promise rejection handler", { reason, e });
}
});
})();