refactor: replace direct EmbedBuilder usage with a new createBaseEmbed helper for consistent embed creation

This commit is contained in:
syntaxbullet
2025-12-24 11:17:59 +01:00
parent 1189483244
commit eaf97572a4
14 changed files with 58 additions and 79 deletions

View File

@@ -1,5 +1,6 @@
import { createCommand } from "@/lib/utils"; import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder, MessageFlags } from "discord.js"; import { SlashCommandBuilder, PermissionFlagsBits, MessageFlags } from "discord.js";
import { createBaseEmbed } from "@lib/embeds";
import { configManager } from "@/lib/configManager"; import { configManager } from "@/lib/configManager";
import { config, reloadConfig } from "@/lib/config"; import { config, reloadConfig } from "@/lib/config";
import { AuroraClient } from "@/lib/BotClient"; import { AuroraClient } from "@/lib/BotClient";
@@ -45,9 +46,7 @@ export const features = createCommand({
const overrides = Object.entries(config.commands) const overrides = Object.entries(config.commands)
.map(([name, enabled]) => `• **${name}**: ${enabled ? "✅ Enabled (Override)" : "❌ Disabled"}`); .map(([name, enabled]) => `• **${name}**: ${enabled ? "✅ Enabled (Override)" : "❌ Disabled"}`);
const embed = new EmbedBuilder() const embed = createBaseEmbed("Command Features", undefined, "Blue");
.setTitle("Command Features")
.setColor("Blue");
// Add fields for each category // Add fields for each category
const sortedCategories = [...categories.keys()].sort(); const sortedCategories = [...categories.keys()].sort();

View File

@@ -1,7 +1,6 @@
import { createCommand } from "@/lib/utils"; import { createCommand } from "@/lib/utils";
import { import {
SlashCommandBuilder, SlashCommandBuilder,
EmbedBuilder,
ActionRowBuilder, ActionRowBuilder,
ButtonBuilder, ButtonBuilder,
ButtonStyle, ButtonStyle,
@@ -10,7 +9,7 @@ import {
MessageFlags MessageFlags
} from "discord.js"; } from "discord.js";
import { inventoryService } from "@/modules/inventory/inventory.service"; import { inventoryService } from "@/modules/inventory/inventory.service";
import { createSuccessEmbed, createErrorEmbed } from "@lib/embeds"; import { createSuccessEmbed, createErrorEmbed, createBaseEmbed } from "@lib/embeds";
import { UserError } from "@/lib/errors"; import { UserError } from "@/lib/errors";
import { items } from "@/db/schema"; import { items } from "@/db/schema";
import { ilike, isNotNull, and } from "drizzle-orm"; import { ilike, isNotNull, and } from "drizzle-orm";
@@ -54,11 +53,8 @@ export const listing = createCommand({
return; return;
} }
const embed = new EmbedBuilder() const embed = createBaseEmbed(`Shop: ${item.name}`, item.description || "No description available.", "Green")
.setTitle(`Shop: ${item.name}`)
.setDescription(item.description || "No description available.")
.addFields({ name: "Price", value: `${item.price} 🪙`, inline: true }) .addFields({ name: "Price", value: `${item.price} 🪙`, inline: true })
.setColor("Green")
.setThumbnail(item.iconUrl || null) .setThumbnail(item.iconUrl || null)
.setImage(item.imageUrl || null) .setImage(item.imageUrl || null)
.setFooter({ text: "Click the button below to purchase instantly." }); .setFooter({ text: "Click the button below to purchase instantly." });

View File

@@ -1,6 +1,7 @@
import { createCommand } from "@/lib/utils"; import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder } from "discord.js"; import { SlashCommandBuilder } from "discord.js";
import { userService } from "@/modules/user/user.service"; import { userService } from "@/modules/user/user.service";
import { createBaseEmbed } from "@lib/embeds";
export const balance = createCommand({ export const balance = createCommand({
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
@@ -22,10 +23,8 @@ export const balance = createCommand({
const user = await userService.getOrCreateUser(targetUser.id, targetUser.username); const user = await userService.getOrCreateUser(targetUser.id, targetUser.username);
const embed = new EmbedBuilder() const embed = createBaseEmbed(undefined, `**Balance**: ${user.balance || 0n} AU`, "Yellow")
.setAuthor({ name: targetUser.username, iconURL: targetUser.displayAvatarURL() }) .setAuthor({ name: targetUser.username, iconURL: targetUser.displayAvatarURL() });
.setDescription(`**Balance**: ${user.balance || 0n} AU`)
.setColor("Yellow");
await interaction.editReply({ embeds: [embed] }); await interaction.editReply({ embeds: [embed] });
} }

View File

@@ -1,8 +1,8 @@
import { createCommand } from "@/lib/utils"; import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder } from "discord.js"; import { SlashCommandBuilder } from "discord.js";
import { economyService } from "@/modules/economy/economy.service"; import { economyService } from "@/modules/economy/economy.service";
import { createErrorEmbed } from "@lib/embeds"; import { createErrorEmbed, createSuccessEmbed } from "@lib/embeds";
import { UserError } from "@/lib/errors"; import { UserError } from "@/lib/errors";
export const daily = createCommand({ export const daily = createCommand({
@@ -13,16 +13,13 @@ export const daily = createCommand({
try { try {
const result = await economyService.claimDaily(interaction.user.id); const result = await economyService.claimDaily(interaction.user.id);
const embed = new EmbedBuilder() const embed = createSuccessEmbed(`You claimed ** ${result.amount}** Astral Units!${result.isWeekly ? `\n🎉 **Weekly Bonus!** +${result.weeklyBonus} extra!` : ''}`, "💰 Daily Reward Claimed!")
.setTitle("💰 Daily Reward Claimed!")
.setDescription(`You claimed ** ${result.amount}** Astral Units!${result.isWeekly ? `\n🎉 **Weekly Bonus!** +${result.weeklyBonus} extra!` : ''}`)
.addFields( .addFields(
{ name: "Streak", value: `🔥 ${result.streak} days`, inline: true }, { name: "Streak", value: `🔥 ${result.streak} days`, inline: true },
{ name: "Weekly Progress", value: `${"🟩".repeat(result.streak % 7 || 7)}${"⬜".repeat(7 - (result.streak % 7 || 7))} (${result.streak % 7 || 7}/7)`, inline: true }, { name: "Weekly Progress", value: `${"🟩".repeat(result.streak % 7 || 7)}${"⬜".repeat(7 - (result.streak % 7 || 7))} (${result.streak % 7 || 7}/7)`, inline: true },
{ name: "Next Reward", value: `<t:${Math.floor(result.nextReadyAt.getTime() / 1000)}:R> `, inline: true } { name: "Next Reward", value: `<t:${Math.floor(result.nextReadyAt.getTime() / 1000)}:R> `, inline: true }
) )
.setColor("Gold") .setColor("Gold");
.setTimestamp();
await interaction.reply({ embeds: [embed] }); await interaction.reply({ embeds: [embed] });

View File

@@ -1,10 +1,10 @@
import { createCommand } from "@/lib/utils"; import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder, MessageFlags } from "discord.js"; import { SlashCommandBuilder, MessageFlags } from "discord.js";
import { economyService } from "@/modules/economy/economy.service"; import { economyService } from "@/modules/economy/economy.service";
import { userService } from "@/modules/user/user.service"; import { userService } from "@/modules/user/user.service";
import { config } from "@/lib/config"; import { config } from "@/lib/config";
import { createErrorEmbed } from "@lib/embeds"; import { createErrorEmbed, createSuccessEmbed } from "@lib/embeds";
import { UserError } from "@/lib/errors"; import { UserError } from "@/lib/errors";
export const pay = createCommand({ export const pay = createCommand({
@@ -49,12 +49,7 @@ export const pay = createCommand({
await interaction.deferReply(); await interaction.deferReply();
await economyService.transfer(senderId, receiverId, amount); await economyService.transfer(senderId, receiverId, amount);
const embed = new EmbedBuilder() const embed = createSuccessEmbed(`Successfully sent ** ${amount}** Astral Units to <@${targetUser.id}>.`, "💸 Transfer Successful");
.setTitle("💸 Transfer Successful")
.setDescription(`Successfully sent ** ${amount}** Astral Units to <@${targetUser.id}>.`)
.setColor("Green")
.setTimestamp();
await interaction.editReply({ embeds: [embed], content: `<@${receiverId}>` }); await interaction.editReply({ embeds: [embed], content: `<@${receiverId}>` });
} catch (error: any) { } catch (error: any) {

View File

@@ -1,7 +1,7 @@
import { createCommand } from "@/lib/utils"; import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder, ChannelType, ActionRowBuilder, ButtonBuilder, ButtonStyle, ThreadAutoArchiveDuration, MessageFlags } from "discord.js"; import { SlashCommandBuilder, ChannelType, ActionRowBuilder, ButtonBuilder, ButtonStyle, ThreadAutoArchiveDuration, MessageFlags } from "discord.js";
import { TradeService } from "@/modules/trade/trade.service"; import { TradeService } from "@/modules/trade/trade.service";
import { createErrorEmbed, createWarningEmbed } from "@lib/embeds"; import { createErrorEmbed, createWarningEmbed, createBaseEmbed } from "@lib/embeds";
export const trade = createCommand({ export const trade = createCommand({
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
@@ -64,10 +64,7 @@ export const trade = createCommand({
); );
// Send Dashboard to Thread // Send Dashboard to Thread
const embed = new EmbedBuilder() const embed = createBaseEmbed("🤝 Trading Session", `Trade started between ${interaction.user} and ${targetUser}.\nUse the controls below to build your offer.`, 0xFFD700)
.setTitle("🤝 Trading Session")
.setDescription(`Trade started between ${interaction.user} and ${targetUser}.\nUse the controls below to build your offer.`)
.setColor(0xFFD700)
.addFields( .addFields(
{ name: interaction.user.username, value: "*Empty Offer*", inline: true }, { name: interaction.user.username, value: "*Empty Offer*", inline: true },
{ name: targetUser.username, value: "*Empty Offer*", inline: true } { name: targetUser.username, value: "*Empty Offer*", inline: true }

View File

@@ -1,8 +1,8 @@
import { createCommand } from "@/lib/utils"; import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder } from "discord.js"; import { SlashCommandBuilder } from "discord.js";
import { inventoryService } from "@/modules/inventory/inventory.service"; import { inventoryService } from "@/modules/inventory/inventory.service";
import { userService } from "@/modules/user/user.service"; import { userService } from "@/modules/user/user.service";
import { createWarningEmbed } from "@lib/embeds"; import { createWarningEmbed, createBaseEmbed } from "@lib/embeds";
export const inventory = createCommand({ export const inventory = createCommand({
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
@@ -35,11 +35,7 @@ export const inventory = createCommand({
return `**${entry.item.name}** x${entry.quantity}`; return `**${entry.item.name}** x${entry.quantity}`;
}).join("\n"); }).join("\n");
const embed = new EmbedBuilder() const embed = createBaseEmbed(`${user.username}'s Inventory`, description, "Blue");
.setTitle(`${user.username}'s Inventory`)
.setDescription(description)
.setColor("Blue")
.setTimestamp();
await interaction.editReply({ embeds: [embed] }); await interaction.editReply({ embeds: [embed] });
} }

View File

@@ -1,9 +1,9 @@
import { createCommand } from "@/lib/utils"; import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder } from "discord.js"; import { SlashCommandBuilder } from "discord.js";
import { DrizzleClient } from "@/lib/DrizzleClient"; import { DrizzleClient } from "@/lib/DrizzleClient";
import { users } from "@/db/schema"; import { users } from "@/db/schema";
import { desc } from "drizzle-orm"; import { desc } from "drizzle-orm";
import { createWarningEmbed } from "@lib/embeds"; import { createWarningEmbed, createBaseEmbed } from "@lib/embeds";
export const leaderboard = createCommand({ export const leaderboard = createCommand({
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
@@ -40,11 +40,7 @@ export const leaderboard = createCommand({
return `${medal} **${user.username}** — ${value}`; return `${medal} **${user.username}** — ${value}`;
}).join("\n"); }).join("\n");
const embed = new EmbedBuilder() const embed = createBaseEmbed(isXp ? "🏆 XP Leaderboard" : "💰 Richest Players", description, "Gold");
.setTitle(isXp ? "🏆 XP Leaderboard" : "💰 Richest Players")
.setDescription(description)
.setColor("Gold")
.setTimestamp();
await interaction.editReply({ embeds: [embed] }); await interaction.editReply({ embeds: [embed] });
} }

View File

@@ -1,7 +1,7 @@
import { createCommand } from "@/lib/utils"; import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder, MessageFlags } from "discord.js"; import { SlashCommandBuilder, MessageFlags } from "discord.js";
import { questService } from "@/modules/quest/quest.service"; import { questService } from "@/modules/quest/quest.service";
import { createWarningEmbed } from "@lib/embeds"; import { createWarningEmbed, createBaseEmbed } from "@lib/embeds";
export const quests = createCommand({ export const quests = createCommand({
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
@@ -17,10 +17,7 @@ export const quests = createCommand({
return; return;
} }
const embed = new EmbedBuilder() const embed = createBaseEmbed("📜 Quest Log", undefined, "Blue");
.setTitle("📜 Quest Log")
.setColor("Blue")
.setTimestamp();
userQuests.forEach(entry => { userQuests.forEach(entry => {
const status = entry.completedAt ? "✅ Completed" : "In Progress"; const status = entry.completedAt ? "✅ Completed" : "In Progress";

View File

@@ -1,4 +1,4 @@
import { EmbedBuilder, Colors } from "discord.js"; import { Colors, type ColorResolvable, EmbedBuilder } from "discord.js";
/** /**
* Creates a standardized error embed. * Creates a standardized error embed.
@@ -55,3 +55,21 @@ export function createInfoEmbed(message: string, title: string = "Info"): EmbedB
.setColor(Colors.Blue) .setColor(Colors.Blue)
.setTimestamp(); .setTimestamp();
} }
/**
* Creates a standardized base embed with common configuration.
* @param title Optional title for the embed.
* @param description Optional description for the embed.
* @param color Optional color for the embed.
* @returns An EmbedBuilder instance with base configuration.
*/
export function createBaseEmbed(title?: string, description?: string, color?: ColorResolvable): EmbedBuilder {
const embed = new EmbedBuilder()
.setTimestamp();
if (title) embed.setTitle(title);
if (description) embed.setDescription(description);
if (color) embed.setColor(color);
return embed;
}

View File

@@ -2,7 +2,6 @@ import {
ActionRowBuilder, ActionRowBuilder,
ButtonBuilder, ButtonBuilder,
ButtonStyle, ButtonStyle,
EmbedBuilder,
ModalBuilder, ModalBuilder,
StringSelectMenuBuilder, StringSelectMenuBuilder,
TextInputBuilder, TextInputBuilder,
@@ -13,6 +12,7 @@ import {
import { items } from "@/db/schema"; import { items } from "@/db/schema";
import { DrizzleClient } from "@/lib/DrizzleClient"; import { DrizzleClient } from "@/lib/DrizzleClient";
import type { ItemUsageData, ItemEffect } from "@/lib/types"; import type { ItemUsageData, ItemEffect } from "@/lib/types";
import { createBaseEmbed } from "@lib/embeds";
// --- Types --- // --- Types ---
export interface DraftItem { export interface DraftItem {
@@ -66,9 +66,7 @@ export const renderWizard = (userId: string, isDraft = true) => {
draftSession.set(userId, draft); draftSession.set(userId, draft);
} }
const embed = new EmbedBuilder() const embed = createBaseEmbed(`🛠️ Item Creator: ${draft.name}`, undefined, "Blue")
.setTitle(`🛠️ Item Creator: ${draft.name}`)
.setColor("Blue")
.addFields( .addFields(
{ name: "General", value: `**Type:** ${draft.type}\n**Rarity:** ${draft.rarity}\n**Desc:** ${draft.description}`, inline: true }, { name: "General", value: `**Type:** ${draft.type}\n**Rarity:** ${draft.rarity}\n**Desc:** ${draft.description}`, inline: true },
{ name: "Economy", value: `**Price:** ${draft.price ? `${draft.price} 🪙` : "Not for sale"}`, inline: true }, { name: "Economy", value: `**Price:** ${draft.price ? `${draft.price} 🪙` : "Not for sale"}`, inline: true },

View File

@@ -1,6 +1,6 @@
import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, EmbedBuilder, ButtonStyle } from "discord.js"; import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle } from "discord.js";
import { lootdropService } from "./lootdrop.service"; import { lootdropService } from "./lootdrop.service";
import { createErrorEmbed } from "@/lib/embeds"; import { createErrorEmbed, createSuccessEmbed, createBaseEmbed } from "@/lib/embeds";
export async function handleLootdropInteraction(interaction: ButtonInteraction) { export async function handleLootdropInteraction(interaction: ButtonInteraction) {
if (interaction.customId === "lootdrop_claim") { if (interaction.customId === "lootdrop_claim") {
@@ -17,9 +17,7 @@ export async function handleLootdropInteraction(interaction: ButtonInteraction)
const originalEmbed = interaction.message.embeds[0]; const originalEmbed = interaction.message.embeds[0];
if (!originalEmbed) return; if (!originalEmbed) return;
const newEmbed = new EmbedBuilder(originalEmbed.data) const newEmbed = createBaseEmbed(originalEmbed.title || "💰 LOOTDROP!", `✅ Claimed by <@${interaction.user.id}> for **${result.amount} ${result.currency}**!`, "#00FF00");
.setDescription(`✅ Claimed by <@${interaction.user.id}> for **${result.amount} ${result.currency}**!`)
.setColor("#00FF00");
// Disable button // Disable button
// We reconstruct the button using builders for safety // We reconstruct the button using builders for safety

View File

@@ -2,6 +2,7 @@
import { Message, TextChannel, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType } from "discord.js"; import { Message, TextChannel, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType } from "discord.js";
import { config } from "@/lib/config"; import { config } from "@/lib/config";
import { economyService } from "./economy.service"; import { economyService } from "./economy.service";
import { createBaseEmbed } from "@lib/embeds";
import { lootdrops } from "@/db/schema"; import { lootdrops } from "@/db/schema";
import { DrizzleClient } from "@/lib/DrizzleClient"; import { DrizzleClient } from "@/lib/DrizzleClient";
@@ -91,11 +92,7 @@ class LootdropService {
const reward = Math.floor(Math.random() * (max - min + 1)) + min; const reward = Math.floor(Math.random() * (max - min + 1)) + min;
const currency = config.lootdrop.reward.currency; const currency = config.lootdrop.reward.currency;
const embed = new EmbedBuilder() const embed = createBaseEmbed("💰 LOOTDROP!", `A lootdrop has appeared! Click the button below to claim **${reward} ${currency}**!`, "#FFD700");
.setTitle("💰 LOOTDROP!")
.setDescription(`A lootdrop has appeared! Click the button below to claim **${reward} ${currency}**!`)
.setColor("#FFD700")
.setTimestamp();
const claimButton = new ButtonBuilder() const claimButton = new ButtonBuilder()
.setCustomId("lootdrop_claim") .setCustomId("lootdrop_claim")

View File

@@ -3,7 +3,6 @@ import {
ModalSubmitInteraction, ModalSubmitInteraction,
StringSelectMenuInteraction, StringSelectMenuInteraction,
type Interaction, type Interaction,
EmbedBuilder,
ActionRowBuilder, ActionRowBuilder,
ButtonBuilder, ButtonBuilder,
ButtonStyle, ButtonStyle,
@@ -13,10 +12,11 @@ import {
TextInputStyle, TextInputStyle,
ThreadChannel, ThreadChannel,
TextChannel, TextChannel,
EmbedBuilder
} from "discord.js"; } from "discord.js";
import { TradeService } from "./trade.service"; import { TradeService } from "./trade.service";
import { inventoryService } from "@/modules/inventory/inventory.service"; import { inventoryService } from "@/modules/inventory/inventory.service";
import { createErrorEmbed, createWarningEmbed, createSuccessEmbed, createInfoEmbed } from "@lib/embeds"; import { createErrorEmbed, createWarningEmbed, createSuccessEmbed, createInfoEmbed, createBaseEmbed } from "@lib/embeds";
const EMBED_COLOR = 0xFFD700; // Gold const EMBED_COLOR = 0xFFD700; // Gold
@@ -207,9 +207,7 @@ export async function updateTradeDashboard(interaction: Interaction, threadId: s
// Execute Trade // Execute Trade
try { try {
await TradeService.executeTrade(threadId); await TradeService.executeTrade(threadId);
const embed = new EmbedBuilder() const embed = createBaseEmbed("✅ Trade Completed", undefined, "Green")
.setTitle("✅ Trade Completed")
.setColor("Green")
.addFields( .addFields(
{ name: session.userA.username, value: formatOffer(session.userA), inline: true }, { name: session.userA.username, value: formatOffer(session.userA), inline: true },
{ name: session.userB.username, value: formatOffer(session.userB), inline: true } { name: session.userB.username, value: formatOffer(session.userB), inline: true }
@@ -246,9 +244,7 @@ export async function updateTradeDashboard(interaction: Interaction, threadId: s
} }
// Build Status Embed // Build Status Embed
const embed = new EmbedBuilder() const embed = createBaseEmbed("🤝 Trading Session", undefined, EMBED_COLOR)
.setTitle("🤝 Trading Session")
.setColor(EMBED_COLOR)
.addFields( .addFields(
{ {
name: `${session.userA.username} ${session.userA.locked ? '✅ (Ready)' : '✏️ (Editing)'}`, name: `${session.userA.username} ${session.userA.locked ? '✅ (Ready)' : '✏️ (Editing)'}`,