-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
329 lines (263 loc) · 11.9 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
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
const EventEmitter = require("events");
const formatDistanceToNow = require("date-fns/formatDistanceToNow");
const { setImmediate } = require("timers/promises");
/*
let { ACHIEVEMENTS } = require("./Achievements.js");
async function isPartOfAchievement(param, value, options) {
if (!ACHIEVEMENTS.length) await ACHIEVEMENTS;
if (!ACHIEVEMENTS.length) return false;
return !!ACHIEVEMENTS.find(a => a.condition.includes(param));
}
*/
class ProgressionManager extends EventEmitter {
constructor(client) {
super();
this.userCheckQueue = new Map();
this._client = client;
this.on("*", async (event, opts) => {
let { value, msg, userID } = opts;
userID ??= msg?.author?.id
if (!userID) return;
if (event === "QUEST_COMPLETED") return;
let [action, scope, condition] = event.split('.');
if (global.INSTR){
INSTR.inc("progression.events", { action, scope, condition, value: opts.value, userID: opts.userID, valueSet: opts.valueSet });
}
console.log(`${"•".cyan} Progression: ${action?.gray || "*".gray} -> ${scope?.yellow || "*".gray} -> ${condition?.blue || "*".gray} ${typeof opts.valueSet == 'number' ? " RESET ".bgRed : `[+${value || 1}]`.cyan
}`);
await setImmediate(0, { ref: false });
await this.updateQuestTracker(userID || msg?.author?.id, event, value, opts);
if (!msg) return;
if (!value && !value?.content && !msg?.content) return;
//if (isPartOfAchievement(event)) Achievements.check(msg.author.id, true, { msg: msg || value });
await wait(1);
});
this.on("craft", async (event, opts) => {
const { item, amount, userID, msg } = opts;
const userQuests = await this.getUserQuests(userID);
await Promise.all(userQuests.map(async quest => {
const [action, type, condition] = quest.tracker.split('.');
if (action !== 'craft') return;
if (item[type] === condition) {
await this.updateProgress(userID, quest._id, amount, msg);
}
if (!msg) return;
//this.checkStatusOne(quest._id,userID,msg);
}));
});
/* DEPRECATED
this.on("spend", async (event, opts) => {
return;
let { value, msg, userID } = opts;
let [, currency] = event.split('.');
userID ??= msg?.author?.id;
const userQuests = await this.getUserQuests(userID);
await Promise.all(userQuests.map(async quest => {
const [action, type, condition] = quest.tracker.split('.');
if (condition) return;
if (action !== 'spend') return;
if (currency === type) {
await this.updateProgress(userID, quest._id, value);
}
}));
if (!msg) return;
})
*/
this.on("QUEST_COMPLETED", async (event, quest, opts) => {
const { msg, userQuests, userID } = opts;
//award rewards;
msg.channel.send(await this.questCompletedMsg(quest, userID))
.catch((err) => {
console.error(err)
this._client.getDMChannel( userID ).then(async DM =>
DM.createMessage(await this.questCompletedMsg(quest, userID)).catch(console.error)
).catchReturn(0);
});
if (userQuests?.every(q => q.completed)) {
await wait(4);
//award extra bonus
msg.channel.send("**Extra bonus:** `All Quests Completed` +100 EXP");
await DB.users.set(userID, {
$inc: {
"modules.exp": 100,
"modules.SPH": 0
}
});
}
//notify user
})
}
emit(event, ...args) {
const [action, type, condition] = event.split('.');
super.emit('*', event, ...args); // Catch-all
super.emit(action, event, ...args); // emit top-level
if (type) super.emit(`${action}.${type}`, event, ...args); // emit specific
if (condition) super.emit(`${action}.${type}.${condition}`, event, ...args); // emit super specific
}
async questCompletedMsg(userQuest, userID) {
if (!userID) return " • Errand Completed Error";
let thisUser = this._client.resolveUser(userID);
const quest = await DB.quests.get(userQuest.id);
const currentUserQuests = (await DB.users.findOne({ id: userID }, { quest: 1 }).noCache())?.quests || [];
await wait(3);
// DOUBLE-CHECK
if (currentUserQuests.find(q => userQuest._id.toString() == q._id)?.completed) return;
const embed = {};
await DB.users.set(userID, {
$inc: {
"modules.exp": quest.rewards?.exp || 0,
"modules.RBN": quest.rewards?.RBN || 0,
"modules.SPH": quest.rewards?.SPH || 0
}
});
const createdAt = new Date(parseInt(userQuest._id.toString().substring(0, 8), 16) * 1000).getTime();
const completion = formatDistanceToNow(createdAt);
thisUser = await thisUser;
embed.footer = { icon_url: thisUser.avatarURL, text: ` ${thisUser.tag} • Completed in: ${completion}` };
embed.timestamp = new Date();
embed.description =
/////////////////////////
`${_emoji('yep')} \`COMPLETED\` **${quest.name}**
*${quest.INSTRUCTION}*
${[
(quest.rewards?.exp ? `${_emoji('EXP')}**${quest.rewards.exp}** ` : ""),
(quest.rewards?.RBN ? `${_emoji('RBN')}**${quest.rewards.RBN}** ` : ""),
(quest.rewards?.SPH ? `${_emoji('SPH')}**${quest.rewards.SPH}** ` : "")
].filter(e => !!e).join('\u2002•\u2002')}
`;
/////////////////////////
return { embed };
}
async getUserQuests(userID) {
let quests = (await DB.users.findOne({ id: userID }).noCache().lean())?.quests; //this.userQuestsCache.get(userID);
if (!quests) {
const userData = await DB.users.findOne({ id: userID }).noCache().lean() || [];
quests = userData.quests || [];
//this.userQuestsCache.set(userID,quests);
}
return quests;
}
async updateProgress(userID, questUniqueID, value = 1, msg) {
await DB.users.updateOne({ id: userID, "quests._id": questUniqueID }, { $inc: { 'quests.$.progress': value } }, { new: !0 });
if (msg) this.checkStatusOne(questUniqueID, userID, msg);
}
async overrideProgress(userID, questUniqueID, value = 0, msg) {
await DB.users.updateOne({ id: userID, "quests._id": questUniqueID }, { $set: { 'quests.$.progress': value } }, { new: !0 });
if (msg) this.checkStatusOne(questUniqueID, userID, msg);
}
async updateAll(userID, quests) {
await DB.users.set(userID, { $set: { quests } });
//this.userQuestsCache.set(userID,quests);
}
async checkStatusAll(userID, msg) {
this.userCheckQueue.set(userID, true);
let userQuests = await this.getUserQuests(userID);
if (userQuests) {
for (let i in userQuests) {
let quest = userQuests[i];
await setImmediate(0, { ref: false });
if (quest.progress >= quest.target) {
await DB.users.updateOne({ id: userID, "quests._id": quest._id }, { $set: { 'quests.$.completed': true } }, { new: !0 });
if (msg && !quest.completed) return Progression.emit("QUEST_COMPLETED", quest, { msg, userQuests, userID });
};
if (quest.progress && !quest.target) {
await DB.users.updateOne({ id: userID, "quests._id": quest._id }, { $set: { 'quests.$.completed': true } }, { new: !0 });
if (msg && !quest.completed) Progression.emit("QUEST_COMPLETED", quest, { msg, userQuests, userID });
}
}
};
this.userCheckQueue.set(userID, false);
return userQuests;
}
async checkStatusOne(questID, userID, msg) {
let userQuests = await this.getUserQuests(userID);
if (!userQuests) return [];
const quest = userQuests.find(q => q._id == questID.toString());
await setImmediate(0, { ref: false });
if (quest.progress >= quest.target) {
await DB.users.updateOne({ id: userID, "quests._id": quest._id }, { $set: { 'quests.$.completed': true } }, { new: !0 });
if (msg && !quest.completed) return Progression.emit("QUEST_COMPLETED", quest, { msg, userQuests, userID });
}
if (quest.progress && !quest.target) {
await DB.users.updateOne({ id: userID, "quests._id": quest._id }, { $set: { 'quests.$.completed': true } }, { new: !0 });
if (msg && !quest.completed) Progression.emit("QUEST_COMPLETED", quest, { msg, userQuests, userID });
}
}
async assign(questID, userID) {
let quest = await DB.quests.get(questID);
let newQuest = {
id: quest.id,
target: quest.target || 1,
tracker: `${quest.action}.${quest.type || "*"}${quest.condition ? "." + quest.condition : ""}`,
progress: 0,
completed: false,
}
await DB.users.set(userID, { $push: { quests: newQuest } });
let quests = (await DB.users.findOne({ id: userID }).noCache().lean())?.quests; // this.userQuestsCache.get(userID) || [];
//quests.push(newQuest);
//this.userQuestsCache.set(userID,quests);
return quest;
}
async remove(questID, userID) {
await DB.users.set(userID, { $pull: { "quests": { id: questID } } });
const userData = await DB.users.findOne({ id: userID }).noCache().lean();
//this.userQuestsCache.set(userID,userData.quests);
}
async assignArbitrary(newQuest, userID) {
await DB.users.set(userID, { $push: { quests: newQuest } });
let quests = (await DB.users.findOne({ id: userID }).noCache().lean())?.quests; //this.userQuestsCache.get(userID) || [];
//quests.push(newQuest);
//this.userQuestsCache.set(userID,quests);
return newQuest;
}
async available(userID) {
const userData = await DB.users.findOne({ id: userID }).noCache().lean();
return (await DB.quests.find({ public: true, reveal_level: { $lte: userData.modules.level } }).lean());
}
fulfillsTracker(eventTracker, quest) {
const [questAction, questScope, questCondition, ...questExtras] = quest.tracker.split('.');
const [eventAction, eventScope, eventCondition, ...eventExtras] = eventTracker.split('.');
/* NOTE -- INSPECT EVENTS
console.table({
quest: [questAction, questScope, questCondition, ...questExtras] ,
event: [eventAction, eventScope, eventCondition, ...eventExtras]
})
//*/
if (eventAction === "streak" && questAction !== "streak") return false;
if(quest.tracker === eventTracker || quest.tracker === "*" || quest.tracker === "*.*" || quest.tracker === "*.*.*" ) { // PERFECT MATCH
console.log("[Progression]".blue, "Perfect Match".green, eventTracker,"/",quest.tracker )
return true;
} else if (questAction === eventAction && (((questScope || '*') === (eventScope || '*') && questCondition === eventCondition) || (questScope || '*') === '*')) {
console.log("[Progression]".blue, "Match Scope (arg 2)".green, eventTracker, "/", quest.tracker)
return true;
} else if (questAction === eventAction && questScope === eventScope && ((questCondition || '*') === (eventCondition || '*') || (questCondition || '*') === '*')) {
console.log("[Progression]".blue, "Match Condition (arg 3)".green, eventTracker, "/", quest.tracker)
return true;
}
return false;
}
async updateQuestTracker(userID, eventTracker, value = 1, options) {
let userQuests = await this.getUserQuests(userID);
if (!userQuests) return [];
for (let quest of userQuests) {
if (this.fulfillsTracker(eventTracker, quest)) {
await setImmediate((await processQuest(this, quest)), { ref: false });
}
}
function processQuest(parent, q) {
if (typeof options?.valueSet == 'number')
return parent.overrideProgress(userID, q._id, options.valueSet, options.msg);
else
return parent.updateProgress(userID, q._id, value, options.msg);
}
}
}
// Backwards Compat //
const init = (client) => {
client ??= PLX;
if (!client) throw new Error("Progression can't initialize without a client");
global.Progression = new ProgressionManager(client);
return global.Progression;
}
//////////////////////
module.exports = { ProgressionManager, init }