-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sidecar.js
231 lines (199 loc) · 8.25 KB
/
sidecar.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
// _PLX[epic=Utilities] Sidecar Instance / Cronjobs
const isPRIME = process.env.PRIME;
const { Client } = require("eris");
const formatDistance = require("date-fns/formatDistance");
const { CronJob } = require("cron");
require("colors");
Promise = require("bluebird");
console.log("Sidecar Started".blue);
global.PLX = new Client(`Bot ${isPRIME ? cfg.token_prime : cfg.token}`, { restMode: true, intents: 0 });
PLX.cluster = { id: "-1", name: "[SIDECAR]" };
PLX.tempRoleTimers = new Map();
PLX.muteTimers = new Map();
PLX.reminderTimers = new Map();
const DBSchema = require("@polestar/database_schema");
const cfg = require("./config.json");
const WebhookDigester = require("./utils/WebhookDigester.js");
const debugHook = new WebhookDigester(PLX);
const dbConnectionData = {
hook: null,
url: process.env.NODE_ENV === "dev" ? cfg.dbURL_beta : cfg.dbURL,
options: {
useNewUrlParser: true,
keepAlive: 1,
connectTimeoutMS: 8000,
useUnifiedTopology: true,
poolSize: 100,
},
};
const Gearbox = require("./core/utilities/Gearbox");
Object.assign(global, Gearbox.Global);
Object.assign(PLX, Gearbox.Client);
require("@polestar/emoji-grimoire").initialize(PLX);
DBSchema(dbConnectionData).then((Connection) => {
global.DB = Connection;
// PLX.connect().then((_) => debugHook.info("Sidecar instance running")).catch(console.error);
});
//= =====================================================================================
//= =====================================================================================
//= =====================================================================================
//= =====================================================================================
//= =====================================================================================
console.log("• ".blue, "Loading CRON subroutines...");
const MIDNIGHT = new CronJob("0 0 * * *", () => {
//= =====================================================================================
/* EVERY MIDNIGHT */
//= =====================================================================================
}, null, true);
const FIVEminute = new CronJob("*/5 * * * *", async () => {
}, null, true);
const FIFTEENminute = new CronJob("*/1 * * * *", async () => {
delete require.cache[require.resolve("./core/subroutines/feeds")];
const feeds = require("./core/subroutines/feeds");
feeds.check();
});
const ONEminute = new CronJob("*/1 * * * *", async () => {
console.log(`
${"[SIDECAR]".blue} - Uptime: ${formatDistance(PLX.uptime, 0)}
`);
//= =====================================================================================
/* EVERY 1 MINUTE */
//= =====================================================================================
DB.temproles.find({ expires: { $lte: Date.now() + 75e3 } }).lean().exec()
.then((temps) => {
temps.forEach((tprl) => {
DB.servers.get(tprl.server).then(async (/* svData */) => {
if (PLX.tempRoleTimers.has(tprl._id)) return;
PLX.tempRoleTimers.set(
tprl._id,
setTimeout(async () => {
PLX.tempRoleTimers.delete(tprl._id); // We don't need to cache expired Timeouts
const [logSERVER, logMEMBER] = await Promise.all([
PLX.getRESTGuild(tprl.server),
PLX.resolveMember(tprl.server, tprl.user),
]).catch(async () => {
await DB.temproles.remove({ _id: tprl._id });
});
if (!logSERVER || !logMEMBER) return;
await DB.temproles.expire({ U: tprl.user, S: tprl.server });
await PLX.removeGuildMemberRole(tprl.server, tprl.user, tprl.role, "Temporary Role").catch(() => "Die Silently");
/*
if (svData.dDATA || svData.logging) {
return;
// delete require.cache[require.resolve('./modules/dev/logs_infra.js')]
const log = require("./modules/dev/logs_infra.js");
log.init({
bot,
server: logSERVER,
member: logMEMBER,
user: logUSER,
logtype: "usrUnmute",
});
}
*/
}, tprl.expires - Date.now()),
);
});
});
});
/* Manage Reminders */ //= ===============================
processReminders();
// setTimeout(() => processReminders(), 30e3);
/* Manage Mutes */ //= ===============================
DB.mutes.find({ expires: { $lte: Date.now() + 75e3 } })
.then((mutes) => {
[...new Set(mutes.map((m) => m.server))].forEach((muteSv) => {
DB.servers.get(muteSv).then((svData) => {
mutes.filter((mut) => mut.server === muteSv).forEach(async (mtu) => {
if (PLX.muteTimers.has(mtu._id)) return;
PLX.muteTimers.set(
mtu._id,
setTimeout(async () => {
PLX.muteTimers.delete(mtu._id);
// DB.mutes.expire(Date.now());
const logSERVER = await PLX.getRESTGuild(mtu.server);
if (svData.modules.MUTEROLE) {
PLX.removeGuildMemberRole(svData.id, mtu.user, svData.modules.MUTEROLE, "Mute Expired").catch(() => "Die Silently")
.then(() => mtu.delete())
.catch(() => mtu.delete());
} else {
return mtu.delete();
}
// activity logs stuff (LEGACY CODE)
return undefined;
/*
const logUSER = await PLX.resolveUser(mtu.user);
if (!logSERVER || !logUSER) return;
const logMEMBER = logSERVER.member(logUSER);
if (!logMEMBER) return;
if (svData.dDATA || svData.logging) {
return;
// delete require.cache[require.resolve('./modules/dev/logs_infra.js')]
const log = require("./modules/dev/logs_infra.js");
log.init({
bot,
server: logSERVER,
member: logMEMBER,
user: logUSER,
logtype: "usrUnmute",
});
}
*/
}, mtu.expires - Date.now()),
);
});
});
});
});
/* Exchange Currency */ //= ===============================
/*
discoin.fetch().then(async trades => {
trades = JSON.parse(trades)
if (!trades.length || trades.length === 0) return;
await wait(Number(process.env.SHARD) * 2);
Promise.all(trades.map(td => resolveExchange(td, bot)));
});
*/
// ---CRON END----///-----////------/////
}, null, true);
MIDNIGHT.start();
FIVEminute.start();
ONEminute.start();
FIFTEENminute.start();
console.log("• ".green, "CRONs ready");
function processReminders() {
DB.feed.find({ expires: { $lte: Date.now() + 45e3 } }).limit(50).lean()
.then((reminders) => {
console.log({ reminders });
reminders.forEach(async (rem) => {
console.log(rem);
if (PLX.reminderTimers.has(rem._id)) return;
PLX.reminderTimers.set(
rem._id,
setTimeout(async () => {
PLX.reminderTimers.delete(rem._id);
try {
// url = userID
const destChannel = (await PLX.getRESTChannel(rem.channel).catch(() => null)) || (await PLX.getDMChannel(rem.url));
await DB.feed.deleteOne({ _id: rem._id });
await destChannel.createMessage({
content: (rem.channel === "dm" ? "" : `<@${rem.url}>`),
embed: {
title: "<:alarm:446901834305634304> REMINDER:",
description: rem.name,
timestamp: new Date(),
color: 0xcc2233,
thumbnail: { url: "https://visualpharm.com/assets/601/Stopwatch-595b40b65ba036ed117d167a.svg" },
},
});
} catch (e) {
await DB.feed.updateOne({ _id: rem._id }, { $inc: { failed: 1 } });
await DB.feed.deleteOne({ _id: rem._id });
console.error("REMOVED FAULTY REMINDER");
console.error(e);
}
}, rem.expires - Date.now()),
);
});
});
}