galactic-bot/structure/extensions/User.js

77 lines
2.7 KiB
JavaScript

const { Structures } = require('discord.js');
const User = Structures.extend('User', (User) => {
class ExtendedUser extends User {
constructor(...args) {
super(...args);
this._settings = null; //internal cache of current users' settings; should ALWAYS stay the same as database.
this._cached = Date.now();
this._points = {
expirations: [],
points: null
};
}
async settings() {
if (!this._settings) this._settings = this.client.storageManager.mongodb.users.findOne({ userId: this.id });
if (this._settings instanceof Promise) this._settings = await this._settings || {};
return this._settings;
}
async totalPoints(guild, point) { // point = { points: x, expiration: x, timestamp: x}
if(this._points.points === null) {
const find = await this.client.storageManager.mongodb.infractions.find(
{ guild: guild.id, target: this.id, points: { $gt: 0 } },
{ projection: { points: "$points", expiration: "$expiration", timestamp: "$timestamp" } }
);
this._points.points = 0;
if(find && find.length > 0) {
for(const { points, expiration, timestamp } of find) {
if(expiration > 0) {
this._points.expirations.push({ points, expiration: expiration*1000+timestamp });
} else {
this._points.points += points;
}
}
}
}
if(point) {
if(point.expiration > 0) {
this._points.expirations.push({ points: point.points, expiration: point.expiration*1000+point.timestamp });
} else {
this._points.points += point.points;
}
}
let points = this._points.expirations.map((e) => { //eslint-disable-line array-callback-return, consistent-return
if(e.expiration >= Date.now()) return e.points;
return 0;
});
if(points.length === 0) points = [ 0 ];
return points.reduce((p, v) => p+v) + this._points.points;
}
get developer() {
return this.client._options.bot.owners.includes(this.id);
}
get timeSinceCached() {
return Date.now()-this._cached;
}
get prefix() {
return this.client._options.bot.prefix;
}
}
return ExtendedUser;
});
module.exports = User;