xp-flow
Version:
A robust and customizable leveling system for Discord.js bots with multi-database support and beautiful rank cards.
229 lines (175 loc) • 7.09 kB
Markdown
# XP-Flow v2.0
XP-Flow is a robust, highly-customizable, and developer-friendly leveling system for Discord.js bots. It's built for performance and simplicity, allowing you to integrate a rich XP and leveling experience into your server in minutes.
## ✨ Key Features
🚀 **Blazing Fast:** Optimized for high-performance bots and large servers.
💾 **Multi-Database Support:** Seamlessly use SQLite, MongoDB, or MySQL.
🎨 **Beautiful Rank Cards:** A powerful and easy-to-use builder for creating stunning, customized rank cards.
📈 **Dynamic Leveling:** The XP required for each level increases dynamically for a balanced progression curve.
🏆 **Leaderboards:** Built-in leaderboard functionality to foster competition.
💻 **Modern API:** A clean, promise-based API that's simple to integrate and works with both message and interaction commands.
## 📦 Installation
Install the package and your preferred database driver.
```bash
# Install the core package
npm install xp-flow
# Install ONE of the following database drivers
npm install sqlite3
# OR
npm install mongoose
# OR
npm install mysql2
```
## 🚀 Quick Start Example
Here is a complete example of a Discord.js v14 bot using xp-flow with both message and slash commands.
See the full example code in `example.js`.
```javascript
// index.js (Your bot's main file)
const { Client, GatewayIntentBits, Partials, EmbedBuilder, AttachmentBuilder } = require('discord.js');
const { LevelingSystem, RankCardBuilder } = require('xp-flow');
require('dotenv').config(); // Use dotenv to manage your bot token
const client = new Client({
intents: [ /* Your intents here */ ]
});
// --- Database Configuration ---
// Choose ONE of the following.
const dbConfig = {
type: 'sqlite',
path: 'database.db'
};
/*
const dbConfig = {
type: 'mongodb',
uri: process.env.MONGO_URI
};
*/
/*
const dbConfig = {
type: 'mysql',
host: 'localhost',
user: 'root',
password: 'password',
database: 'my_database'
};
*/
const leveling = new LevelingSystem({
database: dbConfig,
xp: {
min: 15,
max: 25,
cooldown: 60000
}
});
client.on('ready', () => {
console.log(`Bot is online as ${client.user.tag}!`);
// Register slash commands here
});
// --- XP Handling on Message ---
client.on('messageCreate', async message => {
if (message.author.bot || !message.guild) return;
const xpResult = await leveling.addXp(message.author.id, message.guild.id);
if (xpResult.leveledUp) {
message.channel.send(`🎉 Congratulations, ${message.author}! You've reached level **${xpResult.newLevel}**!`);
}
});
// --- Command Handling ---
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const { commandName } = interaction;
const user = interaction.options.getUser('user') || interaction.user;
if (commandName === 'rank') {
await interaction.deferReply();
const userData = await leveling.getUser(user.id, interaction.guild.id);
const leaderboard = await leveling.getLeaderboard(interaction.guild.id, 100);
const rank = leaderboard.findIndex(u => u.userId === user.id) + 1 || "N/A";
const card = new RankCardBuilder({
username: user.username,
discriminator: user.discriminator,
avatarUrl: user.displayAvatarURL({ extension: 'png' }),
status: interaction.member.presence?.status || 'offline'
})
.setLevel(userData.level)
.setRank(rank)
.setCurrentXp(userData.xp)
.setRequiredXp(leveling.xpForLevel(userData.level))
.setBackgroundColor("#2a2e35")
.setXpBarColor("#5865F2");
const imageBuffer = await leveling.createRankCard(card);
const attachment = new AttachmentBuilder(imageBuffer, { name: 'rank-card.png' });
interaction.editReply({ files: [attachment] });
}
});
client.login(process.env.BOT_TOKEN);
```
## 🎨 Rank Card Customization
The `RankCardBuilder` makes customization incredibly simple and powerful.
```javascript
const { RankCardBuilder } = require('xp-flow');
const card = new RankCardBuilder({
username: user.username,
avatarUrl: user.displayAvatarURL({ extension: 'png' }),
discriminator: user.discriminator
})
// Set Data
.setLevel(10)
.setRank(3)
.setCurrentXp(1500)
.setRequiredXp(2500)
// Set Styles
.setBackgroundImage('https://your.domain/image.png')
.setOverlayColor('rgba(0, 0, 0, 0.7)')
.setPrimaryColor('#FFC107') // Yellow
.setXpBarColor('#FFC107')
.setStatus(member.presence?.status || 'offline'); // online, idle, dnd, offline
// To generate the card:
const imageBuffer = await leveling.createRankCard(card);
```
## RankCardBuilder Methods
- `setLevel(level)`: Sets the user's level.
- `setRank(rank)`: Sets the user's rank.
- `setCurrentXp(xp)`: Sets the user's current XP.
- `setRequiredXp(xp)`: Sets the XP required for the next level.
- `setStatus(status)`: Sets the status ring color (online, idle, dnd, offline).
- `setBackgroundImage(url)`: Sets a custom background image.
- `setBackgroundColor(hex)`: Sets the fallback background color.
- `setOverlayColor(rgba)`: Sets the color and transparency of the main overlay.
- `setPrimaryColor(hex)`: Sets the color for username, rank/level numbers, and XP text.
- `setSecondaryColor(hex)`: Sets the color for the discriminator and rank/level labels.
- `setXpBarColor(hex)`: Sets the color of the XP progress bar fill.
## 📚 API Reference
### `new LevelingSystem(options)`
Initializes the system.
**options.database (Object):** The database configuration.
- `type`: `'sqlite'`, `'mongodb'`, or `'mysql'`.
- Other properties based on type (e.g., `uri` for MongoDB).
**options.xp (Object, optional):** XP gain configuration.
- `min`: Minimum XP per message.
- `max`: Maximum XP per message.
- `cooldown`: Milliseconds between XP gains.
### `leveling.addXp(userId, guildId)`
Adds XP to a user and handles level-ups.
Returns `{ leveledUp: boolean, newLevel: number|null }`.
### `leveling.getUser(userId, guildId)`
Fetches a user's data. Creates a new user if they don't exist.
Returns `{ userId, guildId, xp, level }`.
### `leveling.getLeaderboard(guildId, limit)`
Fetches the server's leaderboard. Returns an array of user objects sorted by rank.
### `leveling.createRankCard(cardBuilder)`
Takes a configured `RankCardBuilder` instance and returns the image Buffer.
### `leveling.xpForLevel(level)`
A utility function to calculate the XP needed to complete a given level.
## Rank Card
Below is an example image illustrating the customization options available for rank cards.

## 🤝 Contributing
Contributions are welcome! Please open an issue or submit a pull request on our GitHub repository.
## 📜 License
This project is licensed under the MIT License.