testsss-akazaz-lib
v0.6.74
Published
๐ NEW: Dashboard System - Web Control Panel! ๐
Readme

Welcome to the ultimate Discord Bot Utilities package! ๐ฅ Boost your Discord bot development with ease, speed, and all-in-one features.
๐ Table of Contents
- ๐ฏ Starter โ Initialize your bot with commands, events, presence, and more.
- โ๏ธ Functions โ Utilities like CreateRow, CreateBar, Wait, and GetUser.
- โก Commands & Events โ Easy setup with cooldowns, permissions, logging, and anti-crash.
- ๐ Dashboard โ Web-based control panel for managing your bot.
๐ฏ STARTER
The starter function is the ultimate initializer for your Discord bot ๐ค. It handles everything from logging in, loading commands/events, setting the bot presence, anti-crash protection, logging commands usage, and even checking for library updates.
Features:
- ๐ ๏ธ One-line loader for both Slash & Prefix commands ๐ฉ
- ๐ Comprehensive terminal info display (commands, events, bot stats) ๐
- ๐งฐ Event handler loader in one line ๐
- โ ๏ธ Anti-crash system with automatic webhook reporting ๐
- ๐ MongoDB connection support ๐ฅ
- ๐ Command logger for both Slash and Prefix commands ๐งญ
- ๐ก Supports custom prefixes per guild and cooldowns โณ
- ๐ผ Automatic update checker for
djs-builder๐ฆ
๐ก Tip: Any option you donโt want, just remove it ๐๏ธ.
const { starter } = require("djs-builder");
const { Client, GatewayIntentBits } = require("discord.js");
const client = new Client({
intents: Object.keys(GatewayIntentBits).map((a) => GatewayIntentBits[a]),
});
// Define starter options
const starterOptions = {
bot: {
token: "YOUR_BOT_TOKEN", // ๐ Discord bot token
ownerId: "YOUR_USER_ID", // ๐ค Bot owner ID
},
terminal: true, // ๐ฅ๏ธ Show bot info in terminal
Status: {
status: "online", // โ
Presence state: online, dnd, idle, offline
activities: ["Game 1", "Game 2"], // ๐ฎ Multiple activities
type: 0, // ๐ญ Activity type: (0=PLAYING, 1=STREAMING, 2=LISTENING, 3=WATCHING)
time: 60000, // โฑ๏ธ Rotate activities every X ms
url: "https://twitch.tv/example", // ๐ Twitch URL (only required for streaming)
},
database: {
url: "mongodb://localhost:27017", // ๐พ MongoDB connection
},
anticrash: {
url: "https://your.crash.webhook.url", // ๐จ Webhook for crash reports
mention_id: "YOUR_USER_ID", // ๐ฃ Optional: mention user on crash
},
// ๐ Dashboard Configuration (Full docs at the end of this page)
dashboard: {
clientID: "YOUR_DISCORD_CLIENT_ID", // ๐ Discord Application Client ID
clientSecret: "YOUR_DISCORD_CLIENT_SECRET", // ๐ Discord Application Client Secret
callbackURL: "http://localhost:3000/auth/discord/callback", // ๐ OAuth2 Callback URL
sessionSecret: "your-super-secret-key", // ๐ Session encryption secret
port: 3000, // ๐ Dashboard port (default: 3000)
},
};
// Start the bot
await starter(client, starterOptions);๐ How Starter Works
1๏ธโฃ Bot Login & Status
- Authenticates the bot using your token ๐.
- Supports multiple rotating activities (e.g.,
Game 1โGame 2โ โฆ) โฑ๏ธ. - Works with all Discord activity types: PLAYING, STREAMING, LISTENING, WATCHING ๐ญ.
- Twitch URL is supported for streaming mode ๐.
2๏ธโฃ Database Connection
- Connects automatically to MongoDB ๐พ.
- Useful for bots with persistent data storage.
3๏ธโฃ Anticrash System
Catches and logs:
unhandledRejectionuncaughtExceptionuncaughtExceptionMonitorunhandledRejectionMonitorwarningโ ๏ธ
Sends error reports to a webhook ๐จ.
Optionally pings the owner ๐ฃ.
4๏ธโฃ Terminal Info
Displays colorful and structured information ๐ฅ๏ธ:
- Bot name, user, guild, and channel counts ๐.
- Owner ID ๐ค.
- Database connection status ๐พ.
- Uptime โณ.
Powered by
cli-table3+chalkfor a professional CLI look ๐จ.
5๏ธโฃ Auto Update Checker
- Monitors new versions of
djs-builderautomatically ๐. - Sends update notifications to the webhook ๐.
6๏ธโฃ Bot Files Information
Access detailed stats about loaded files directly from the client:
- Number of prefix commands โก.
- Number of slash commands โ๏ธ.
- Number of events ๐.
Available via
client.files, useful for debugging or terminal display ๐ ๏ธ.
7๏ธโฃ Dashboard (Web Control Panel)
- Launches a modern web-based control panel for your bot ๐.
- Supports Discord OAuth2 authentication ๐.
- Manage servers, levels, giveaways, and blacklists from the browser ๐๏ธ.
๐ Full Dashboard documentation available at the end of this page โ ๐ DASHBOARD
๐ก Tips
- Flexible: Delete any section you donโt need (anticrash, database, etc.) ๐๏ธ.
- Multi-Status: Add as many activities as you want and let them rotate ๐ฎ.
- Safe by Default: Anticrash system ensures your bot wonโt go down easily ๐ก๏ธ.
- Always Up-to-Date: Automatic update checker keeps your bot running on the latest version โฌ๏ธ.
- Transparent: Quickly check how many files your bot has loaded anytime ๐.
โ๏ธ functions
- Easiest โจ / Fastest โก /Clear ๐งต
Than the discord.js
๐ต CreateRow โ Easily create Discord Action Rows with Buttons & Select Menus โจ
CreateRow is a powerful utility to build Discord Action Rows. It supports:
- Buttons โ
- Select Menus ๐ฏ (
string,role,user,channel) - Advanced options like
defaultValuesandchannelTypes.
๐ Example Usage:
const { CreateRow } = require("djs-builder");
const actionRow = new CreateRow([
//// For each new row, use [] for buttons or {} for a select menu
// ๐น Row #1: Buttons
[
{
id: "button1", // customId for the button
style: 1, // Button styles: Primary(1), Secondary(2), Success(3), Danger(4), Link(5)
label: "Primary Button", // Text shown on button
emoji: "๐", // Emoji displayed
disabled: false, // true = disabled
},
{
id: "button2",
style: 2,
emoji: "๐",
disabled: true, // Button is disabled
},
],
// ๐น Row #2: Select Menu
{
type: "string", // Options: "string" | "role" | "user" | "channel"
options: {
id: "menu1", // customId for the select menu
placeholder: "Select an option",
min: 1, // Minimum selection
max: 2, // Maximum selection
// ๐ธ Data for string select only
data: [
{
name: "Option 1",
id: "opt1",
about: "First option",
icon: "๐",
default: true,
},
{ name: "Option 2", id: "opt2", about: "Second option", icon: "๐" },
{ name: "Option 3", id: "opt3", about: "Third option", icon: "๐" },
],
// ๐ธ Map keys
label: "name", // Which field is the label
value: "id", // Which field is the value
description: "about", // Description for each option
emoji: "icon", // Emoji for each option
// ๐ธ Extra options
disabled: false, // Disable the entire menu
defaultValues: [
// For role/user/channel menus
{ id: "123456789012345678", type: "user" }, // Pre-selected
],
channelTypes: [0, 2], // Only for ChannelSelectMenu (0 = Text, 2 = Voice)
},
},
]);๐ Explanation
๐น Buttons
idโ customId for the buttonstyleโ 1: Primary, 2: Secondary, 3: Success, 4: Danger, 5: Linklabelโ Button textemojiโ Displayed emojidisabledโ true = button is unclickable
๐น Select Menus
typeโ"string" | "user" | "role" | "channel"idโ customId for menuplaceholderโ Text shown before selectionmin/maxโ Min/Max selectable valuesdataโ Options array (for string select only)labelโ Visible textvalueโ Internal valuedescriptionโ Short descriptionemojiโ Option emojidefaultโ Pre-selected option
disabledโ Disable menu completelydefaultValuesโ Pre-selected user/role/channel optionschannelTypesโ Restrict selectable channel types
๐งพ CreateBar โ Text-based Progress Bar for Discord โจ
CreateBar allows you to display a customizable progress bar with optional percentages and partial symbols. Perfect for showing progress, loading, or stats in messages.
๐ Basic Example:
const { CreateBar } = require("djs-builder");
const bar = new CreateBar(7, 10, {
length: 20, // Total length of the bar
fill: "๐", // Filled portion
empty: "๐ค", // Empty portion
partialChar: "๐", // Partial fill
showPercent: true, // Show percentage
left: "โฐ", // Left bracket
right: "โฑ", // Right bracket
});
console.log(bar);
// Output: โฐ๐๐๐๐๐๐๐๐๐ค๐ค๐ค๐ค๐ค๐ค๐ค๐ค๐ค๐คโฑ 70%๐ Another Example with different symbols:
console.log(
CreateBar(3.7, 5, {
fill: "๐ฆ",
empty: "โฌ",
partialChar: "๐จ",
length: 10,
left: "โฐ",
right: "โฑ",
showPercent: true,
})
);
// Output: โฐ๐ฆ๐ฆ๐ฆ๐จโฌโฌโฌโฌโฌโฌโฑ 74%๐ Minimalist example without percentage:
console.log(
CreateBar(4, 8, {
fill: "๐ต",
empty: "โช",
showPercent: false,
})
);
// Output: ๐ต๐ต๐ต๐ตโชโชโชโช๐ Fun Emoji example:
console.log(
CreateBar(6, 10, {
length: 12,
fill: "๐ฅ",
empty: "โ๏ธ",
partialChar: "๐",
showPercent: true,
left: "ยซ",
right: "ยป",
})
);
// Output: ยซ๐ฅ๐ฅ๐ฅ๐ฅ๐ฅ๐ฅ๐โ๏ธโ๏ธโ๏ธโ๏ธยป 60%๐น Options Summary
lengthโ Total number of symbolsfillโ Symbol for filled portionemptyโ Symbol for empty portionpartialCharโ Symbol for partial fill (e.g., half-filled)showPercentโ Show percentage at the endleft/rightโ Brackets or edges for the bar
๐น Notes
- Supports fractional values for partial fill
- Fully customizable with any emoji or character ๐จ
- Great for progress, stats, experience bars, or loading indicators
โฐ Wait โ Await messages, buttons, select menus or modals easily โจ
Wait is a replacement for traditional collectors. It supports:
- Awaiting messages ๐
- Awaiting interactions (buttons / select menus) ๐๏ธ
- Awaiting modal submissions ๐
- Filtering by user and timeout
๐ Example Usage:
const { Wait } = require("djs-builder");
const response = await Wait({
context: message, // Message or Interaction object
userId: message.author.id, // Optional: filter by user
type: "both", // "message" | "interaction" | "both"
time: 30000, // Time in ms
message_Wait: message, // Required if waiting for buttons/selects
});
if (!response) return console.log("โฑ๏ธ Timeout!");
console.log("โ
Collected:", response);๐น Options
contextโ The message or interaction contextuserIdโ Only collect from this user (optional)typeโ"message" | "interaction" | "both"timeโ Timeout in millisecondsmessage_Waitโ Message containing buttons/select menus (for interaction/both type)
๐น Notes
- Supports automatic cleanup of collectors after completion
- Can return Message, Interaction, or ModalSubmitInteraction
๐ค GetUser โ Fetch a GuildMember easily from a message โจ
GetUser helps to detect a target member in multiple ways:
- Mention (
@User) - User ID (
123456789012345678) - Reply to another message
๐ Example Usage:
const { GetUser } = require("djs-builder");
const data = await GetUser(message);
if (!data) return message.reply("โ Could not find the user.");
const member = data.user; // GuildMember object
const args = data.args; // Remaining arguments
const reason = args.join(" ") || "No reason provided";
await member.ban({ reason });
message.reply(`๐ซ ${member.user.tag} was banned for: ${reason}`);๐น Returns
{
user: <GuildMember>, // Targeted member
args: [ "arg1", "arg2" ] // Remaining message arguments
}๐น Detection Methods
- Mention:
!ban @Ahmed Spamming - User ID:
!ban 123456789012345678 Spamming - Reply:
Reply to user's message with !ban
๐น Notes
- Automatically handles missing users
- Returns
nullif user not found - Works in any text channel of the guild
The Logging System is a powerful feature that keeps track of almost everything happening inside your Discord server ๐.
From messages ๐ to channels ๐, roles ๐ญ, invites ๐, and even voice state changes ๐๏ธ โ nothing goes unnoticed!
โจ Features
- ๐ Messages โ Deleted & edited messages are logged with details.
- ๐ Channels โ Creation, deletion, and updates are tracked.
- ๐ญ Roles โ Created, deleted, and updated roles, including member role changes.
- ๐๏ธ Voice State โ Joins, leaves, and moves between channels.
- ๐ Invites โ Created invites & usage tracking.
- ๐ Emojis & Stickers โ Added, removed, or updated.
- ๐จ Audit Log Integration โ Fetches the executor (who did what).
- ๐จ Beautiful Embeds โ Every log is shown in a clean, styled embed with timestamps.
โ๏ธ Setup Example
Using the log function is very simple โก.
Just place this code inside an event (like clientReady) to start logging:
const { log } = require("djs-builder");
module.exports = {
name: "clientReady",
async run(client) {
await log(
client,
"GUILD_ID", // ๐ Guild ID (server)
"CHANNEL_ID" // ๐ข Channel ID for logs
);
},
};๐ก How It Works
- โ Pass your Client, Guild ID, and Log Channel ID.
- ๐ Instantly starts tracking events and sending them to the log channel.
- ๐งฐ No extra setup required โ plug and play!
๐ Level System โ XP, Levels & Leaderboard
The Level System module lets you track user experience points (XP) in text ๐ฌ and voice ๐๏ธ, handle level-ups โฌ๏ธ, and display leaderboards ๐ . Perfect for gamifying your Discord server! ๐ฎโจ
Note: To use this module, you MUST have DATABASE conection. | Note 2: You can get all data by requiring the Level module.
๐ฆ Module Exports
const { addXP, UserLevel, leaderboard } = require("djs-builder");addXP(userId, guildId, options)โ Adds XP for a user and handles level-ups ๐ฒ.UserLevel(userId, guildId)โ Fetch a user's XP and level ๐ค.leaderboard(guildId, type, limit)โ Get top users ๐ .
๐ฒ addXP โ Add Experience Points
Adds XP to a user and automatically handles level-ups.
const result = await addXP("USER_ID", "GUILD_ID", {
type: "text", // "text" ๐ฌ | "voice" ๐๏ธ
minXP: 5, // Minimum random XP ๐ข
maxXP: 15, // Maximum random XP ๐ต
amount_add: 10, // Optional: fixed XP ๐
level_add: 1, // Optional: direct level boost โฌ๏ธ
});
console.log(result);
/* Example output:
{
newLevel: 3,
oldLevel: 2,
totalXP: 250,
leveledUp: true
}
*/๐งโ๐คโ๐ง UserLevel โ Fetch User Data
Fetch a user's text XP, voice XP, total XP, and current level.
const data = await UserLevel("USER_ID", "GUILD_ID");
console.log(data);
/* Example output:
{
text: 120 ๐ฌ,
voice: 50 ๐๏ธ,
totalXP: 170 โญ,
level: 2 โฌ๏ธ
}
*/Returns default values if the user is not found.
๐ Leaderboard โ Top Users
Get a sorted list of users based on XP or level.
const topUsers = await leaderboard("GUILD_ID", "totalXP", 5);
console.log(topUsers);
/* Example output:
[
{ userId: "123", totalXP: 500, level: 5 },
{ userId: "456", totalXP: 400, level: 4 },
...
]
*/Parameters:
guildIdโ Server ID ๐typeโ"totalXP","text"๐ฌ,"voice"๐๏ธ, or"level"โฌ๏ธ. Default ="totalXP"limitโ Number of top users to return ๐ข. Default = 10
โก Practical Example: messageCreate Event
const { addXP, UserLevel, leaderboard } = require("djs-builder");
module.exports = {
name: "messageCreate",
run: async (msg, client) => {
if (msg.author.bot) return;
// ๐ฒ Add XP on every message
const result = await addXP(msg.author.id, msg.guild.id, {
type: "text",
minXP: 5,
maxXP: 15,
});
// ๐ Level-up notification
if (result.leveledUp) {
msg.channel.send(`๐ ${msg.author} new level **${result.newLevel}** โฌ๏ธ`);
}
// ๐ Check your rank
if (msg.content === "!rank") {
const data = await UserLevel(msg.author.id, msg.guild.id);
msg.reply(`๐ **level ** ${data.level} โฌ๏ธ โ **XP:** ${data.totalXP} โญ`);
}
// ๐
Display top users
if (msg.content === "!top") {
const lb = await leaderboard(msg.guild.id, "totalXP", 5);
msg.reply(
lb
.map(
(u, i) =>
`#${i + 1} <@${u.userId}> โ Lv.${u.level} โฌ๏ธ (${u.totalXP} โญ)`
)
.join("\n")
);
}
},
};๐ก Notes & Tips
- ๐ฌ Text XP โ Add XP for messages automatically.
- ๐๏ธ Voice XP โ Add XP for voice activity.
- โฌ๏ธ Level Up โ Trigger notifications when leveling up.
- ๐ Leaderboard โ Display the top users in server using embeds for better look.
- ๐ฎ Gamify your server easily with XP rewards, mini-games, and custom commands.
๐ Giveaway System โ All-in-One Contest Management ๐โจ
This module provides a robust and feature-rich suite of functions to effortlessly launch, monitor, manage, and conclude Giveaways on your Discord server. It fully supports both Reactions and Buttons for entry, featuring advanced controls like pausing, resuming, and rerolling winners. It is highly recommended to read the Important Notes section below. ๐จ
Note: To use this module, you MUST have DATABASE conection. | Note 2: You can get all data by requiring the giveaway module.
๐ฆ Module Exports
const {
Gstart,
Gcheck,
Greroll,
Glist,
Gpause,
Gresume,
Gdelete,
GaddUser,
GremoveUser,
GaddTime,
GremoveTime,
Gdata,
} = require("djs-builder");๐ฌ Gstart โ Launch a Brand New Giveaway! ๐
This is the primary function to kick off a new giveaway. It handles creating the Discord message and persists all necessary data in the database (MongoDB). This function offers deep customization for embeds and entry methods. ๐จ
โ๏ธ Essential Options:
context: The Message or Interaction object that triggered the command.endTime: The duration until the giveaway ends (in milliseconds โฑ๏ธ).winers: The number of winners for the contest. ๐channelId: The ID of the channel where the giveaway message will be posted. ๐ขembed/endEmbed: Options to fully customize the starting message and the final end message.reaction: To specify the entry method (buttonorreaction). ๐ฑ๏ธ
โก Simple Usage Example (Basic Requirements Only):
This example provides a fast and minimalist way to start a giveaway with default embed colors, a simple title, and the default reaction entry type (if the reaction object is omitted or set to reaction).
const { Gstart } = require("djs-builder");
module.exports = {
name: "gstart",
description: "Starts a new simple giveaway.",
run: async (client, message, args) => {
// โฐ Giveaway ends in 1 hour
const oneHour = 60 * 60 * 1000;
const channelId = message.channel.id;
await Gstart({
context: message,
endTime: oneHour,
winers: 1,
channelId: channelId,
embed: {
title: "๐ Simple Test Giveaway",
description: "React to enter! Prize: Discord Nitro.",
},
});
message.reply("๐ Simple Giveaway started successfully!");
},
};๐ก Tip: This example provides a fast and minimalist way to start a giveaway with the default reaction type (emoji reaction).
โก Full Customization Example (Demonstrating all options):
This example showcases all available configuration options for deep customization of the embeds and the button entry method.
const { Gstart } = require("djs-builder");
const { EmbedBuilder } = require("discord.js");
module.exports = {
ย name: "gstart",
ย description: "Starts a new highly-customized giveaway.",
ย run: async (client, message, args) => {
ย ย // โฐ Giveaway ends in 48 hours
const twoDays = Date.now() + (48 * 60 * 60 * 1000);
const channelId = 'YOUR_GIVEAWAY_CHANNEL_ID'; // ๐ข Target Channel
ย ย await Gstart({
ย ย ย context: message,
ย ย ย endTime: twoDays,
ย ย ย winers: 5, // 5 lucky winners! ๐
ย ย ย channelId: channelId,
// ๐จ Customization for the STARTING EMBED
ย ย ย embed: {
custom: new EmbedBuilder().setTitle("Raw Embed"),// ๐ก You can use 'custom' to pass a raw Discord.js EmbedBuilder JSON
ย ย ย ย ย ย title: "๐ **HUGE SERVER BOOST GIVEAWAY!**",
ย ย ย ย ย ย description: "Click the button below to enter for a chance to win a free server boost!",
ย ย ย ย ย ย color: "Blue", // Any valid Discord color
image: "https://yourimage.com/banner.png", // image URL
ย ย ย ย ย ย thumbnail: message.guild.iconURL(),
ย ย ย },
// ๐ Customization for the ENDED EMBED
ย ย ย endEmbed: {
custom: new EmbedBuilder().setTitle("Raw Embed"),// ๐ก You can use 'custom' to pass a raw Discord.js EmbedBuilder JSON
ย ย ย ย ย ย title: "๐ Giveaway Has Concluded!",
ย ย ย ย ย ย description: "Congratulations to the winners! Check the message below.",
ย ย ย ย ย ย color: "Green",
ย ย ย ย ย ย // Eimage and Ethumbnail can also be set here
ย ย ย },
// ๐ฑ๏ธ Button Entry Method
ย ย ย reaction: {
ย ย ย ย type: "button", // Use 'reaction' for an emoji reaction
ย ย ย ย emoji: "โ
", // The emoji displayed on the button
ย ย ย ย label: "Enter Giveaway!", // The text label
ย ย ย ย style: 3, // Button style: Primary(1), Secondary(2), Success(3), Danger(4)
ย ย ย ย id: "djs-builder-giveaway", // Custom ID for the button
ย ย ย },
// ๐ Requirements (Optional)
requirements: {
requiredRoles: ["123456789012345678"], // ๐ก๏ธ User MUST have this role to join (Button Only)
},
ย ย });
ย ย message.reply("๐ Giveaway started successfully!");
ย },
};๐ก Flexibility Tip: You can safely remove any option you do not wish to use (e.g., remove
endEmbedentirely if you are happy with the default end message structure). ๐๏ธ
โ ๏ธ Important Notes โ Read Before Use! ๐จ
This module requires specific setup steps to function correctly. Pay attention to the following crucial points:
1. The Gcheck Requirement (Monitor):
- The
Gcheck(client)function is responsible for monitoring and ending the giveaways once their time runs out. - Failure to call
Gcheck(client)when your bot starts (e.g., in theclientReadyevent) will result in giveaways never ending automatically! ๐
- The
2. Button Entry vs. InteractionCreate:
- If you set
reaction.typetobuttoninGstart, the system will create the button but will NOT automatically register the participants. - You MUST manually implement a listener for the
interactionCreateevent and use theGaddUserfunction to register the user entry when the button is clicked. ๐ฑ๏ธ - See the
GaddUsersection for a detailed code example.
- If you set
3. Requirements (Roles):
- The
requiredRolesfeature currently works ONLY with the Button entry method (reaction.type: "button"). - When using
GaddUser, you must pass theguildobject as the third argument for the role check to work.
- The
๐ Gcheck โ Monitor and End Time-Expired Giveaways ๐
This function runs periodically (every 10 seconds โฑ๏ธ) to check all active, non-paused giveaways. It automatically concludes contests that have passed their endTime. This function must be called once when the bot starts up. ๐
โก Simple Example (in your clientReady event):
const { Gcheck } = require("djs-builder");
module.exports = {
name: "clientReady",
once: true,
run: (client) => {
console.log(`๐ค Bot is ready and monitoring giveaways...`);
Gcheck(client); // ๐ Start the continuous check loop!
},
};๐ Greroll โ Redraw Winners for an Ended Contest ๐ฒ
Used to redraw one or more new winners for a completed giveaway. It sends a new announcement message with the updated winners.
โ๏ธ Options:
client: The Discord Client object. ๐คmessageId: The Message ID of the giveaway post. ๐
โก Simple Example:
const { Greroll } = require("djs-builder");
module.exports = {
name: "reroll",
description: "Redraws winners for an ended giveaway.",
Permissions: ["MANAGE_MESSAGES"], // ๐ก๏ธ Permission check
run: async (client, message, args) => {
const id = args[0];
if (!id)
return message.reply(
"โ **Error:** Please provide the Giveaway Message ID."
);
const result = await Greroll(client, id);
if (result?.error) {
return message.reply(`โ ๏ธ **Reroll Failed:** ${result.error}`);
} else {
message.reply(`โ
**Success!** Reroll initiated for giveaway \`${id}\`.`);
}
},
};๐ Glist โ Retrieve List of Giveaways ๐
Fetches a list of all saved giveaways based on their current status.
โ๏ธ Options:
type: Can beended,active,paused, orall. ๐
โก Simple Example:
const { Glist } = require("djs-builder");
// Retrieve all currently active (non-paused, non-ended) giveaways
const activeGiveaways = await Glist("active");
if (activeGiveaways.length > 0) {
console.log(`โ
Found ${activeGiveaways.length} Active Giveaways.`); // ... You can format and display this list to the user
} else {
console.log("No active giveaways found.");
}โธ๏ธ Gpause & โถ๏ธ Gresume โ Stop and Continue Contests ๐
Allows you to temporarily halt an ongoing giveaway, preserving the remaining time, and then resume it later. The message embed is automatically updated to reflect the pause/resume status.
โ๏ธ Options:
client: The Discord Client object. ๐คmessageId: The Message ID of the giveaway post. ๐
โก Simple Example (for a management command):
const { Gpause, Gresume } = require("djs-builder");
module.exports = {
name: "g_manage",
description: "Pause or resume a giveaway.",
devOnly: true, // ๐ Developer only access
run: async (client, message, args) => {
const [action, id] = args;
if (!action || !id) return message.reply("โ ๏ธ Missing action or ID.");
if (action === "pause") {
const result = await Gpause(client, id);
if (result?.error) return message.reply(`โ ${result.error}`);
message.reply("โธ๏ธ Giveaway successfully **paused**!");
} else if (action === "resume") {
const result = await Gresume(client, id);
if (result?.error) return message.reply(`โ ${result.error}`);
message.reply("โถ๏ธ Giveaway successfully **resumed**!");
}
},
};๐๏ธ Gdelete โ Permanently Remove Giveaway Data ๐๏ธ
Deletes the giveaway record entirely from the database. Note: This does not delete the Discord message itself, only the data.
โ๏ธ Options:
messageId: The Message ID of the giveaway post. ๐
โก Simple Example:
const { Gdelete } = require("djs-builder");
module.exports = {
name: "gdelete",
run: async (client, message, args) => {
const messageId = args[0];
const result = await Gdelete(messageId);
if (result?.delete) {
message.reply(
`โ
**Success:** Giveaway data for \`${messageId}\` has been permanently deleted.`
);
} else {
message.reply(
`โ **Error:** ${result?.error || "Could not delete giveaway data."}`
);
}
},
};โ GaddUser & โ GremoveUser โ Manual Participant Control ๐งโ๐คโ๐ง
These functions allow you to manually add or remove user IDs from the participant list. This is crucial when setting the giveaway reaction type to button.
โ๏ธ Options:
messageId: The Message ID of the giveaway. ๐userId: The ID of the user to add/remove. ๐ค
๐ก InteractionCreate Setup (for Button Entry) ๐ฑ๏ธ
When using the button type, you MUST implement the following listener to handle join/leave actions dynamically.
โก Example Code for Dynamic Join/Leave in interactionCreate Event:
const { GaddUser, GremoveUser, CreateRow } = require("djs-builder");
module.exports = {
name: "interactionCreate",
run: async (interaction) => {
// 1. Handle Join/Entry Button Click
if (interaction.customId === "djs-builder-giveaway") {
// โ ๏ธ Note: Pass 'interaction.guild' as the 3rd argument to enable Role Requirements check!
const result = await GaddUser(
interaction.message.id,
interaction.user.id,
interaction.guild
);
if (result?.error) {
// Handles both "User Already Joined" and "Missing Roles" errors
if (result.error === "โ User Already Joined") {
// ... (Leave button logic)
const row = await CreateRow([
[
{
label: "Leave Giveaway",
id: "djs-builder-giveaway-leave-" + interaction.message.id, // Dynamic ID
style: 4, // Danger Red
},
],
]);
return interaction.reply({
content: "โ ๏ธ You have **already joined** this giveaway! You can **leave** by clicking the button below.",
components: row,
flags: 64,
});
}
// Show error (e.g. Missing Role)
return interaction.reply({
content: result.error,
flags: 64
});
}
await interaction.reply({
content: "๐ **Success!** Your entry has been registered!",
flags: 64,
});
}
// 2. Handle Leave Button Click (Dynamically Generated ID)
if (
interaction.customId &&
interaction.customId.startsWith("djs-builder-giveaway-leave-")
) {
const id = interaction.customId.split("-")[4]; // Extract message ID
const result = await GremoveUser(id, interaction.user.id);
// Note: The error message should ideally reflect the module's logic (User Not Joined)
if (result?.error && result.error.includes("User Not Joined")) {
return interaction.reply({
content: "โ ๏ธ You have **already left** this giveaway!",
flags: 64,
});
}
await interaction.reply({
content: "๐ **Success!** Your entry has been removed!",
flags: 64,
});
}
},
};โ GaddTime & โ GremoveTime โ Adjust the End Time ๐ฐ๏ธ
Allows you to extend or shorten the duration of an active giveaway.
โ๏ธ Options:
messageId: The Message ID of the giveaway. ๐client: The Discord Client object. ๐คtime: The amount of time (in milliseconds โณ) to add or remove.
โก Simple Example (Extending the Giveaway):
const { GaddTime } = require("djs-builder");
// Extend the contest by 30 minutes (1,800,000 MS)
const halfHour = 30 * 60 * 1000;
const result = await GaddTime(messageId, client, halfHour);
if (result?.error) {
console.log(`Error adding time: ${result.error}`);
} else {
console.log("Time successfully added!");
}๐ Gdata โ Retrieve Giveaway Data ๐พ
Fetches all saved data for a specific giveaway message.
โ๏ธ Options:
messageId: The Message ID of the giveaway. ๐
โก Simple Example:
const { Gdata } = require("djs-builder");
const giveawayData = await Gdata(messageId);
if (giveawayData) {
console.log(`Giveaway hosted by: <@${giveawayData.hoster}>`);
console.log(`Current status: ${giveawayData.ended ? "Ended" : "Active"}`);
} else {
console.log("No data found for this message ID.");
}๐ Gdata(messageId) โ Returned Object Structure
- Returns an object like:
{
ย "_id": "651234567890abcdef12345678", // ๐ MongoDB unique ID
ย "ended": false, // ๐ก Current status of the giveaway
ย "guildId": "123456789012345678", // ๐ Server ID
ย "channelId": "876543210987654321", // ๐ข Channel ID
ย "messageId": "987654321098765432", // ๐ฌ Message ID of the giveaway post
ย "hoster": "112233445566778899", // ๐ค User ID of the giveaway host
"prize" : "code" // ๐ prize
ย "winnerCount": 1, // ๐ข Number of winners set
ย "winners": [], // ๐ Array of user IDs who won (empty if not ended)
ย "paused": false, // โธ๏ธ True if the giveaway is paused
ย "pausedTime": [], // โฑ๏ธ Array of saved remaining times (used for resume)
ย "endTime": "1730995200000", // ๐
Timestamp (MS) of when the giveaway should end
ย "endType": "Time End", // ๐ How the giveaway ended (e.g., Time End, Reroll: 1 time(s))
ย "reaction": "button", // ๐ฑ๏ธ Entry method: "reaction" or "button"
ย "users": ["111111111111111111", "222222222222222222"], // ๐งโ๐คโ๐ง Array of user IDs who entered (used for button type)
ย "endEmbed": {
ย ย "title": "๐ Giveaway Has Concluded!",
ย ย "description": "Congratulations to the winners!",
ย ย "color": 3066993, // Green color code
ย ย "fields": [
ย ย ย {
ย ย ย ย "name": "๐ Giveaway",
ย ย ย ย "value": "- Winner(s): 1\n- Time : <t:1730995200:R>\n- Hosted By : <@112233445566778899>",
ย ย ย ย "inline": true
ย ย ย }
ย ย ]
ย },
ย "__v": 0 // ๐ Mongoose version key (internal)
}๐ก General Code Example โ The All-in-One /giveaway Command ๐ ๏ธ
This complete example demonstrates how to integrate all functions of the Giveaway System into a single Discord Slash Command, /giveaway, using subcommands for clean management.
const {
Gstart,
Greroll,
Glist,
Gpause,
Gresume,
Gdelete,
GaddUser,
GremoveUser,
GaddTime,
GremoveTime,
Gdata,
} = require("djs-builder");
const {
SlashCommandBuilder,
EmbedBuilder,
AttachmentBuilder,
PermissionFlagsBits,
} = require("discord.js");
const ms = require("ms");
module.exports = {
data: new SlashCommandBuilder()
.setName("giveaway")
.setDescription("Comprehensive giveaway system management")
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
// ๐ฌ /giveaway start
.addSubcommand((subcommand) =>
subcommand
.setName("start")
.setDescription("Starts a new giveaway")
.addStringOption((option) =>
option
.setName("prize")
.setDescription("The prize for the winner(s)")
.setRequired(true)
)
.addStringOption((option) =>
option
.setName("time")
.setDescription("Duration (e.g., 1h, 30m, 7d)")
.setRequired(true)
)
.addStringOption((option) =>
option
.setName("winner")
.setDescription("Number of winners (e.g., 1, 3)")
.setRequired(true)
)
.addChannelOption((option) =>
option
.setName("channel")
.setDescription("The channel to post the giveaway in")
)
.addStringOption((option) =>
option
.setName("description")
.setDescription("Custom description for the giveaway embed")
)
.addStringOption((option) =>
option
.setName("image")
.setDescription("Image URL for the embed banner")
)
.addStringOption((option) =>
option
.setName("thumbnail")
.setDescription("Thumbnail URL for the embed")
)
)
// ๐ Management Commands: /giveaway reroll, pause, resume, delete, data
.addSubcommand((subcommand) =>
subcommand
.setName("reroll")
.setDescription("Redraw winners for an ended giveaway")
.addStringOption((option) =>
option
.setName("id")
.setDescription("Giveaway message ID")
.setRequired(true)
)
)
.addSubcommand((subcommand) =>
subcommand
.setName("pause")
.setDescription("Pause an active giveaway")
.addStringOption((option) =>
option
.setName("id")
.setDescription("Giveaway message ID")
.setRequired(true)
)
)
.addSubcommand((subcommand) =>
subcommand
.setName("resume")
.setDescription("Resume a paused giveaway")
.addStringOption((option) =>
option
.setName("id")
.setDescription("Giveaway message ID")
.setRequired(true)
)
)
.addSubcommand((subcommand) =>
subcommand
.setName("delete")
.setDescription("Delete a giveaway's data")
.addStringOption((option) =>
option
.setName("id")
.setDescription("Giveaway message ID")
.setRequired(true)
)
)
.addSubcommand((subcommand) =>
subcommand
.setName("data")
.setDescription("Get raw data for a giveaway")
.addStringOption((option) =>
option
.setName("id")
.setDescription("Giveaway message ID")
.setRequired(true)
)
)
// ๐งโ๐คโ๐ง User Entry Management: /giveaway adduser, removeuser
.addSubcommand((subcommand) =>
subcommand
.setName("adduser")
.setDescription("Manually add user to giveaway (button entry only)")
.addStringOption((option) =>
option
.setName("id")
.setDescription("Giveaway message ID")
.setRequired(true)
)
.addUserOption((option) =>
option.setName("user").setDescription("User to add").setRequired(true)
)
)
.addSubcommand((subcommand) =>
subcommand
.setName("removeuser")
.setDescription(
"Manually remove user from giveaway (button entry only)"
)
.addStringOption((option) =>
option
.setName("id")
.setDescription("Giveaway message ID")
.setRequired(true)
)
.addUserOption((option) =>
option
.setName("user")
.setDescription("User to remove")
.setRequired(true)
)
)
// โฑ๏ธ Time Modification: /giveaway addtime, removetime
.addSubcommand((subcommand) =>
subcommand
.setName("addtime")
.setDescription("Add time to an active giveaway")
.addStringOption((option) =>
option
.setName("id")
.setDescription("Giveaway message ID")
.setRequired(true)
)
.addStringOption((option) =>
option
.setName("time")
.setDescription("Time to add (e.g., 30m, 1h)")
.setRequired(true)
)
)
.addSubcommand((subcommand) =>
subcommand
.setName("removetime")
.setDescription("Remove time from an active giveaway")
.addStringOption((option) =>
option
.setName("id")
.setDescription("Giveaway message ID")
.setRequired(true)
)
.addStringOption((option) =>
option
.setName("time")
.setDescription("Time to remove (e.g., 10m)")
.setRequired(true)
)
)
// ๐ giveaways list
.addSubcommand((subcommand) =>
subcommand
.setName("list")
.setDescription("List giveaways")
.addStringOption((option) =>
option
.setName("type")
.setDescription("Type of giveaways to list")
.setRequired(true)
.addChoices(
{ name: "Ended", value: "ended" },
{ name: "Active", value: "active" },
{ name: "Paused", value: "paused" },
{ name: "All", value: "all" }
)
)
),
// โ๏ธ Command Execution
run: async (interaction, client) => {
await interaction.deferReply({ flags: 64 }); // Acknowledge command immediately
const command = interaction.options.getSubcommand();
const id = interaction.options.getString("id");
if (command === "start") {
// ๐ START LOGIC
const channel =
interaction.options.getChannel("channel") || interaction.channel;
const description = interaction.options.getString("description");
const image = interaction.options.getString("image");
const thumbnail = interaction.options.getString("thumbnail");
const timeString = interaction.options.getString("time");
const winnerCount = parseInt(interaction.options.getString("winner"));
const prize = interaction.options.getString("prize");
const durationMs = ms(timeString);
const endTimeMs = Date.now() + durationMs;
if (!durationMs) {
return interaction.editReply(
"โ **Error:** Invalid time format provided (e.g., 1h, 30m)."
);
}
if (isNaN(winnerCount) || winnerCount < 1) {
return interaction.editReply(
"โ **Error:** Winner count must be a number greater than 0."
);
}
const giveaway = await Gstart({
context: interaction,
channelId: channel.id,
winers: winnerCount,
endTime: endTimeMs,
prize : prize,
embed: {
title: `๐ ${prize} Giveaway!`,
image: image,
thumbnail: thumbnail,
description: description,
},
reaction: {
type: "button",
label: "Enter Giveaway",
style: 1,
emoji: "๐",
},
});
if (giveaway?.error) {
return interaction.editReply(`โ **Error:** ${giveaway.error}`);
}
return interaction.editReply(
`โ
**Success!** Giveaway for **${prize}** has been started in ${channel}!`
);
} else if (command === "list") {
// ๐ LIST LOGIC
const type = interaction.options.getString("type");
const giveaways = await Glist(type);
const MAX_EMBED_LENGTH = 4000;
const MAX_MESSAGE_LENGTH = 2000;
if (!giveaways || giveaways.length === 0) {
return interaction.editReply(`โ No **${type}** giveaways found.`);
}
const listContent = giveaways
.map(
(g, i) =>
`**#${i + 1}** | ID: \`${g.messageId}\` | Hoster: <@${
g.hoster
}> | End: <t:${Math.floor(g.endTime / 1000)}:R>`
)
.join("\n");
const title = `๐ **${type.toUpperCase()} Giveaways:** (${
giveaways.length
} found)`;
if (listContent.length <= MAX_MESSAGE_LENGTH) {
// Output as a simple message (Under 2000 chars)
return interaction.editReply({
content: `${title}\n\n${listContent}`,
});
} else if (listContent.length <= MAX_EMBED_LENGTH) {
// Output as an Embed (Over 2000, under 4000)
const embed = new EmbedBuilder()
.setTitle(title.replace(/\*\*/g, ""))
.setDescription(listContent)
.setColor("Blue");
return interaction.editReply({
content: `Too many results for a single message, displaying via Embed.`,
embeds: [embed],
});
} else {
// Output as an attachment/JSON file (Over 4000 chars)
const jsonFile = new AttachmentBuilder(
Buffer.from(JSON.stringify(giveaways, null, 2)),
{ name: `${type}_giveaways_list.json` }
);
return interaction.editReply({
content: `โ ๏ธ **Warning:** The list is too long! Sending ${giveaways.length} results in a JSON file.`,
files: [jsonFile],
});
}
} else if (command === "pause") {
// โธ๏ธ PAUSE LOGIC
const result = await Gpause(client, id);
if (result?.error)
return interaction.editReply(`โ **Error:** ${result.error}`);
return interaction.editReply(
`โธ๏ธ Giveaway \`${id}\` paused successfully!`
);
} else if (command === "resume") {
// โถ๏ธ RESUME LOGIC
const result = await Gresume(client, id);
if (result?.error)
return interaction.editReply(`โ **Error:** ${result.error}`);
return interaction.editReply(
`โถ๏ธ Giveaway \`${id}\` resumed successfully!`
);
} else if (command === "reroll") {
// ๐ REROLL LOGIC
const result = await Greroll(client, id);
if (result?.error)
return interaction.editReply(`โ **Error:** ${result.error}`);
return interaction.editReply(
`๐ Reroll command sent for giveaway \`${id}\`! Check the channel for the new winner.`
);
} else if (command === "delete") {
// ๐๏ธ DELETE LOGIC
const result = await Gdelete(id);
if (result?.error)
return interaction.editReply(`โ **Error:** ${result.error}`);
return interaction.editReply(
`๐๏ธ Giveaway data for \`${id}\` deleted successfully!`
);
// โ USER MANAGEMENT LOGIC
} else if (command === "adduser") {
const user = interaction.options.getUser("user");
const result = await GaddUser(id, user.id);
if (result?.error)
return interaction.editReply(`โ **Error:** ${result.error}`);
return interaction.editReply(
`โ User **${user.tag}** added to giveaway \`${id}\`.`
);
} else if (command === "removeuser") {
// โ REMOVE USER LOGIC
const user = interaction.options.getUser("user");
const result = await GremoveUser(id, user.id);
if (result?.error)
return interaction.editReply(`โ **Error:** ${result.error}`);
return interaction.editReply(
`โ User **${user.tag}** removed from giveaway \`${id}\`.`
);
// โณ TIME MANAGEMENT LOGIC
} else if (command === "addtime") {
const timeString = interaction.options.getString("time");
const timeMs = ms(timeString);
if (!timeMs) {
return interaction.editReply(
"โ **Error:** Invalid time format provided (e.g., 1h, 30m)."
);
}
const result = await GaddTime(id, client, timeMs);
if (result?.error)
return interaction.editReply(`โ **Error:** ${result.error}`);
return interaction.editReply(
`โฑ๏ธ Added ${timeString} to giveaway \`${id}\`.`
);
} else if (command === "removetime") {
// โช REMOVE TIME LOGIC
const timeString = interaction.options.getString("time");
const timeMs = ms(timeString);
if (!timeMs) {
return interaction.editReply(
"โ **Error:** Invalid time format provided (e.g., 1h, 30m)."
);
}
const result = await GremoveTime(id, client, timeMs);
if (result?.error)
return interaction.editReply(`โ **Error:** ${result.error}`);
return interaction.editReply(
`โฑ๏ธ Removed ${timeString} from giveaway \`${id}\`.`
);
// ๐ DATA LOGIC
} else if (command === "data") {
const id = interaction.options.getString("id");
console.log(id);
const data = await Gdata(id);
if (data?.error)
return interaction.editReply(`โ **Error:** ${data.error}`);
const giveawayEmbed = new EmbedBuilder()
.setTitle(`๐ Giveaway Data: ${id}`)
.setColor(data.ended ? 0xff0000 : data.paused ? 0xffc0cb : 0x00ff00)
.setDescription(
`**Jump to Message ๐ ** : ${
data.messageId
? `https://discord.com/channels/${data.guildId}/${data.channelId}/${data.messageId}`
: "N/A"
}`
);
giveawayEmbed.addFields(
{
name: "โจ Status",
value: data.ended
? "ENDED ๐"
: data.paused
? "PAUSED โธ๏ธ"
: "ACTIVE โ
",
inline: true,
},
{
name: "๐ Winners",
value: data.winwesNumber.toString(),
inline: true,
},
{
name: "๐โโ๏ธ Hoster",
value: `<@${data.hoster}>`,
inline: true,
},
{
name: "โณ Ends In",
value: `<t:${Math.floor(data.endTime / 1000)}:R>`,
inline: true,
},
{
name: "๐๏ธ Entries",
value:
data.reaction === "button"
? data.users.length.toString()
: "N/A (Reaction Type)",
inline: true,
},
{
name: "๐ฑ๏ธ Entry Type",
value: data.reaction.toUpperCase(),
inline: true,
}
);
if (data.ended && data.winers.length > 0) {
giveawayEmbed.addFields({
name: "๐
Past Winners",
value: data.winers.map((u) => `<@${u}>`).join(", ") || "N/A",
inline: false,
});
}
return interaction.editReply({
embeds: [giveawayEmbed],
content: `Data retrieved for giveaway \`${id}\`.`,
});
}
},
};๐ Final Improvements and Notes: โจ๐
1. Time Parsing via
ms: โฐโณ- for time inputs (e.g.,
1h,30m) to be correctly converted into milliseconds.
- for time inputs (e.g.,
2. List Command Robustness: ๐๐ก๏ธ
- The
listcommand logic handles large result sets automatically to avoid the Discord 2000-character limit error:- Under 2000 characters: Sent as a direct, formatted message.
- Between 2000 and 4000 characters: Sent inside an EmbedBuilder.
- Over 4000 characters: Sent as a JSON attachment, preventing API errors.
- The
3. Function Call Integrity: โ๏ธโ
- The
clientobject is correctly passed toGaddTimeandGremoveTime(id, client, timeMs), meeting the module's requirements for management functions.
- The
4. Enhanced User Experience (UX): ๐ฏ๐
- The
channeloption uses.addChannelOption()for a native Discord selector. - Validation is included for
winnerCountand time formats. ๐ซ
- The
5. Private and Immediate Feedback: ๐๐ฌ
- Uses
interaction.deferReply({ flags: 64 })(ephemeral/private) andinteraction.editReply()for fast, clean, and non-intrusive status updates.
- Uses
๐ซ Blacklist System โ Restrict Access to Commands
The Blacklist System allows you to block specific users, roles, or channels from using your bot's commands. This is useful for moderation and preventing abuse.
Note 1: To use this module, you MUST have DATABASE connection. | Note 2: You can get all data by requiring the Blacklist module.
๐ฆ Module Exports
const {
isBlacklisted,
addToBlacklist,
removeFromBlacklist,
getBlacklist,
Blacklist,
} = require("djs-builder");isBlacklisted(guildId, type, id)โ Check if a target is blacklisted ๐.addToBlacklist(guildId, type, id)โ Add a target to the blacklist โ.removeFromBlacklist(guildId, type, id)โ Remove a target from the blacklist โ.getBlacklist(guildId, type)โ Get all blacklisted items (optionally filtered by type) ๐.Blacklistโ The Mongoose model for direct DB access ๐พ.
๐ isBlacklisted โ Check Status
Checks if a user, role, or channel is blacklisted.
const isBlocked = await isBlacklisted("GUILD_ID", "user", "USER_ID");
if (isBlocked) {
console.log("User is blacklisted! ๐ซ");
}โ addToBlacklist โ Block a Target
Adds a user, role, or channel to the blacklist.
await addToBlacklist("GUILD_ID", "channel", "CHANNEL_ID");
console.log("Channel blacklisted successfully! ๐");โ removeFromBlacklist โ Unblock a Target
Removes a user, role, or channel from the blacklist.
await removeFromBlacklist("GUILD_ID", "role", "ROLE_ID");
console.log("Role unblacklisted! ๐");๐ getBlacklist โ List Blacklisted Items
Returns an array of blacklisted items for a guild. You can optionally filter by type (user, role, channel).
Parameters:
guildId(String): The ID of the guild.type(String, optional): The type to filter by (user,role,channel).
Example:
// Get all blacklisted items
const allBlacklisted = await getBlacklist("GUILD_ID");
console.log(allBlacklisted);
// Get only blacklisted users
const blacklistedUsers = await getBlacklist("GUILD_ID", "user");
console.log(blacklistedUsers);
/*
Output:
[
{ guild: 'GUILD_ID', type: 'user', id: 'USER_ID_1', ... },
{ guild: 'GUILD_ID', type: 'user', id: 'USER_ID_2', ... }
]
*/โก Practical Example: Blacklist Command
You can create a slash command to manage the blacklist easily.
const { addToBlacklist, removeFromBlacklist, isBlacklisted, getBlacklist } = require("djs-builder");
const { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("blacklist")
.setDescription("Manage the blacklist")
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
.addSubcommand(sub =>
sub.setName("add").setDescription("Add to blacklist")
.addUserOption(opt => opt.setName("user").setDescription("User to blacklist"))
.addRoleOption(opt => opt.setName("role").setDescription("Role to blacklist"))
.addChannelOption(opt => opt.setName("channel").setDescription("Channel to blacklist"))
)
.addSubcommand(sub =>
sub.setName("remove").setDescription("Remove from blacklist")
.addUserOption(opt => opt.setName("user").setDescription("User to remove"))
.addRoleOption(opt => opt.setName("role").setDescription("Role to remove"))
.addChannelOption(opt => opt.setName("channel").setDescription("Channel to remove"))
)
.addSubcommand(sub =>
sub.setName("check").setDescription("Check if a target is blacklisted")
.addUserOption(opt => opt.setName("user").setDescription("User to check"))
.addRoleOption(opt => opt.setName("role").setDescription("Role to check"))
.addChannelOption(opt => opt.setName("channel").setDescription("Channel to check"))
)
.addSubcommand(sub =>
sub.setName("list").setDescription("List all blacklisted items")
.addStringOption(opt => opt.setName("type").setDescription("Filter by type").addChoices({ name: "User", value: "user" }, { name: "Role", value: "role" }, { name: "Channel", value: "channel" } , { name: "All", value: "all" }))
),
async run(interaction) {
const sub = interaction.options.getSubcommand();
const user = interaction.options.getUser("user");
const role = interaction.options.getRole("role");
const channel = interaction.options.getChannel("channel");
const guildId = interaction.guild.id;
if (sub === "list") {
const type = interaction.options.getString("type");
if (type !== "all") {
const list = await getBlacklist(guildId, type);
if (!list.length) return interaction.reply({ content: "โ
No blacklisted items found.", flags : 64 });
const embed = new EmbedBuilder()
.setTitle("๐ซ Blacklist")
.setColor("Red")
.setDescription(list.map(item => `โข **${item.type.toUpperCase()}**: <${item.type === 'channel' ? '#' : item.type === 'role' ? '@&' : '@'}${item.id}> (\`${item.id}\`)`).join("\n").slice(0, 4000));
return interaction.reply({ embeds: [embed], flags : 64 });
} else {
const list = await getBlacklist(guildId);
if (!list.length) return interaction.reply({ content: "โ
No blacklisted items found.", flags : 64 });
const embeds = [];
const roles = list.filter(i => i.type === "role");
const users = list.filter(i => i.type === "user");
const channels = list.filter(i => i.type === "channel");
if (users.length) {
const userEmbed = new EmbedBuilder()
.setTitle("๐ซ Blacklisted Users")
.setColor("Red")
.setDescription(users.map(item => `โข <@${item.id}> (\`${item.id}\`)`).join("\n").slice(0, 4000));
embeds.push(userEmbed);
}
if( roles.length) {
const roleEmbed = new EmbedBuilder()
.setTitle("๐ซ Blacklisted Roles")
.setColor("Red")
.setDescription(roles.map(item => `โข <@&${item.id}> (\`${item.id}\`)`).join("\n").slice(0, 4000));
embeds.push(roleEmbed);
}
if( channels.length) {
const channelEmbed = new EmbedBuilder()
.setTitle("๐ซ Blacklisted Channels")
.setColor("Red")
.setDescription(channels.map(item => `โข <#${item.id}> (\`${item.id}\`)`).join("\n").slice(0, 4000));
embeds.push(channelEmbed);
}
return interaction.reply({ embeds, flags : 64 });
}
}
if (!user && !role && !channel) {
return interaction.reply({ content: "โ ๏ธ You must provide at least one option (User, Role, or Channel).", flags : 64 });
}
const target = user || role || channel;
const type = user ? "user" : role ? "role" : "channel";
const id = target.id;
if (sub === "add") {
const success = await addToBlacklist(guildId, type, id);
if (success) interaction.reply(`โ
Added **${type}** ${target} to blacklist.`);
else interaction.reply(`โ ๏ธ **${type}** ${target} is already blacklisted.`);
} else if (sub === "remove") {
const success = await removeFromBlacklist(guildId, type, id);
if (success) interaction.reply(`โ
Removed **${type}** ${target} from blacklist.`);
else interaction.reply(`โ ๏ธ **${type}** ${target} is not blacklisted.`);
} else if (sub === "check") {
const isBlocked = await isBlacklisted(guildId, type, id);
if (isBlocked) interaction.reply(`๐ซ **${type}** ${target} is currently **blacklisted**.`);
else interaction.reply(`โ
**${type}** ${target} is **not** blacklisted.`);
}
}
};๐ Hot Reloading โ Update your bot without restarting!
djs-builder allows you to reload your commands and events instantly while the bot is running. This is perfect for rapid development and fixing bugs on the fly.
๐ Features
- Prefix Commands: Reloads all prefix commands from disk.
- Slash Commands: Reloads slash command logic (internal cache).
- Events: Reloads event listeners (removes old ones, adds new ones).
- All: Reloads everything at once.
๐ Example Usage (Slash Command)
const { reload } = require("djs-builder");
const { SlashCommandBuilder } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("reload")
.setDescription("Reload bot commands/events")
.addStringOption((option) =>
option
.setName("type")
.setDescription("What to reload?")
.setRequired(true)
.addChoices(
{ name: "Prefix Commands", value: "prefix" },
{ name: "Slash Commands", value: "slash" },
{ name: "Events", value: "events" },
{ name: "All", value: "all" }
)
),
async run(interaction, client) {
const type = interaction.options.getString("type");
try {
await interaction.deferReply();
await reload(client, type);
await interaction.editReply(`โ
Successfully reloaded **${type}**! ๐`);
} catch (error) {
console.error(error);
await interaction.editReply(
"โ Failed to reload. Check console for errors."
);
}
},
};๐ก Notes
- Slash Commands: Reloading only updates the code execution. If you change the command name, description, or options, you still need to restart the bot to update Discord's API.
- Events: Old event listeners are automatically removed before adding new ones to prevent duplicates.
โก Commands & Events
๐ก Commands & Events made easy!
With djs-builder, handling commands and events is smooth, fast, and fully customizable.
You get built-in features like:
- โ ๏ธ Anti-crash protection โ your bot wonโt crash unexpectedly.
- โณ Cooldowns โ prevent spam and control usage.
- ๐ก๏ธ Permissions & owner/dev only checks โ secure your commands.
- โก Fast Use & custom prefixes โ run commands easily across guilds.
- ๐ Logging โ track every command usage for prefix or slash.
Below are all the available properties you can use for your commands and events:
โก COMMAND OPTIONS (Prefix & Slash)
name: 'string', // ๐ท๏ธ Command name (required)
aliases: ['string'], // ๐ Alternative names (Prefix only)
description: 'string', // โ๏ธ Short description of the command
cooldown: 5, // โณ Cooldown in seconds before reusing the command
Permissions: ['ADMINISTRATOR'],// ๐ก๏ธ Required permissions to execute the command
ownerOnly: true, // ๐ Only server owner can use this command
devOnly: true, // ๐ ๏ธ Only bot developer can use this command
guildOnly: true, // ๐ Command works only in servers
dmOnly: true, // โ๏ธ Command works only in DMs
fastUse: true, // โก Allow command to be executed without prefix (Prefix only)
Blacklist: true, // ๐ซ Check if user/role/channel is blacklisted
run: Function, // ๐โโ๏ธ Main function to run the command
execute: Function, // ๐โโ๏ธ Alternative function to run the commandโก EVENT OPTIONS
name: 'string', // ๐ท๏ธ Event name (e.g., messageCreate, guildMemberAdd)
once: true, // ๐ฏ If true, the event will be executed only once
run: Function, // ๐โโ๏ธ Function to run when the event triggers
execute: Function // ๐โโ๏ธ Alternative function to run the event๐ก Tip: Use these properties to fully control command behavior, access, and event handling.
๐ DASHBOARD
The Dashboard System is a modern,
