-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
index.js
454 lines (349 loc) · 13.5 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/* eslint-disable no-unused-vars */
const mongoose = require('mongoose');
const levels = require('./models/levels.js');
const rewards = require('./models/rewards.js');
let mongoUrl;
// Checking if the person has NodeJS v16 or higher
if(process.version.slice(1, 3) - 0 < 16) {
throw new Error(
`NodeJS Version 16 or newer is required, but you are using ${process.version}. See https://nodejs.org to update.`,
);
}
class DiscordXp {
/**
* @param {string} [dbUrl] - A valid mongo database URI.
*/
static async setURL(dbUrl) {
if (!dbUrl) throw new TypeError('A database url was not provided.');
mongoUrl = dbUrl;
return mongoose.connect(dbUrl);
}
/**
* @param {string} [guildId] - Discord guild id.
* @param {number} [level] - level.
*@param {string} [roleId] - Level for which the reward will be created.
*/
static async createRoleReward(guildId, level, roleId) {
if (!guildId) throw new TypeError('A guild id was not provided.');
if (!level) throw new TypeError('A level was not provided.');
if (!roleId) throw new TypeError('A role id was not provided.');
const guildEntry = await rewards.findOne({ guildID: guildId });
const isReward = await rewards.findOne({
guildID: guildId,
rewards: {
$elemMatch: {
level: level,
},
},
});
if(!guildEntry) {
const newReward = new rewards({
guildID: guildId,
rewards: { level: level, roleId: roleId },
});
await newReward.save().catch(e => console.log(`Failed to create role reward: ${e}`));
return newReward;
}
// guildEntry exists but level reward also
if (guildEntry && isReward) return false;
if(guildEntry && !isReward) {
guildEntry.rewards.push({ level: level, roleId: roleId });
await guildEntry.save().catch(e => console.log(`Failed to create role reward: ${e}`));
return guildEntry;
}
}
/**
* @param {string} [guildId] - Discord guild id.
* @param {number} [level] - Level for which the reward will be deleted.
*/
static async deleteRoleReward(guildId, level) {
if (!guildId) throw new TypeError('A guild id was not provided.');
if (!level) throw new TypeError('A level was not provided.');
const isReward = await rewards.findOne({
guildID: guildId,
rewards: {
$elemMatch: {
level: level,
},
},
});
if (!isReward) return false;
const filteredRewardEntries = isReward.rewards.filter(item => item.level !== level);
isReward.rewards = filteredRewardEntries;
isReward.lastUpdated = new Date();
await isReward.save().catch(e => console.log(`Failed to delete role reward: ${e}`));
return isReward;
}
/**
* @param {string} [guildId] - Discord guild id.
* @param {number} [level] - Level for which the reward will be fetched.
*/
static async fetchRoleReward(guildId, level) {
if (!guildId) throw new TypeError('A guild id was not provided.');
if (!level) throw new TypeError('A level was not provided.');
const isReward = await rewards.findOne({
guildID: guildId,
rewards: {
$elemMatch: {
level: level,
},
},
});
if (!isReward) return false;
const filteredRewardEntries = isReward.rewards.filter(item => item.level === level);
return filteredRewardEntries[0];
}
/**
* @param {string} [client] - Your Discord.CLient.
* @param {string} [guildId] - The guild which entries should be cleaned.
*/
static async cleanDatabase(client, guildId) {
if (!client) throw new TypeError('A client was not provided.');
if (!guildId) throw new TypeError('A guild id was not provided.');
const users = await levels.find({ guildID: guildId });
// return users.slice(0, limit);
const computedArray = [];
for (const user of users) {
try {
const isUser = await client.users.fetch(user.userID);
}
catch (error) {
computedArray.push(user.userID);
return await levels.findOneAndDelete({ userID: user.userID, guildID: guildId }).catch(e => console.log(`Failed to delete user: ${e}`));
}
}
return computedArray;
}
/**
* @param {string} [userId] - Discord user id.
* @param {string} [guildId] - Discord guild id.
*/
static async createUser(userId, guildId) {
if (!userId) throw new TypeError('An user id was not provided.');
if (!guildId) throw new TypeError('A guild id was not provided.');
const isUser = await levels.findOne({ userID: userId, guildID: guildId });
if (isUser) return false;
const newUser = new levels({
userID: userId,
guildID: guildId,
});
await newUser.save().catch(e => console.log(`Failed to create user: ${e}`));
return newUser;
}
/**
* @param {string} [userId] - Discord user id.
* @param {string} [guildId] - Discord guild id.
*/
static async deleteUser(userId, guildId) {
if (!userId) throw new TypeError('An user id was not provided.');
if (!guildId) throw new TypeError('A guild id was not provided.');
const user = await levels.findOne({ userID: userId, guildID: guildId });
if (!user) return false;
await levels.findOneAndDelete({ userID: userId, guildID: guildId }).catch(e => console.log(`Failed to delete user: ${e}`));
return user;
}
/**
* @param {string} [userId] - Discord user id.
* @param {string} [guildId] - Discord guild id.
* @param {number} [xp] - Amount of xp to append.
*/
static async appendXp(userId, guildId, xp) {
if (!userId) throw new TypeError('An user id was not provided.');
if (!guildId) throw new TypeError('A guild id was not provided.');
if (xp <= 0 || !xp || isNaN(parseInt(xp))) throw new TypeError('An amount of xp was not provided/was invalid.');
const user = await levels.findOne({ userID: userId, guildID: guildId });
if (!user) {
const newUser = new levels({
userID: userId,
guildID: guildId,
xp: xp,
level: Math.floor(0.1 * Math.sqrt(xp)),
});
await newUser.save().catch(e => console.log('Failed to save new user.'));
return (Math.floor(0.1 * Math.sqrt(xp)) > 0);
}
user.xp += parseInt(xp, 10);
user.level = Math.floor(0.1 * Math.sqrt(user.xp));
user.lastUpdated = new Date();
await user.save().catch(e => console.log(`Failed to append xp: ${e}`));
/*
const isReward = await rewards.findOne({ guildID: guildId, rewards: level });
if(Math.floor(0.1 * Math.sqrt(user.xp -= xp)) < user.level && isReward) return isReward;
*/
return (Math.floor(0.1 * Math.sqrt(user.xp -= xp)) < user.level);
}
/**
* @param {string} [userId] - Discord user id.
* @param {string} [guildId] - Discord guild id.
* @param {number} [levels] - Amount of levels to append.
*/
static async appendLevel(userId, guildId, levelss) {
if (!userId) throw new TypeError('An user id was not provided.');
if (!guildId) throw new TypeError('A guild id was not provided.');
if (!levelss) throw new TypeError('An amount of levels was not provided.');
const user = await levels.findOne({ userID: userId, guildID: guildId });
if (!user) return false;
user.level += parseInt(levelss, 10);
user.xp = user.level * user.level * 100;
user.lastUpdated = new Date();
user.save().catch(e => console.log(`Failed to append level: ${e}`));
return user;
}
/**
* @param {string} [userId] - Discord user id.
* @param {string} [guildId] - Discord guild id.
* @param {number} [xp] - Amount of xp to set.
*/
static async setXp(userId, guildId, xp) {
if (!userId) throw new TypeError('An user id was not provided.');
if (!guildId) throw new TypeError('A guild id was not provided.');
if (xp <= 0 || !xp || isNaN(parseInt(xp))) throw new TypeError('An amount of xp was not provided/was invalid.');
const user = await levels.findOne({ userID: userId, guildID: guildId });
if (!user) return false;
user.xp = xp;
user.level = Math.floor(0.1 * Math.sqrt(user.xp));
user.lastUpdated = new Date();
user.save().catch(e => console.log(`Failed to set xp: ${e}`));
return user;
}
/**
* @param {string} [userId] - Discord user id.
* @param {string} [guildId] - Discord guild id.
* @param {number} [level] - A level to set.
*/
static async setLevel(userId, guildId, level) {
if (!userId) throw new TypeError('An user id was not provided.');
if (!guildId) throw new TypeError('A guild id was not provided.');
if (!level) throw new TypeError('A level was not provided.');
const user = await levels.findOne({ userID: userId, guildID: guildId });
if (!user) return false;
user.level = level;
user.xp = level * level * 100;
user.lastUpdated = new Date();
user.save().catch(e => console.log(`Failed to set level: ${e}`));
return user;
}
/**
* @param {string} [userId] - Discord user id.
* @param {string} [guildId] - Discord guild id.
*/
static async fetch(userId, guildId, fetchPosition = false) {
if (!userId) throw new TypeError('An user id was not provided.');
if (!guildId) throw new TypeError('A guild id was not provided.');
const user = await levels.findOne({
userID: userId,
guildID: guildId,
});
if (!user) return false;
if (fetchPosition === true) {
const leaderboard = await levels.find({
guildID: guildId,
}).sort([['xp', 'descending']]).exec();
user.position = leaderboard.findIndex(i => i.userID === userId) + 1;
}
/* To be used with canvacord or displaying xp in a pretier fashion, with each level the cleanXp stats from 0 and goes until cleanNextLevelXp when user levels up and gets back to 0 then the cleanNextLevelXp is re-calculated */
user.cleanXp = user.xp - this.xpFor(user.level);
user.cleanNextLevelXp = this.xpFor(user.level + 1) - this.xpFor(user.level);
return user;
}
/**
* @param {string} [userId] - Discord user id.
* @param {string} [guildId] - Discord guild id.
* @param {number} [xp] - Amount of xp to subtract.
*/
static async subtractXp(userId, guildId, xp) {
if (!userId) throw new TypeError('An user id was not provided.');
if (!guildId) throw new TypeError('A guild id was not provided.');
if (xp <= 0 || !xp || isNaN(parseInt(xp))) throw new TypeError('An amount of xp was not provided/was invalid.');
const user = await levels.findOne({ userID: userId, guildID: guildId });
if (!user) return false;
user.xp -= xp;
user.level = Math.floor(0.1 * Math.sqrt(user.xp));
user.lastUpdated = new Date();
user.save().catch(e => console.log(`Failed to subtract xp: ${e}`));
return user;
}
/**
* @param {string} [userId] - Discord user id.
* @param {string} [guildId] - Discord guild id.
* @param {number} [levels] - Amount of levels to subtract.
*/
static async subtractLevel(userId, guildId, levelss) {
if (!userId) throw new TypeError('An user id was not provided.');
if (!guildId) throw new TypeError('A guild id was not provided.');
if (!levelss) throw new TypeError('An amount of levels was not provided.');
const user = await levels.findOne({ userID: userId, guildID: guildId });
if (!user) return false;
user.level -= levelss;
user.xp = user.level * user.level * 100;
user.lastUpdated = new Date();
user.save().catch(e => console.log(`Failed to subtract levels: ${e}`));
return user;
}
/**
* @param {string} [guildId] - Discord guild id.
* @param {number} [limit] - Amount of maximum enteries to return.
*/
static async fetchLeaderboard(guildId, limit) {
if (!guildId) throw new TypeError('A guild id was not provided.');
if (!limit) throw new TypeError('A limit was not provided.');
const users = await levels.find({ guildID: guildId }).sort([['xp', 'descending']]).limit(limit).exec();
return users;
}
/**
* @param {string} [client] - Your Discord.CLient.
* @param {array} [leaderboard] - The output from 'fetchLeaderboard' function.
*/
static async computeLeaderboard(client, leaderboard, fetchUsers = false) {
if (!client) throw new TypeError('A client was not provided.');
if (!leaderboard) throw new TypeError('A leaderboard id was not provided.');
if (leaderboard.length < 1) return [];
const computedArray = [];
if (fetchUsers) {
for (const key of leaderboard) {
const user = await client.users.fetch(key.userID) || { username: 'Unknown', discriminator: '0000' };
computedArray.push({
guildID: key.guildID,
userID: key.userID,
xp: key.xp,
level: key.level,
position: (leaderboard.findIndex(i => i.guildID === key.guildID && i.userID === key.userID) + 1),
username: user.username,
discriminator: user.discriminator,
});
}
}
else {
leaderboard.map(key => computedArray.push({
guildID: key.guildID,
userID: key.userID,
xp: key.xp,
level: key.level,
position: (leaderboard.findIndex(i => i.guildID === key.guildID && i.userID === key.userID) + 1),
username: client.users.cache.get(key.userID) ? client.users.cache.get(key.userID).username : 'Unknown',
discriminator: client.users.cache.get(key.userID) ? client.users.cache.get(key.userID).discriminator : '0000',
}));
}
return computedArray;
}
/*
* @param {number} [targetLevel] - Xp required to reach that level.
*/
static xpFor(targetLevel) {
if (isNaN(targetLevel) || isNaN(parseInt(targetLevel, 10))) throw new TypeError('Target level should be a valid number.');
if (isNaN(targetLevel)) targetLevel = parseInt(targetLevel, 10);
if (targetLevel < 0) throw new RangeError('Target level should be a positive number.');
return targetLevel * targetLevel * 100;
}
/**
* @param {string} [guildId] - Discord guild id.
*/
static async deleteGuild(guildId) {
if (!guildId) throw new TypeError('A guild id was not provided.');
const guild = await levels.findOne({ guildID: guildId });
if (!guild) return false;
await levels.deleteMany({ guildID: guildId }).catch(e => console.log(`Failed to delete guild: ${e}`));
return guild;
}
}
module.exports = DiscordXp;