discord-xp-fork 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +187 -0
- package/index.d.ts +45 -0
- package/index.js +321 -0
- package/models/levels.js +11 -0
- package/package.json +46 -0
- package/test/README.md +102 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2019 MrAugu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# Discord-Xp-Fork
|
|
2
|
+
- Original code made by MrAugu and is located at <a href="https://github.com/MrAugu/discord-xp">this Github Repository</a>. This is a fork of this code, made to address some issues with the original as a result of the time that has passed since its last update.
|
|
3
|
+
- A lightweight and easy to use xp framework for discord bots, uses MongoDB.
|
|
4
|
+
- If you need help feel free to join our <a href="https://discord.gg/aP9UYfaFa4">discord server</a> to talk and help you with your code.
|
|
5
|
+
- If you encounter any of those fell free to open an issue in our <a href="https://github.com/MrAugu/discord-xp/issues">github repository</a>.
|
|
6
|
+
|
|
7
|
+
# Download & Update
|
|
8
|
+
You can download it from npm:
|
|
9
|
+
```cli
|
|
10
|
+
npm i discord-xp
|
|
11
|
+
```
|
|
12
|
+
You can update to a newer version to receive updates using npm.
|
|
13
|
+
```cli
|
|
14
|
+
npm update discord-xp
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
# Changelog
|
|
18
|
+
- **21 April 2025** (v1.2.2) - version bump to update readme on npmjs
|
|
19
|
+
|
|
20
|
+
- **21 April 2025** (v1.2.1) - renamed to "discord-xp-fork", changed repo links to point to woomy/discord-xp on codeberg, updated readme to state that this is a fork of the original and to give credit to the original creator.
|
|
21
|
+
|
|
22
|
+
- **21 April 2025** (v1.2.0) - updated mongoose dependency so that it is no longer vulnerable, appendXp function now returns correct response based on if user has leveled up or not.
|
|
23
|
+
|
|
24
|
+
- **27 May 2021** (v1.1.11) - Adding deleteGuild() method.
|
|
25
|
+
|
|
26
|
+
- **3 April 2021** (v1.1.11) - Adding TS typings.
|
|
27
|
+
|
|
28
|
+
- **25 February 2021** (v1.1.8) - Preventing further deprection warnings to be displayed, if you encounter any of these deprecation issues, update the module.
|
|
29
|
+
|
|
30
|
+
- **22 November 2020** (v1.1.7) `WARNING: This semi-major version contains breaking changes in the way leaderboard computing function works.`
|
|
31
|
+
1. Added an optional `fetchPosition` argument to the `Levels.fetch` which will add the leaderboard rank as the `position` property. Caution: Will be slower on larger servers.
|
|
32
|
+
2. `Levels.computeLeaderboard` is now asynchronous and can take in a third parameter called `fetchUsers` which will fetch all users on the leaderboard. This parameter **does not** require additional Gateway Intents. Caution: Will be substantially slower if you do not have `Guild_Members` intent and catch some users beforehand.
|
|
33
|
+
|
|
34
|
+
- **16 July 2020** - Added `xpFor` method to calculate xp required for a specific level.
|
|
35
|
+
```js
|
|
36
|
+
/* xpFor Example */
|
|
37
|
+
const Levels = require("discord-xp");
|
|
38
|
+
// Returns the xp required to reach level 30.
|
|
39
|
+
var xpRequired = Levels.xpFor(30);
|
|
40
|
+
|
|
41
|
+
console.log(xpRequired); // Output: 90000
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
# Setting Up
|
|
45
|
+
First things first, we include the module into the project.
|
|
46
|
+
```js
|
|
47
|
+
const Levels = require("discord-xp");
|
|
48
|
+
```
|
|
49
|
+
After that, you need to provide a valid mongo database url, and set it. You can do so by:
|
|
50
|
+
```js
|
|
51
|
+
Levels.setURL("mongodb://..."); // You only need to do this ONCE per process.
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
# Examples
|
|
55
|
+
*Examples can be found in /test*
|
|
56
|
+
|
|
57
|
+
# Methods
|
|
58
|
+
**createUser**
|
|
59
|
+
|
|
60
|
+
Creates an entry in database for that user if it doesnt exist.
|
|
61
|
+
```js
|
|
62
|
+
Levels.createUser(<UserID - String>, <GuildID - String>);
|
|
63
|
+
```
|
|
64
|
+
- Output:
|
|
65
|
+
```
|
|
66
|
+
Promise<Object>
|
|
67
|
+
```
|
|
68
|
+
**deleteUser**
|
|
69
|
+
|
|
70
|
+
If the entry exists, it deletes it from database.
|
|
71
|
+
```js
|
|
72
|
+
Levels.deleteUser(<UserID - String>, <GuildID - String>);
|
|
73
|
+
```
|
|
74
|
+
- Output:
|
|
75
|
+
```
|
|
76
|
+
Promise<Object>
|
|
77
|
+
```
|
|
78
|
+
**deleteGuild**
|
|
79
|
+
|
|
80
|
+
If the entry exists, it deletes it from database.
|
|
81
|
+
```js
|
|
82
|
+
Levels.deleteGuild(<GuildID - String>);
|
|
83
|
+
```
|
|
84
|
+
- Output:
|
|
85
|
+
```
|
|
86
|
+
Promise<Object>
|
|
87
|
+
```
|
|
88
|
+
**appendXp**
|
|
89
|
+
|
|
90
|
+
It adds a specified amount of xp to the current amount of xp for that user, in that guild. It re-calculates the level. It creates a new user with that amount of xp, if there is no entry for that user.
|
|
91
|
+
```js
|
|
92
|
+
Levels.appendXp(<UserID - String>, <GuildID - String>, <Amount - Integer>);
|
|
93
|
+
```
|
|
94
|
+
- Output:
|
|
95
|
+
```
|
|
96
|
+
Promise<Boolean>
|
|
97
|
+
```
|
|
98
|
+
**appendLevel**
|
|
99
|
+
|
|
100
|
+
It adds a specified amount of levels to current amount, re-calculates and sets the xp reqired to reach the new amount of levels.
|
|
101
|
+
```js
|
|
102
|
+
Levels.appendLevel(<UserID - String>, <GuildID - String>, <Amount - Integer>);
|
|
103
|
+
```
|
|
104
|
+
- Output:
|
|
105
|
+
```
|
|
106
|
+
Promise<Boolean/Object>
|
|
107
|
+
```
|
|
108
|
+
**setXp**
|
|
109
|
+
|
|
110
|
+
It sets the xp to a specified amount and re-calculates the level.
|
|
111
|
+
```js
|
|
112
|
+
Levels.setXp(<UserID - String>, <GuildID - String>, <Amount - Integer>);
|
|
113
|
+
```
|
|
114
|
+
- Output:
|
|
115
|
+
```
|
|
116
|
+
Promise<Boolean/Object>
|
|
117
|
+
```
|
|
118
|
+
**setLevel**
|
|
119
|
+
|
|
120
|
+
Calculates the xp required to reach a specified level and updates it.
|
|
121
|
+
```js
|
|
122
|
+
Levels.setLevel(<UserID - String>, <GuildID - String>, <Amount - Integer>);
|
|
123
|
+
```
|
|
124
|
+
- Output:
|
|
125
|
+
```
|
|
126
|
+
Promise<Boolean/Object>
|
|
127
|
+
```
|
|
128
|
+
**fetch** (**Updated recently!**)
|
|
129
|
+
|
|
130
|
+
Retrives selected entry from the database, if it exists.
|
|
131
|
+
```js
|
|
132
|
+
Levels.fetch(<UserID - String>, <GuildID - String>, <FetchPosition - Boolean>);
|
|
133
|
+
```
|
|
134
|
+
- Output:
|
|
135
|
+
```
|
|
136
|
+
Promise<Object>
|
|
137
|
+
```
|
|
138
|
+
**subtractXp**
|
|
139
|
+
|
|
140
|
+
It removes a specified amount of xp to the current amount of xp for that user, in that guild. It re-calculates the level.
|
|
141
|
+
```js
|
|
142
|
+
Levels.subtractXp(<UserID - String>, <GuildID - String>, <Amount - Integer>);
|
|
143
|
+
```
|
|
144
|
+
- Output:
|
|
145
|
+
```
|
|
146
|
+
Promise<Boolean/Object>
|
|
147
|
+
```
|
|
148
|
+
**subtractLevel**
|
|
149
|
+
|
|
150
|
+
It removes a specified amount of levels to current amount, re-calculates and sets the xp reqired to reach the new amount of levels.
|
|
151
|
+
```js
|
|
152
|
+
Levels.subtractLevel(<UserID - String>, <GuildID - String>, <Amount - Number>);
|
|
153
|
+
```
|
|
154
|
+
- Output:
|
|
155
|
+
```
|
|
156
|
+
Promise<Boolean/Object>
|
|
157
|
+
```
|
|
158
|
+
**fetchLeaderboard**
|
|
159
|
+
|
|
160
|
+
It gets a specified amount of entries from the database, ordered from higgest to lowest within the specified limit of entries.
|
|
161
|
+
```js
|
|
162
|
+
Levels.fetchLeaderboard(<GuildID - String>, <Limit - Integer>);
|
|
163
|
+
```
|
|
164
|
+
- Output:
|
|
165
|
+
```
|
|
166
|
+
Promise<Array [Objects]>
|
|
167
|
+
```
|
|
168
|
+
**computeLeaderboard** (**Updated recently!**)
|
|
169
|
+
|
|
170
|
+
It returns a new array of object that include level, xp, guild id, user id, leaderboard position, username and discriminator.
|
|
171
|
+
```js
|
|
172
|
+
Levels.computeLeaderboard(<Client - Discord.js Client>, <Leaderboard - fetchLeaderboard output>, <fetchUsers - boolean, disabled by default>);
|
|
173
|
+
```
|
|
174
|
+
- Output:
|
|
175
|
+
```
|
|
176
|
+
Promise<Array [Objects]>
|
|
177
|
+
```
|
|
178
|
+
**xpFor**
|
|
179
|
+
|
|
180
|
+
It returns a number that indicates amount of xp required to reach a level based on the input.
|
|
181
|
+
```js
|
|
182
|
+
Levels.xpFor(<TargetLevel - Integer>);
|
|
183
|
+
```
|
|
184
|
+
- Output:
|
|
185
|
+
```
|
|
186
|
+
Integer
|
|
187
|
+
```
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Type definitions for discord-xp v1.1.8
|
|
2
|
+
// Project: https://github.com/MrAugu/discord-xp
|
|
3
|
+
// Definitions by: Nico Finkernagel <https://github.com/gruselhaus/>
|
|
4
|
+
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
|
5
|
+
|
|
6
|
+
import { Client } from "discord.js";
|
|
7
|
+
|
|
8
|
+
type User = {
|
|
9
|
+
userID: string;
|
|
10
|
+
guildID: string;
|
|
11
|
+
xp: number;
|
|
12
|
+
level: number;
|
|
13
|
+
lastUpdated: Date;
|
|
14
|
+
cleanXp: number;
|
|
15
|
+
cleanNextLevelXp: number;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
type LeaderboardUser = {
|
|
19
|
+
guildID: string;
|
|
20
|
+
userID: string;
|
|
21
|
+
xp: number;
|
|
22
|
+
level: number;
|
|
23
|
+
position: number;
|
|
24
|
+
username: String | null;
|
|
25
|
+
discriminator: String | null;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
declare module "discord-xp" {
|
|
29
|
+
export default class DiscordXp {
|
|
30
|
+
static async setURL(dbURL: string): Promise<typeof import("mongoose")>;
|
|
31
|
+
static async createUser(userId: string, guildId: string): Promise<User>;
|
|
32
|
+
static async deleteUser(userId: string, guildId: string): Promise<User>;
|
|
33
|
+
static async deleteGuild(guildId: string): Promise<Guild>;
|
|
34
|
+
static async appendXp(userId: string, guildId: string, xp: number): Promise<boolean>;
|
|
35
|
+
static async appendLevel(userId: string, guildId: string, levels: number): Promise<User>;
|
|
36
|
+
static async setXp(userId: string, guildId: string, xp: number): Promise<User>;
|
|
37
|
+
static async setLevel(userId: string, guildId: string, level: number): Promise<User>;
|
|
38
|
+
static async fetch(userId: string, guildId: string, fetchPosition = false): Promise<User>;
|
|
39
|
+
static async subtractXp(userId: string, guildId: string, xp: number): Promise<User>;
|
|
40
|
+
static async subtractLevel(userId: string, guildId: string, level: number): Promise<User>;
|
|
41
|
+
static async fetchLeaderboard(guildId: String, limit: number): Promise<User[] | []>;
|
|
42
|
+
static async computeLeaderboard(client: Client, leaderboard: User[], fetchUsers = false): Promise<LeaderboardUser[] | []>;
|
|
43
|
+
static xpFor(targetLevel: number): number;
|
|
44
|
+
}
|
|
45
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
const mongoose = require("mongoose");
|
|
2
|
+
const levels = require("./models/levels.js");
|
|
3
|
+
var mongoUrl;
|
|
4
|
+
|
|
5
|
+
class DiscordXp {
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @param {string} [dbUrl] - A valid mongo database URI.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
static async setURL(dbUrl) {
|
|
12
|
+
if (!dbUrl) throw new TypeError("A database url was not provided.");
|
|
13
|
+
mongoUrl = dbUrl;
|
|
14
|
+
return mongoose.connect(dbUrl);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {string} [userId] - Discord user id.
|
|
19
|
+
* @param {string} [guildId] - Discord guild id.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
static async createUser(userId, guildId) {
|
|
23
|
+
if (!userId) throw new TypeError("An user id was not provided.");
|
|
24
|
+
if (!guildId) throw new TypeError("A guild id was not provided.");
|
|
25
|
+
|
|
26
|
+
const isUser = await levels.findOne({ userID: userId, guildID: guildId });
|
|
27
|
+
if (isUser) return false;
|
|
28
|
+
|
|
29
|
+
const newUser = new levels({
|
|
30
|
+
userID: userId,
|
|
31
|
+
guildID: guildId
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
await newUser.save().catch(e => console.log(`Failed to create user: ${e}`));
|
|
35
|
+
|
|
36
|
+
return newUser;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {string} [userId] - Discord user id.
|
|
41
|
+
* @param {string} [guildId] - Discord guild id.
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
static async deleteUser(userId, guildId) {
|
|
45
|
+
if (!userId) throw new TypeError("An user id was not provided.");
|
|
46
|
+
if (!guildId) throw new TypeError("A guild id was not provided.");
|
|
47
|
+
|
|
48
|
+
const user = await levels.findOne({ userID: userId, guildID: guildId });
|
|
49
|
+
if (!user) return false;
|
|
50
|
+
|
|
51
|
+
await levels.findOneAndDelete({ userID: userId, guildID: guildId }).catch(e => console.log(`Failed to delete user: ${e}`));
|
|
52
|
+
|
|
53
|
+
return user;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @param {string} [userId] - Discord user id.
|
|
58
|
+
* @param {string} [guildId] - Discord guild id.
|
|
59
|
+
* @param {number} [xp] - Amount of xp to append.
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
static async appendXp(userId, guildId, xp) {
|
|
63
|
+
if (!userId) throw new TypeError("An user id was not provided.");
|
|
64
|
+
if (!guildId) throw new TypeError("A guild id was not provided.");
|
|
65
|
+
if (xp == 0 || !xp || isNaN(parseInt(xp))) throw new TypeError("An amount of xp was not provided/was invalid.");
|
|
66
|
+
|
|
67
|
+
const user = await levels.findOne({ userID: userId, guildID: guildId });
|
|
68
|
+
|
|
69
|
+
if (!user) {
|
|
70
|
+
const newUser = new levels({
|
|
71
|
+
userID: userId,
|
|
72
|
+
guildID: guildId,
|
|
73
|
+
xp: xp,
|
|
74
|
+
level: Math.floor(0.1 * Math.sqrt(xp))
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
await newUser.save().catch(e => console.log(`Failed to save new user.`));
|
|
78
|
+
|
|
79
|
+
return (Math.floor(0.1 * Math.sqrt(xp)) > 0);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const oldLevel = user.level;
|
|
83
|
+
|
|
84
|
+
user.xp += parseInt(xp, 10);
|
|
85
|
+
user.level = Math.floor(0.1 * Math.sqrt(user.xp));
|
|
86
|
+
user.lastUpdated = new Date();
|
|
87
|
+
|
|
88
|
+
await user.save().catch(e => console.log(`Failed to append xp: ${e}`) );
|
|
89
|
+
|
|
90
|
+
return (Math.floor(0.1 * Math.sqrt(user.xp -= xp)) > oldLevel);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* @param {string} [userId] - Discord user id.
|
|
95
|
+
* @param {string} [guildId] - Discord guild id.
|
|
96
|
+
* @param {number} [levels] - Amount of levels to append.
|
|
97
|
+
*/
|
|
98
|
+
|
|
99
|
+
static async appendLevel(userId, guildId, levelss) {
|
|
100
|
+
if (!userId) throw new TypeError("An user id was not provided.");
|
|
101
|
+
if (!guildId) throw new TypeError("A guild id was not provided.");
|
|
102
|
+
if (!levelss) throw new TypeError("An amount of levels was not provided.");
|
|
103
|
+
|
|
104
|
+
const user = await levels.findOne({ userID: userId, guildID: guildId });
|
|
105
|
+
if (!user) return false;
|
|
106
|
+
|
|
107
|
+
user.level += parseInt(levelss, 10);
|
|
108
|
+
user.xp = user.level * user.level * 100;
|
|
109
|
+
user.lastUpdated = new Date();
|
|
110
|
+
|
|
111
|
+
user.save().catch(e => console.log(`Failed to append level: ${e}`) );
|
|
112
|
+
|
|
113
|
+
return user;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* @param {string} [userId] - Discord user id.
|
|
118
|
+
* @param {string} [guildId] - Discord guild id.
|
|
119
|
+
* @param {number} [xp] - Amount of xp to set.
|
|
120
|
+
*/
|
|
121
|
+
|
|
122
|
+
static async setXp(userId, guildId, xp) {
|
|
123
|
+
if (!userId) throw new TypeError("An user id was not provided.");
|
|
124
|
+
if (!guildId) throw new TypeError("A guild id was not provided.");
|
|
125
|
+
if (xp == 0 || !xp || isNaN(parseInt(xp))) throw new TypeError("An amount of xp was not provided/was invalid.");
|
|
126
|
+
|
|
127
|
+
const user = await levels.findOne({ userID: userId, guildID: guildId });
|
|
128
|
+
if (!user) return false;
|
|
129
|
+
|
|
130
|
+
user.xp = xp;
|
|
131
|
+
user.level = Math.floor(0.1 * Math.sqrt(user.xp));
|
|
132
|
+
user.lastUpdated = new Date();
|
|
133
|
+
|
|
134
|
+
user.save().catch(e => console.log(`Failed to set xp: ${e}`) );
|
|
135
|
+
|
|
136
|
+
return user;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @param {string} [userId] - Discord user id.
|
|
141
|
+
* @param {string} [guildId] - Discord guild id.
|
|
142
|
+
* @param {number} [level] - A level to set.
|
|
143
|
+
*/
|
|
144
|
+
|
|
145
|
+
static async setLevel(userId, guildId, level) {
|
|
146
|
+
if (!userId) throw new TypeError("An user id was not provided.");
|
|
147
|
+
if (!guildId) throw new TypeError("A guild id was not provided.");
|
|
148
|
+
if (!level) throw new TypeError("A level was not provided.");
|
|
149
|
+
|
|
150
|
+
const user = await levels.findOne({ userID: userId, guildID: guildId });
|
|
151
|
+
if (!user) return false;
|
|
152
|
+
|
|
153
|
+
user.level = level;
|
|
154
|
+
user.xp = level * level * 100;
|
|
155
|
+
user.lastUpdated = new Date();
|
|
156
|
+
|
|
157
|
+
user.save().catch(e => console.log(`Failed to set level: ${e}`) );
|
|
158
|
+
|
|
159
|
+
return user;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* @param {string} [userId] - Discord user id.
|
|
164
|
+
* @param {string} [guildId] - Discord guild id.
|
|
165
|
+
*/
|
|
166
|
+
|
|
167
|
+
static async fetch(userId, guildId, fetchPosition = false) {
|
|
168
|
+
if (!userId) throw new TypeError("An user id was not provided.");
|
|
169
|
+
if (!guildId) throw new TypeError("A guild id was not provided.");
|
|
170
|
+
|
|
171
|
+
const user = await levels.findOne({
|
|
172
|
+
userID: userId,
|
|
173
|
+
guildID: guildId
|
|
174
|
+
});
|
|
175
|
+
if (!user) return false;
|
|
176
|
+
|
|
177
|
+
if (fetchPosition === true) {
|
|
178
|
+
const leaderboard = await levels.find({
|
|
179
|
+
guildID: guildId
|
|
180
|
+
}).sort([['xp', 'descending']]).exec();
|
|
181
|
+
|
|
182
|
+
user.position = leaderboard.findIndex(i => i.userID === userId) + 1;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
/* 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 */
|
|
187
|
+
user.cleanXp = user.xp - this.xpFor(user.level);
|
|
188
|
+
user.cleanNextLevelXp = this.xpFor(user.level + 1) - this.xpFor(user.level);
|
|
189
|
+
|
|
190
|
+
return user;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* @param {string} [userId] - Discord user id.
|
|
195
|
+
* @param {string} [guildId] - Discord guild id.
|
|
196
|
+
* @param {number} [xp] - Amount of xp to subtract.
|
|
197
|
+
*/
|
|
198
|
+
|
|
199
|
+
static async subtractXp(userId, guildId, xp) {
|
|
200
|
+
if (!userId) throw new TypeError("An user id was not provided.");
|
|
201
|
+
if (!guildId) throw new TypeError("A guild id was not provided.");
|
|
202
|
+
if (xp == 0 || !xp || isNaN(parseInt(xp))) throw new TypeError("An amount of xp was not provided/was invalid.");
|
|
203
|
+
|
|
204
|
+
const user = await levels.findOne({ userID: userId, guildID: guildId });
|
|
205
|
+
if (!user) return false;
|
|
206
|
+
|
|
207
|
+
user.xp -= xp;
|
|
208
|
+
user.level = Math.floor(0.1 * Math.sqrt(user.xp));
|
|
209
|
+
user.lastUpdated = new Date();
|
|
210
|
+
|
|
211
|
+
user.save().catch(e => console.log(`Failed to subtract xp: ${e}`) );
|
|
212
|
+
|
|
213
|
+
return user;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* @param {string} [userId] - Discord user id.
|
|
218
|
+
* @param {string} [guildId] - Discord guild id.
|
|
219
|
+
* @param {number} [levels] - Amount of levels to subtract.
|
|
220
|
+
*/
|
|
221
|
+
|
|
222
|
+
static async subtractLevel(userId, guildId, levelss) {
|
|
223
|
+
if (!userId) throw new TypeError("An user id was not provided.");
|
|
224
|
+
if (!guildId) throw new TypeError("A guild id was not provided.");
|
|
225
|
+
if (!levelss) throw new TypeError("An amount of levels was not provided.");
|
|
226
|
+
|
|
227
|
+
const user = await levels.findOne({ userID: userId, guildID: guildId });
|
|
228
|
+
if (!user) return false;
|
|
229
|
+
|
|
230
|
+
user.level -= levelss;
|
|
231
|
+
user.xp = user.level * user.level * 100;
|
|
232
|
+
user.lastUpdated = new Date();
|
|
233
|
+
|
|
234
|
+
user.save().catch(e => console.log(`Failed to subtract levels: ${e}`) );
|
|
235
|
+
|
|
236
|
+
return user;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* @param {string} [guildId] - Discord guild id.
|
|
241
|
+
* @param {number} [limit] - Amount of maximum enteries to return.
|
|
242
|
+
*/
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
static async fetchLeaderboard(guildId, limit) {
|
|
246
|
+
if (!guildId) throw new TypeError("A guild id was not provided.");
|
|
247
|
+
if (!limit) throw new TypeError("A limit was not provided.");
|
|
248
|
+
|
|
249
|
+
var users = await levels.find({ guildID: guildId }).sort([['xp', 'descending']]).exec();
|
|
250
|
+
|
|
251
|
+
return users.slice(0, limit);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* @param {string} [client] - Your Discord.CLient.
|
|
256
|
+
* @param {array} [leaderboard] - The output from 'fetchLeaderboard' function.
|
|
257
|
+
*/
|
|
258
|
+
|
|
259
|
+
static async computeLeaderboard(client, leaderboard, fetchUsers = false) {
|
|
260
|
+
if (!client) throw new TypeError("A client was not provided.");
|
|
261
|
+
if (!leaderboard) throw new TypeError("A leaderboard id was not provided.");
|
|
262
|
+
|
|
263
|
+
if (leaderboard.length < 1) return [];
|
|
264
|
+
|
|
265
|
+
const computedArray = [];
|
|
266
|
+
|
|
267
|
+
if (fetchUsers) {
|
|
268
|
+
for (const key of leaderboard) {
|
|
269
|
+
const user = await client.users.fetch(key.userID) || { username: "Unknown", discriminator: "0000" };
|
|
270
|
+
computedArray.push({
|
|
271
|
+
guildID: key.guildID,
|
|
272
|
+
userID: key.userID,
|
|
273
|
+
xp: key.xp,
|
|
274
|
+
level: key.level,
|
|
275
|
+
position: (leaderboard.findIndex(i => i.guildID === key.guildID && i.userID === key.userID) + 1),
|
|
276
|
+
username: user.username,
|
|
277
|
+
discriminator: user.discriminator
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
} else {
|
|
281
|
+
leaderboard.map(key => computedArray.push({
|
|
282
|
+
guildID: key.guildID,
|
|
283
|
+
userID: key.userID,
|
|
284
|
+
xp: key.xp,
|
|
285
|
+
level: key.level,
|
|
286
|
+
position: (leaderboard.findIndex(i => i.guildID === key.guildID && i.userID === key.userID) + 1),
|
|
287
|
+
username: client.users.cache.get(key.userID) ? client.users.cache.get(key.userID).username : "Unknown",
|
|
288
|
+
discriminator: client.users.cache.get(key.userID) ? client.users.cache.get(key.userID).discriminator : "0000"
|
|
289
|
+
}));
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
return computedArray;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/*
|
|
296
|
+
* @param {number} [targetLevel] - Xp required to reach that level.
|
|
297
|
+
*/
|
|
298
|
+
static xpFor (targetLevel) {
|
|
299
|
+
if (isNaN(targetLevel) || isNaN(parseInt(targetLevel, 10))) throw new TypeError("Target level should be a valid number.");
|
|
300
|
+
if (isNaN(targetLevel)) targetLevel = parseInt(targetLevel, 10);
|
|
301
|
+
if (targetLevel < 0) throw new RangeError("Target level should be a positive number.");
|
|
302
|
+
return targetLevel * targetLevel * 100;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* @param {string} [guildId] - Discord guild id.
|
|
307
|
+
*/
|
|
308
|
+
|
|
309
|
+
static async deleteGuild(guildId) {
|
|
310
|
+
if (!guildId) throw new TypeError("A guild id was not provided.");
|
|
311
|
+
|
|
312
|
+
const guild = await levels.findOne({ guildID: guildId });
|
|
313
|
+
if (!guild) return false;
|
|
314
|
+
|
|
315
|
+
await levels.deleteMany({ guildID: guildId }).catch(e => console.log(`Failed to delete guild: ${e}`));
|
|
316
|
+
|
|
317
|
+
return guild;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
module.exports = DiscordXp;
|
package/models/levels.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const mongoose = require("mongoose");
|
|
2
|
+
|
|
3
|
+
const LevelSchema = new mongoose.Schema({
|
|
4
|
+
userID: { type: String },
|
|
5
|
+
guildID: { type: String },
|
|
6
|
+
xp: { type: Number, default: 0 },
|
|
7
|
+
level: { type: Number, default: 0 },
|
|
8
|
+
lastUpdated: { type: Date, default: new Date() }
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
module.exports = mongoose.model('Levels', LevelSchema);
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "discord-xp-fork",
|
|
3
|
+
"version": "1.2.2",
|
|
4
|
+
"description": "A lightweight and easy to use economy framework for discord bots, uses MongoDB.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"discord",
|
|
7
|
+
"economy",
|
|
8
|
+
"discord.js",
|
|
9
|
+
"bot",
|
|
10
|
+
"bots",
|
|
11
|
+
"leveling",
|
|
12
|
+
"levels",
|
|
13
|
+
"discord-levels",
|
|
14
|
+
"discord-xp",
|
|
15
|
+
"xp",
|
|
16
|
+
"mongo",
|
|
17
|
+
"mongoose",
|
|
18
|
+
"mongodb",
|
|
19
|
+
"discord-economy",
|
|
20
|
+
"discord-eco",
|
|
21
|
+
"framework"
|
|
22
|
+
],
|
|
23
|
+
"homepage": "https://codeberg.org/woomy/discord-xp",
|
|
24
|
+
"bugs": {
|
|
25
|
+
"url": "https://codeberg.org/woomy/discord-xp/issues"
|
|
26
|
+
},
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://codeberg.org/woomy/discord-xp"
|
|
30
|
+
},
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"author": "MrAugu, woomyboi",
|
|
33
|
+
"type": "commonjs",
|
|
34
|
+
"main": "index.js",
|
|
35
|
+
"types": "./index.d.ts",
|
|
36
|
+
"directories": {
|
|
37
|
+
"test": "test"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"mongoose": "^8.13.2"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {}
|
|
46
|
+
}
|
package/test/README.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
|
|
2
|
+
# Setting Up
|
|
3
|
+
First things first, we include the module into the project.
|
|
4
|
+
```js
|
|
5
|
+
const Levels = require("discord-xp");
|
|
6
|
+
```
|
|
7
|
+
After that, you need to provide a valid mongo database url, and set it. You can do so by:
|
|
8
|
+
```js
|
|
9
|
+
Levels.setURL("mongodb://..."); // You only need to do this ONCE per process.
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
# Examples
|
|
13
|
+
*Examples assume that you have setted up the module as presented in 'Setting Up' section.*
|
|
14
|
+
*Following examples assume that your `Discord.Client` is called `client`.*
|
|
15
|
+
|
|
16
|
+
*Following examples assume that your `client.on("message", message` is called `message`.*
|
|
17
|
+
|
|
18
|
+
*Following example contains isolated code which you need to integrate in your own command handler.*
|
|
19
|
+
|
|
20
|
+
*Following example assumes that you are able to write asynchronous code (use `await`).*
|
|
21
|
+
|
|
22
|
+
- **Allocating Random XP For Each Message Sent**
|
|
23
|
+
|
|
24
|
+
```js
|
|
25
|
+
client.on("message", async (message) => {
|
|
26
|
+
if (!message.guild) return;
|
|
27
|
+
if (message.author.bot) return;
|
|
28
|
+
|
|
29
|
+
const randomAmountOfXp = Math.floor(Math.random() * 29) + 1; // Min 1, Max 30
|
|
30
|
+
const hasLeveledUp = await Levels.appendXp(message.author.id, message.guild.id, randomAmountOfXp);
|
|
31
|
+
if (hasLeveledUp) {
|
|
32
|
+
const user = await Levels.fetch(message.author.id, message.guild.id);
|
|
33
|
+
message.channel.send(`${message.author}, congratulations! You have leveled up to **${user.level}**. :tada:`);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
- **Rank Command**
|
|
39
|
+
|
|
40
|
+
```js
|
|
41
|
+
const target = message.mentions.users.first() || message.author; // Grab the target.
|
|
42
|
+
|
|
43
|
+
const user = await Levels.fetch(target.id, message.guild.id); // Selects the target from the database.
|
|
44
|
+
|
|
45
|
+
if (!user) return message.channel.send("Seems like this user has not earned any xp so far."); // If there isnt such user in the database, we send a message in general.
|
|
46
|
+
|
|
47
|
+
message.channel.send(`> **${target.tag}** is currently level ${user.level}.`); // We show the level.
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
- **Leaderboard Command**
|
|
51
|
+
|
|
52
|
+
```js
|
|
53
|
+
const rawLeaderboard = await Levels.fetchLeaderboard(message.guild.id, 10); // We grab top 10 users with most xp in the current server.
|
|
54
|
+
|
|
55
|
+
if (rawLeaderboard.length < 1) return reply("Nobody's in leaderboard yet.");
|
|
56
|
+
|
|
57
|
+
const leaderboard = await Levels.computeLeaderboard(client, rawLeaderboard, true); // We process the leaderboard.
|
|
58
|
+
|
|
59
|
+
const lb = leaderboard.map(e => `${e.position}. ${e.username}#${e.discriminator}\nLevel: ${e.level}\nXP: ${e.xp.toLocaleString()}`); // We map the outputs.
|
|
60
|
+
|
|
61
|
+
message.channel.send(`**Leaderboard**:\n\n${lb.join("\n\n")}`);
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
- **Position of a user in the leaderboard**
|
|
65
|
+
```js
|
|
66
|
+
const target = message.mentions.users.first() || message.author; // Grab the target.
|
|
67
|
+
|
|
68
|
+
const user = await Levels.fetch(target.id, message.guild.id, true); // Selects the target from the database.
|
|
69
|
+
|
|
70
|
+
console.log(user.position);
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
- **Canvacord Integration**
|
|
74
|
+
|
|
75
|
+
Obviously you need the npm package `canvacord` for that. Install it with `npm install canvacord`.
|
|
76
|
+
|
|
77
|
+
```js
|
|
78
|
+
const canvacord = require('canvacord');
|
|
79
|
+
|
|
80
|
+
const target = message.mentions.users.first() || message.author; // Grab the target.
|
|
81
|
+
|
|
82
|
+
const user = await Levels.fetch(target.id, message.guild.id, true); // Selects the target from the database.
|
|
83
|
+
|
|
84
|
+
const rank = new canvacord.Rank() // Build the Rank Card
|
|
85
|
+
.setAvatar(target.displayAvatarURL({format: 'png', size: 512}))
|
|
86
|
+
.setCurrentXP(user.xp) // Current User Xp
|
|
87
|
+
.setRequiredXP(Levels.xpFor(user.level + 1)) // We calculate the required Xp for the next level
|
|
88
|
+
.setRank(user.position) // Position of the user on the leaderboard
|
|
89
|
+
.setLevel(user.level) // Current Level of the user
|
|
90
|
+
.setStatus(target.presence.status)
|
|
91
|
+
.setProgressBar("#FFFFFF")
|
|
92
|
+
.setUsername(target.username)
|
|
93
|
+
.setDiscriminator(target.discriminator);
|
|
94
|
+
|
|
95
|
+
rank.build()
|
|
96
|
+
.then(data => {
|
|
97
|
+
const attachment = new Discord.MessageAttachment(data, "RankCard.png");
|
|
98
|
+
message.channel.send(attachment);
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
*It's time for you to get creative..*
|