16 Commits

Author SHA1 Message Date
syntaxbullet
1eace32aa1 feat: Implement dynamic event loading and refactor event handlers into dedicated files. 2025-12-14 22:21:28 +01:00
syntaxbullet
32c614975e feat: automatically assign 'Visitor' role to new guild members on join 2025-12-14 21:33:32 +01:00
syntaxbullet
7dd9052c9b feat: add webhook command for sending messages via JSON payload 2025-12-14 15:48:27 +01:00
syntaxbullet
9d1d4aeaea feat: clarify daily reward streak display by renaming field and adding 'days' unit 2025-12-14 15:32:36 +01:00
syntaxbullet
bd59f01a41 chore: update currency symbol from 🪙 to AU in balance display 2025-12-14 14:28:11 +01:00
syntaxbullet
4639fecf45 feat: Implement gradual daily streak decay and rename currency from 'coins' to 'Astral Units'. 2025-12-14 14:16:16 +01:00
syntaxbullet
ee2fda83e5 feat: Add anonymous volume for /app/node_modules to the service definition. 2025-12-14 12:36:30 +01:00
syntaxbullet
7e9aa06556 feat: Introduce success and info embeds, add related user tracking to economy transactions, and refine trade interaction feedback and thread cleanup. 2025-12-13 16:02:07 +01:00
syntaxbullet
f96d81f8a3 chore: Remove unnecessary comments from profile command, trade interaction handler, inventory service, and scheduler. 2025-12-13 14:28:36 +01:00
syntaxbullet
d34e872133 feat: Implement a generic user timers system with a scheduler to manage cooldowns, effects, and access. 2025-12-13 14:18:46 +01:00
syntaxbullet
b33738aee3 refactor: remove unused imports and types across trade and economy modules 2025-12-13 12:50:00 +01:00
syntaxbullet
86cbe827a2 refactor: Remove interaction deferrals, use direct replies, and make error/warning messages ephemeral in economy commands. 2025-12-13 12:46:38 +01:00
syntaxbullet
421bb26ceb feat: add trading system with dedicated modules and centralize embed creation for commands 2025-12-13 12:43:27 +01:00
syntaxbullet
5f4efd372f feat: Introduce GameConfig to centralize constants for leveling, economy, and inventory, adding new transfer and inventory limits. 2025-12-13 12:20:30 +01:00
syntaxbullet
8818d6bb15 feat: Add type and usageData columns to the item schema to support item usage effects. 2025-12-13 12:02:30 +01:00
syntaxbullet
29899acc7f feat: update database schema to support item trading 2025-12-13 12:00:02 +01:00
32 changed files with 1269 additions and 182 deletions

View File

@@ -48,6 +48,7 @@ services:
- "4983:4983"
volumes:
- .:/app
- /app/node_modules
environment:
- DB_USER=${DB_USER}
- DB_PASSWORD=${DB_PASSWORD}

View File

@@ -19,7 +19,7 @@ export const balance = createCommand({
const embed = new EmbedBuilder()
.setAuthor({ name: targetUser.username, iconURL: targetUser.displayAvatarURL() })
.setDescription(`**Balance**: ${user.balance || 0n} 🪙`)
.setDescription(`**Balance**: ${user.balance || 0n} AU`)
.setColor("Yellow");
await interaction.editReply({ embeds: [embed] });

View File

@@ -1,43 +1,36 @@
import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder } from "discord.js";
import { economyService } from "@/modules/economy/economy.service";
import { userService } from "@/modules/user/user.service";
import { createErrorEmbed, createWarningEmbed } from "@lib/embeds";
export const daily = createCommand({
data: new SlashCommandBuilder()
.setName("daily")
.setDescription("Claim your daily reward"),
execute: async (interaction) => {
await interaction.deferReply();
try {
const result = await economyService.claimDaily(interaction.user.id);
const embed = new EmbedBuilder()
.setTitle("💰 Daily Reward Claimed!")
.setDescription(`You claimed **${result.amount}** coins!`)
.setDescription(`You claimed **${result.amount}** Astral Units!`)
.addFields(
{ name: "Current Streak", value: `🔥 ${result.streak} days`, inline: true },
{ name: "Streak", value: `🔥 ${result.streak} days`, inline: true },
{ name: "Next Reward", value: `<t:${Math.floor(result.nextReadyAt.getTime() / 1000)}:R>`, inline: true }
)
.setColor("Gold")
.setTimestamp();
await interaction.editReply({ embeds: [embed] });
await interaction.reply({ embeds: [embed] });
} catch (error: any) {
if (error.message.includes("Daily already claimed")) {
const embed = new EmbedBuilder()
.setTitle("⏳ Cooldown")
.setDescription(error.message)
.setColor("Orange");
await interaction.editReply({ embeds: [embed] });
await interaction.reply({ embeds: [createWarningEmbed(error.message, "Cooldown")], ephemeral: true });
return;
}
console.error(error);
await interaction.editReply({ content: "❌ An error occurred while claiming your daily reward." });
await interaction.reply({ embeds: [createErrorEmbed("An error occurred while claiming your daily reward.")], ephemeral: true });
}
}
});

View File

@@ -2,11 +2,13 @@ import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder } from "discord.js";
import { economyService } from "@/modules/economy/economy.service";
import { userService } from "@/modules/user/user.service";
import { GameConfig } from "@/config/game";
import { createErrorEmbed, createWarningEmbed } from "@lib/embeds";
export const pay = createCommand({
data: new SlashCommandBuilder()
.setName("pay")
.setDescription("Transfer coins to another user")
.setDescription("Transfer Astral Units to another user")
.addUserOption(option =>
option.setName("user")
.setDescription("The user to pay")
@@ -19,15 +21,18 @@ export const pay = createCommand({
.setRequired(true)
),
execute: async (interaction) => {
await interaction.deferReply();
const targetUser = await userService.getOrCreateUser(interaction.options.getUser("user", true).id, interaction.options.getUser("user", true).username);
const amount = BigInt(interaction.options.getInteger("amount", true));
const senderId = interaction.user.id;
const receiverId = targetUser.id;
if (amount < GameConfig.economy.transfers.minAmount) {
await interaction.reply({ embeds: [createWarningEmbed(`Amount must be at least ${GameConfig.economy.transfers.minAmount}.`)], ephemeral: true });
return;
}
if (senderId === receiverId) {
await interaction.editReply({ content: "❌ You cannot pay yourself." });
await interaction.reply({ embeds: [createWarningEmbed("You cannot pay yourself.")], ephemeral: true });
return;
}
@@ -36,19 +41,19 @@ export const pay = createCommand({
const embed = new EmbedBuilder()
.setTitle("💸 Transfer Successful")
.setDescription(`Successfully sent **${amount}** coins to <@${targetUser.id}>.`)
.setDescription(`Successfully sent **${amount}** Astral Units to <@${targetUser.id}>.`)
.setColor("Green")
.setTimestamp();
await interaction.editReply({ embeds: [embed] });
await interaction.reply({ embeds: [embed] });
} catch (error: any) {
if (error.message.includes("Insufficient funds")) {
await interaction.editReply({ content: "❌ Insufficient funds." });
await interaction.reply({ embeds: [createWarningEmbed("Insufficient funds.")], ephemeral: true });
return;
}
console.error(error);
await interaction.editReply({ content: "❌ Transfer failed." });
await interaction.reply({ embeds: [createErrorEmbed("Transfer failed.")], ephemeral: true });
}
}
});

View File

@@ -8,11 +8,13 @@ import {
ComponentType,
type BaseGuildTextChannel,
type ButtonInteraction,
PermissionFlagsBits
PermissionFlagsBits,
MessageFlags
} from "discord.js";
import { userService } from "@/modules/user/user.service";
import { inventoryService } from "@/modules/inventory/inventory.service";
import type { items } from "@db/schema";
import { createErrorEmbed, createWarningEmbed } from "@lib/embeds";
export const sell = createCommand({
data: new SlashCommandBuilder()
@@ -30,24 +32,24 @@ export const sell = createCommand({
)
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
execute: async (interaction) => {
await interaction.deferReply({ ephemeral: true });
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const itemId = interaction.options.getNumber("itemid", true);
const targetChannel = (interaction.options.getChannel("channel") as BaseGuildTextChannel) || interaction.channel as BaseGuildTextChannel;
if (!targetChannel || !targetChannel.isSendable()) {
await interaction.editReply({ content: "Target channel is invalid or not sendable." });
await interaction.editReply({ content: "", embeds: [createErrorEmbed("Target channel is invalid or not sendable.")] });
return;
}
const item = await inventoryService.getItem(itemId);
if (!item) {
await interaction.editReply({ content: `Item with ID ${itemId} not found.` });
await interaction.editReply({ content: "", embeds: [createErrorEmbed(`Item with ID ${itemId} not found.`)] });
return;
}
if (!item.price) {
await interaction.editReply({ content: `Item "${item.name}" is not for sale (no price set).` });
await interaction.editReply({ content: "", embeds: [createWarningEmbed(`Item "${item.name}" is not for sale (no price set).`)] });
return;
}
@@ -82,32 +84,32 @@ export const sell = createCommand({
} catch (error) {
console.error("Failed to send sell message:", error);
await interaction.editReply({ content: "Failed to post the item for sale." });
await interaction.editReply({ content: "", embeds: [createErrorEmbed("Failed to post the item for sale.")] });
}
}
});
async function handleBuyInteraction(interaction: ButtonInteraction, item: typeof items.$inferSelect) {
try {
await interaction.deferReply({ ephemeral: true });
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const userId = interaction.user.id;
const user = await userService.getUserById(userId);
if (!user) {
await interaction.editReply({ content: "User profile not found." });
await interaction.editReply({ content: "", embeds: [createErrorEmbed("User profile not found.")] });
return;
}
if ((user.balance ?? 0n) < (item.price ?? 0n)) {
await interaction.editReply({ content: `You don't have enough money! You need ${item.price} 🪙.` });
await interaction.editReply({ content: "", embeds: [createWarningEmbed(`You don't have enough money! You need ${item.price} 🪙.`)] });
return;
}
const result = await inventoryService.buyItem(userId, item.id, 1n);
if (!result.success) {
await interaction.editReply({ content: "Transaction failed. Please try again." });
await interaction.editReply({ content: "", embeds: [createErrorEmbed("Transaction failed. Please try again.")] });
return;
}
@@ -115,9 +117,9 @@ async function handleBuyInteraction(interaction: ButtonInteraction, item: typeof
} catch (error) {
console.error("Error processing purchase:", error);
if (interaction.deferred || interaction.replied) {
await interaction.editReply({ content: "An error occurred while processing your purchase." });
await interaction.editReply({ content: "", embeds: [createErrorEmbed("An error occurred while processing your purchase.")] });
} else {
await interaction.reply({ content: "An error occurred while processing your purchase.", ephemeral: true });
await interaction.reply({ embeds: [createErrorEmbed("An error occurred while processing your purchase.")], flags: MessageFlags.Ephemeral });
}
}
}

View File

@@ -0,0 +1,91 @@
import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder, ChannelType, ActionRowBuilder, ButtonBuilder, ButtonStyle, ThreadAutoArchiveDuration } from "discord.js";
import { TradeService } from "@/modules/trade/trade.service";
import { createErrorEmbed, createWarningEmbed } from "@lib/embeds";
export const trade = createCommand({
data: new SlashCommandBuilder()
.setName("trade")
.setDescription("Start a trade with another player")
.addUserOption(option =>
option.setName("user")
.setDescription("The user to trade with")
.setRequired(true)
),
execute: async (interaction) => {
const targetUser = interaction.options.getUser("user", true);
if (targetUser.id === interaction.user.id) {
await interaction.reply({ embeds: [createWarningEmbed("You cannot trade with yourself.")], ephemeral: true });
return;
}
if (targetUser.bot) {
await interaction.reply({ embeds: [createWarningEmbed("You cannot trade with bots.")], ephemeral: true });
return;
}
// Create Thread
const channel = interaction.channel;
if (!channel || channel.type === ChannelType.DM) {
await interaction.reply({ embeds: [createErrorEmbed("Cannot start trade in DMs.")], ephemeral: true });
return;
}
// Check if we can create threads
// Assuming permissions are fine.
await interaction.reply({ content: `🔄 Setting up trade with ${targetUser}...` });
const message = await interaction.fetchReply();
let thread;
try {
thread = await message.startThread({
name: `trade-${interaction.user.username}-${targetUser.username}`,
autoArchiveDuration: ThreadAutoArchiveDuration.OneHour,
reason: "Trading Session"
});
} catch (e) {
// Fallback if message threads fail, try channel threads (private preferred)
// But startThread on message is usually easiest.
try {
await message.delete();
} catch (err) {
console.error("Failed to delete setup message", err);
}
await interaction.followUp({ embeds: [createErrorEmbed("Failed to create trade thread. Check permissions.")], ephemeral: true });
return;
}
// Setup Session
TradeService.createSession(thread.id,
{ id: interaction.user.id, username: interaction.user.username },
{ id: targetUser.id, username: targetUser.username }
);
// Send Dashboard to Thread
const embed = new EmbedBuilder()
.setTitle("🤝 Trading Session")
.setDescription(`Trade started between ${interaction.user} and ${targetUser}.\nUse the controls below to build your offer.`)
.setColor(0xFFD700)
.addFields(
{ name: interaction.user.username, value: "*Empty Offer*", inline: true },
{ name: targetUser.username, value: "*Empty Offer*", inline: true }
)
.setFooter({ text: "Both parties must click Lock to confirm trade." });
const row = new ActionRowBuilder<ButtonBuilder>()
.addComponents(
new ButtonBuilder().setCustomId('trade_add_item').setLabel('Add Item').setStyle(ButtonStyle.Secondary),
new ButtonBuilder().setCustomId('trade_add_money').setLabel('Add Money').setStyle(ButtonStyle.Success),
new ButtonBuilder().setCustomId('trade_remove_item').setLabel('Remove Item').setStyle(ButtonStyle.Secondary),
new ButtonBuilder().setCustomId('trade_lock').setLabel('Lock / Unlock').setStyle(ButtonStyle.Primary),
new ButtonBuilder().setCustomId('trade_cancel').setLabel('Cancel').setStyle(ButtonStyle.Danger),
);
await thread.send({ content: `${interaction.user} ${targetUser} Welcome to your trading session!`, embeds: [embed], components: [row] });
// Update original reply
await interaction.editReply({ content: `✅ Trade opened: <#${thread.id}>` });
}
});

View File

@@ -2,6 +2,7 @@ import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder } from "discord.js";
import { inventoryService } from "@/modules/inventory/inventory.service";
import { userService } from "@/modules/user/user.service";
import { createWarningEmbed } from "@lib/embeds";
export const inventory = createCommand({
data: new SlashCommandBuilder()
@@ -20,12 +21,7 @@ export const inventory = createCommand({
const items = await inventoryService.getInventory(user.id);
if (!items || items.length === 0) {
const embed = new EmbedBuilder()
.setTitle(`${user.username}'s Inventory`)
.setDescription("Inventory is empty.")
.setColor("Blue");
await interaction.editReply({ embeds: [embed] });
await interaction.editReply({ embeds: [createWarningEmbed("Inventory is empty.", `${user.username}'s Inventory`)] });
return;
}

View File

@@ -3,6 +3,7 @@ import { SlashCommandBuilder, EmbedBuilder } from "discord.js";
import { DrizzleClient } from "@/lib/DrizzleClient";
import { users } from "@/db/schema";
import { desc } from "drizzle-orm";
import { createWarningEmbed } from "@lib/embeds";
export const leaderboard = createCommand({
data: new SlashCommandBuilder()
@@ -29,7 +30,7 @@ export const leaderboard = createCommand({
});
if (leaders.length === 0) {
await interaction.editReply({ content: "❌ No users found." });
await interaction.editReply({ embeds: [createWarningEmbed("No users found.", "Leaderboard")] });
return;
}

View File

@@ -1,6 +1,7 @@
import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, EmbedBuilder } from "discord.js";
import { questService } from "@/modules/quest/quest.service";
import { createWarningEmbed } from "@lib/embeds";
export const quests = createCommand({
data: new SlashCommandBuilder()
@@ -12,12 +13,7 @@ export const quests = createCommand({
const userQuests = await questService.getUserQuests(interaction.user.id);
if (!userQuests || userQuests.length === 0) {
const embed = new EmbedBuilder()
.setTitle("📜 Quest Log")
.setDescription("You have no active quests.")
.setColor("Grey");
await interaction.editReply({ embeds: [embed] });
await interaction.editReply({ embeds: [createWarningEmbed("You have no active quests.", "Quest Log")] });
return;
}

View File

@@ -1,6 +1,7 @@
import { createCommand } from "@lib/utils";
import { KyokoClient } from "@lib/KyokoClient";
import { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits } from "discord.js";
import { createErrorEmbed } from "@lib/embeds";
export const reload = createCommand({
data: new SlashCommandBuilder()
@@ -23,12 +24,7 @@ export const reload = createCommand({
await interaction.editReply({ embeds: [embed] });
} catch (error) {
console.error(error);
const embed = new EmbedBuilder()
.setTitle("❌ Reload Failed")
.setDescription("An error occurred while reloading commands. Check console for details.")
.setColor("Red");
await interaction.editReply({ embeds: [embed] });
await interaction.editReply({ embeds: [createErrorEmbed("An error occurred while reloading commands. Check console for details.", "Reload Failed")] });
}
}
});

View File

@@ -0,0 +1,75 @@
import { createCommand } from "@/lib/utils";
import { SlashCommandBuilder, PermissionFlagsBits, TextChannel, NewsChannel, VoiceChannel } from "discord.js";
import { createErrorEmbed } from "@/lib/embeds";
export const webhook = createCommand({
data: new SlashCommandBuilder()
.setName("webhook")
.setDescription("Send a message via webhook using a JSON payload")
.setDefaultMemberPermissions(PermissionFlagsBits.ManageWebhooks)
.addStringOption(option =>
option.setName("payload")
.setDescription("The JSON payload for the webhook message")
.setRequired(true)
),
execute: async (interaction) => {
await interaction.deferReply({ ephemeral: true });
const payloadString = interaction.options.getString("payload", true);
let payload;
try {
payload = JSON.parse(payloadString);
} catch (error) {
await interaction.editReply({
embeds: [createErrorEmbed("The provided payload is not valid JSON.", "Invalid JSON")]
});
return;
}
const channel = interaction.channel;
if (!channel || !('createWebhook' in channel)) {
await interaction.editReply({
embeds: [createErrorEmbed("This channel does not support webhooks.", "Unsupported Channel")]
});
return;
}
let webhook;
try {
webhook = await channel.createWebhook({
name: `${interaction.client.user.username} - Proxy`,
avatar: interaction.client.user.displayAvatarURL(),
reason: `Proxy message requested by ${interaction.user.tag}`
});
// Support snake_case keys for raw API compatibility
if (payload.avatar_url && !payload.avatarURL) {
payload.avatarURL = payload.avatar_url;
delete payload.avatar_url;
}
await webhook.send(payload);
await webhook.delete("Proxy message sent");
await interaction.editReply({ content: "Message sent successfully!" });
} catch (error) {
console.error("Webhook error:", error);
// Attempt cleanup if webhook was created but sending failed
if (webhook) {
try {
await webhook.delete("Cleanup after failure");
} catch (cleanupError) {
console.error("Failed to delete webhook during cleanup:", cleanupError);
}
}
await interaction.editReply({
embeds: [createErrorEmbed("Failed to send message via webhook. Ensure the bot has 'Manage Webhooks' permission and the payload is valid.", "Delivery Failed")]
});
}
}
});

View File

@@ -30,7 +30,7 @@ export const profile = createCommand({
const attachment = new AttachmentBuilder(cardBuffer, { name: 'student-id.png' });
await interaction.editReply({ files: [attachment] }); // Send mostly just the image as requested, or maybe both? User said "show that user's student id". Image is primary.
await interaction.editReply({ files: [attachment] });
}
});

29
src/config/game.ts Normal file
View File

@@ -0,0 +1,29 @@
export const GameConfig = {
leveling: {
// Curve: Base * (Level ^ Exponent)
base: 100,
exponent: 2.5,
chat: {
cooldownMs: 60000, // 1 minute
minXp: 15,
maxXp: 25,
}
},
economy: {
daily: {
amount: 100n,
streakBonus: 10n,
cooldownMs: 24 * 60 * 60 * 1000, // 24 hours
},
transfers: {
// Future use
allowSelfTransfer: false,
minAmount: 1n,
}
},
inventory: {
maxStackSize: 999n,
maxSlots: 50,
}
} as const;

View File

@@ -50,6 +50,9 @@ export const items = pgTable('items', {
rarity: varchar('rarity', { length: 20 }).default('Common'),
// Economy & Visuals
type: varchar('type', { length: 50 }).notNull().default('MATERIAL'),
// Examples: 'CONSUMABLE', 'EQUIPMENT', 'MATERIAL'
usageData: jsonb('usage_data').default({}),
price: bigint('price', { mode: 'bigint' }),
iconUrl: text('icon_url').notNull(),
imageUrl: text('image_url').notNull(),
@@ -72,12 +75,28 @@ export const transactions = pgTable('transactions', {
id: bigserial('id', { mode: 'bigint' }).primaryKey(),
userId: bigint('user_id', { mode: 'bigint' })
.references(() => users.id, { onDelete: 'cascade' }),
relatedUserId: bigint('related_user_id', { mode: 'bigint' })
.references(() => users.id, { onDelete: 'set null' }),
amount: bigint('amount', { mode: 'bigint' }).notNull(),
type: varchar('type', { length: 50 }).notNull(),
description: text('description'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow(),
});
export const itemTransactions = pgTable('item_transactions', {
id: bigserial('id', { mode: 'bigint' }).primaryKey(),
userId: bigint('user_id', { mode: 'bigint' })
.references(() => users.id, { onDelete: 'cascade' }).notNull(),
relatedUserId: bigint('related_user_id', { mode: 'bigint' })
.references(() => users.id, { onDelete: 'set null' }), // who they got it from/gave it to
itemId: integer('item_id')
.references(() => items.id, { onDelete: 'cascade' }).notNull(),
quantity: bigint('quantity', { mode: 'bigint' }).notNull(), // positive = gain, negative = loss
type: varchar('type', { length: 50 }).notNull(), // e.g., 'TRADE', 'SHOP_BUY', 'DROP'
description: text('description'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow(),
});
// 6. Quests
export const quests = pgTable('quests', {
id: serial('id').primaryKey(),
@@ -100,14 +119,16 @@ export const userQuests = pgTable('user_quests', {
primaryKey({ columns: [table.userId, table.questId] })
]);
// 8. Cooldowns
export const cooldowns = pgTable('cooldowns', {
// 8. User Timers (Generic: Cooldowns, Effects, Access)
export const userTimers = pgTable('user_timers', {
userId: bigint('user_id', { mode: 'bigint' })
.references(() => users.id, { onDelete: 'cascade' }).notNull(),
actionKey: varchar('action_key', { length: 50 }).notNull(),
readyAt: timestamp('ready_at', { withTimezone: true }).notNull(),
type: varchar('type', { length: 50 }).notNull(), // 'COOLDOWN', 'EFFECT', 'ACCESS'
key: varchar('key', { length: 100 }).notNull(), // 'daily', 'chn_12345', 'xp_boost'
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
metadata: jsonb('metadata').default({}), // Store channelId, specific buff amounts, etc.
}, (table) => [
primaryKey({ columns: [table.userId, table.actionKey] })
primaryKey({ columns: [table.userId, table.type, table.key] })
]);
// --- RELATIONS ---
@@ -124,7 +145,7 @@ export const usersRelations = relations(users, ({ one, many }) => ({
inventory: many(inventory),
transactions: many(transactions),
quests: many(userQuests),
cooldowns: many(cooldowns),
timers: many(userTimers),
}));
export const itemsRelations = relations(items, ({ many }) => ({
@@ -164,9 +185,24 @@ export const userQuestsRelations = relations(userQuests, ({ one }) => ({
}),
}));
export const cooldownsRelations = relations(cooldowns, ({ one }) => ({
export const userTimersRelations = relations(userTimers, ({ one }) => ({
user: one(users, {
fields: [cooldowns.userId],
fields: [userTimers.userId],
references: [users.id],
}),
}));
export const itemTransactionsRelations = relations(itemTransactions, ({ one }) => ({
user: one(users, {
fields: [itemTransactions.userId],
references: [users.id],
}),
relatedUser: one(users, {
fields: [itemTransactions.relatedUserId],
references: [users.id],
}),
item: one(items, {
fields: [itemTransactions.itemId],
references: [items.id],
}),
}));

View File

@@ -0,0 +1,13 @@
import { Events } from "discord.js";
import type { Event } from "@lib/types";
const event: Event<Events.GuildMemberAdd> = {
name: Events.GuildMemberAdd,
execute: async (member) => {
const role = member.guild.roles.cache.find(role => role.name === "Visitor");
if (!role) return;
await member.roles.add(role);
},
};
export default event;

View File

@@ -0,0 +1,53 @@
import { Events, MessageFlags } from "discord.js";
import { KyokoClient } from "@lib/KyokoClient";
import { userService } from "@/modules/user/user.service";
import { createErrorEmbed } from "@lib/embeds";
import type { Event } from "@lib/types";
const event: Event<Events.InteractionCreate> = {
name: Events.InteractionCreate,
execute: async (interaction) => {
// Handle Trade Interactions
if (interaction.isButton() || interaction.isStringSelectMenu() || interaction.isModalSubmit()) {
if (interaction.customId.startsWith("trade_") || interaction.customId === "amount") {
await import("@/modules/trade/trade.interaction").then(m => m.handleTradeInteraction(interaction));
return;
}
}
if (!interaction.isChatInputCommand()) return;
const command = KyokoClient.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
// Ensure user exists in database
try {
const user = await userService.getUserById(interaction.user.id);
if (!user) {
console.log(`🆕 Creating new user entry for ${interaction.user.tag}`);
await userService.createUser(interaction.user.id, interaction.user.username);
}
} catch (error) {
console.error("Failed to check/create user:", error);
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
const errorEmbed = createErrorEmbed('There was an error while executing this command!');
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ embeds: [errorEmbed], flags: MessageFlags.Ephemeral });
} else {
await interaction.reply({ embeds: [errorEmbed], flags: MessageFlags.Ephemeral });
}
}
},
};
export default event;

View File

@@ -0,0 +1,19 @@
import { Events } from "discord.js";
import { userService } from "@/modules/user/user.service";
import { levelingService } from "@/modules/leveling/leveling.service";
import type { Event } from "@lib/types";
const event: Event<Events.MessageCreate> = {
name: Events.MessageCreate,
execute: async (message) => {
if (message.author.bot) return;
if (!message.guild) return;
const user = await userService.getUserById(message.author.id);
if (!user) return;
levelingService.processChatXp(message.author.id);
},
};
export default event;

14
src/events/ready.ts Normal file
View File

@@ -0,0 +1,14 @@
import { Events } from "discord.js";
import { schedulerService } from "@/modules/system/scheduler";
import type { Event } from "@lib/types";
const event: Event<Events.ClientReady> = {
name: Events.ClientReady,
once: true,
execute: async (c) => {
console.log(`Ready! Logged in as ${c.user.tag}`);
schedulerService.start();
},
};
export default event;

View File

@@ -29,7 +29,6 @@ export async function generateStudentIdCard(data: StudentCardData): Promise<Buff
// Draw Background Gradient with random hue
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
const hue = Math.random() * 360;
const saturation = 40 + Math.random() * 20; // 40-60%
const lightness = 20 + Math.random() * 20; // 20-40%
const color2 = `hsl(${Math.random() * 360}, ${saturation}%, ${lightness}%)`;

View File

@@ -1,62 +1,11 @@
import { Events } from "discord.js";
import { KyokoClient } from "@lib/KyokoClient";
import { env } from "@lib/env";
import { userService } from "@/modules/user/user.service";
import { levelingService } from "@/modules/leveling/leveling.service";
// Load commands
// Load commands & events
await KyokoClient.loadCommands();
await KyokoClient.loadEvents();
await KyokoClient.deployCommands();
KyokoClient.once(Events.ClientReady, async c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
// process xp on message
KyokoClient.on(Events.MessageCreate, async message => {
if (message.author.bot) return;
if (!message.guild) return;
const user = await userService.getUserById(message.author.id);
if (!user) return;
levelingService.processChatXp(message.author.id);
});
// handle commands
KyokoClient.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = KyokoClient.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
// Ensure user exists in database
try {
const user = await userService.getUserById(interaction.user.id);
if (!user) {
console.log(`🆕 Creating new user entry for ${interaction.user.tag}`);
await userService.createUser(interaction.user.id, interaction.user.username);
}
} catch (error) {
console.error("Failed to check/create user:", error);
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
});
// login with the token from .env
if (!env.DISCORD_BOT_TOKEN) {

View File

@@ -1,7 +1,7 @@
import { Client as DiscordClient, Collection, GatewayIntentBits, REST, Routes } from "discord.js";
import { readdir } from "node:fs/promises";
import { join } from "node:path";
import type { Command } from "@lib/types";
import type { Command, Event } from "@lib/types";
import { env } from "@lib/env";
class Client extends DiscordClient {
@@ -23,6 +23,16 @@ class Client extends DiscordClient {
await this.readCommandsRecursively(commandsPath, reload);
}
async loadEvents(reload: boolean = false) {
if (reload) {
this.removeAllListeners();
console.log("♻️ Reloading events...");
}
const eventsPath = join(import.meta.dir, '../events');
await this.readEventsRecursively(eventsPath, reload);
}
private async readCommandsRecursively(dir: string, reload: boolean = false) {
try {
const files = await readdir(dir, { withFileTypes: true });
@@ -63,10 +73,52 @@ class Client extends DiscordClient {
}
}
private async readEventsRecursively(dir: string, reload: boolean = false) {
try {
const files = await readdir(dir, { withFileTypes: true });
for (const file of files) {
const filePath = join(dir, file.name);
if (file.isDirectory()) {
await this.readEventsRecursively(filePath, reload);
continue;
}
if (!file.name.endsWith('.ts') && !file.name.endsWith('.js')) continue;
try {
const importPath = reload ? `${filePath}?t=${Date.now()}` : filePath;
const eventModule = await import(importPath);
const event = eventModule.default;
if (this.isValidEvent(event)) {
if (event.once) {
this.once(event.name, (...args) => event.execute(...args));
} else {
this.on(event.name, (...args) => event.execute(...args));
}
console.log(`✅ Loaded event: ${event.name}`);
} else {
console.warn(`⚠️ Skipping invalid event in ${file.name}`);
}
} catch (error) {
console.error(`❌ Failed to load event from ${filePath}:`, error);
}
}
} catch (error) {
console.error(`Error reading directory ${dir}:`, error);
}
}
private isValidCommand(command: any): command is Command {
return command && typeof command === 'object' && 'data' in command && 'execute' in command;
}
private isValidEvent(event: any): event is Event<any> {
return event && typeof event === 'object' && 'name' in event && 'execute' in event;
}
async deployCommands() {
// We use env.DISCORD_BOT_TOKEN directly so this can run without client.login()
const token = env.DISCORD_BOT_TOKEN;

57
src/lib/embeds.ts Normal file
View File

@@ -0,0 +1,57 @@
import { EmbedBuilder, Colors } from "discord.js";
/**
* Creates a standardized error embed.
* @param message The error message to display.
* @param title Optional title for the embed. Defaults to "Error".
* @returns An EmbedBuilder instance configured as an error.
*/
export function createErrorEmbed(message: string, title: string = "Error"): EmbedBuilder {
return new EmbedBuilder()
.setTitle(`${title}`)
.setDescription(message)
.setColor(Colors.Red)
.setTimestamp();
}
/**
* Creates a standardized warning embed.
* @param message The warning message to display.
* @param title Optional title for the embed. Defaults to "Warning".
* @returns An EmbedBuilder instance configured as a warning.
*/
export function createWarningEmbed(message: string, title: string = "Warning"): EmbedBuilder {
return new EmbedBuilder()
.setTitle(`⚠️ ${title}`)
.setDescription(message)
.setColor(Colors.Yellow)
.setTimestamp();
}
/**
* Creates a standardized success embed.
* @param message The success message to display.
* @param title Optional title for the embed. Defaults to "Success".
* @returns An EmbedBuilder instance configured as a success.
*/
export function createSuccessEmbed(message: string, title: string = "Success"): EmbedBuilder {
return new EmbedBuilder()
.setTitle(`${title}`)
.setDescription(message)
.setColor(Colors.Green)
.setTimestamp();
}
/**
* Creates a standardized info embed.
* @param message The info message to display.
* @param title Optional title for the embed. Defaults to "Info".
* @returns An EmbedBuilder instance configured as info.
*/
export function createInfoEmbed(message: string, title: string = "Info"): EmbedBuilder {
return new EmbedBuilder()
.setTitle(` ${title}`)
.setDescription(message)
.setColor(Colors.Blue)
.setTimestamp();
}

View File

@@ -1,6 +1,12 @@
import type { ChatInputCommandInteraction, SlashCommandBuilder, SlashCommandOptionsOnlyBuilder, SlashCommandSubcommandsOnlyBuilder } from "discord.js";
import type { ChatInputCommandInteraction, ClientEvents, SlashCommandBuilder, SlashCommandOptionsOnlyBuilder, SlashCommandSubcommandsOnlyBuilder } from "discord.js";
export interface Command {
data: SlashCommandBuilder | SlashCommandOptionsOnlyBuilder | SlashCommandSubcommandsOnlyBuilder;
execute: (interaction: ChatInputCommandInteraction) => Promise<void> | void;
}
export interface Event<K extends keyof ClientEvents> {
name: K;
once?: boolean;
execute: (...args: ClientEvents[K]) => Promise<void> | void;
}

View File

@@ -1,10 +1,7 @@
import { users, transactions, cooldowns } from "@/db/schema";
import { users, transactions, userTimers } from "@/db/schema";
import { eq, sql, and } from "drizzle-orm";
import { DrizzleClient } from "@/lib/DrizzleClient";
const DAILY_REWARD_AMOUNT = 100n;
const STREAK_BONUS = 10n;
const DAILY_COOLDOWN = 24 * 60 * 60 * 1000; // 24 hours in ms
import { GameConfig } from "@/config/game";
export const economyService = {
transfer: async (fromUserId: string, toUserId: string, amount: bigint, tx?: any) => {
@@ -80,15 +77,16 @@ export const economyService = {
startOfDay.setHours(0, 0, 0, 0);
// Check cooldown
const cooldown = await txFn.query.cooldowns.findFirst({
const cooldown = await txFn.query.userTimers.findFirst({
where: and(
eq(cooldowns.userId, BigInt(userId)),
eq(cooldowns.actionKey, 'daily')
eq(userTimers.userId, BigInt(userId)),
eq(userTimers.type, 'COOLDOWN'),
eq(userTimers.key, 'daily')
),
});
if (cooldown && cooldown.readyAt > now) {
throw new Error(`Daily already claimed. Ready at ${cooldown.readyAt}`);
if (cooldown && cooldown.expiresAt > now) {
throw new Error(`Daily already claimed. Ready at ${cooldown.expiresAt}`);
}
// Get user for streak logic
@@ -102,22 +100,19 @@ export const economyService = {
let streak = (user.dailyStreak || 0) + 1;
// If previous cooldown exists and expired more than 24h ago (meaning >48h since last claim), reset streak
// If previous cooldown exists and expired more than 24h ago (meaning >48h since last claim), reduce streak by one for each day passed minimum 1
if (cooldown) {
const timeSinceReady = now.getTime() - cooldown.readyAt.getTime();
const timeSinceReady = now.getTime() - cooldown.expiresAt.getTime();
if (timeSinceReady > 24 * 60 * 60 * 1000) {
streak = 1;
streak = Math.max(1, streak - Math.floor(timeSinceReady / (24 * 60 * 60 * 1000)));
}
} else {
streak = 1;
}
const bonus = (BigInt(streak) - 1n) * STREAK_BONUS;
const bonus = (BigInt(streak) - 1n) * GameConfig.economy.daily.streakBonus;
const totalReward = DAILY_REWARD_AMOUNT + bonus;
// Update User w/ Economy Service (reuse modifyUserBalance if we split it out, but here manual is fine for atomic combined streak update)
// Actually, we can just update directly here as we are already refining specific fields like streak.
const totalReward = GameConfig.economy.daily.amount + bonus;
await txFn.update(users)
.set({
balance: sql`${users.balance} + ${totalReward}`,
@@ -127,17 +122,18 @@ export const economyService = {
.where(eq(users.id, BigInt(userId)));
// Set new cooldown (now + 24h)
const nextReadyAt = new Date(now.getTime() + DAILY_COOLDOWN);
const nextReadyAt = new Date(now.getTime() + GameConfig.economy.daily.cooldownMs);
await txFn.insert(cooldowns)
await txFn.insert(userTimers)
.values({
userId: BigInt(userId),
actionKey: 'daily',
readyAt: nextReadyAt,
type: 'COOLDOWN',
key: 'daily',
expiresAt: nextReadyAt,
})
.onConflictDoUpdate({
target: [cooldowns.userId, cooldowns.actionKey],
set: { readyAt: nextReadyAt },
target: [userTimers.userId, userTimers.type, userTimers.key],
set: { expiresAt: nextReadyAt },
});
// Log Transaction
@@ -160,7 +156,7 @@ export const economyService = {
}
},
modifyUserBalance: async (id: string, amount: bigint, type: string, description: string, tx?: any) => {
modifyUserBalance: async (id: string, amount: bigint, type: string, description: string, relatedUserId?: string | null, tx?: any) => {
const execute = async (txFn: any) => {
if (amount < 0n) {
// Check sufficient funds if removing
@@ -181,6 +177,7 @@ export const economyService = {
await txFn.insert(transactions).values({
userId: BigInt(id),
relatedUserId: relatedUserId ? BigInt(relatedUserId) : null,
amount: amount,
type: type,
description: description,

View File

@@ -1,8 +1,9 @@
import { inventory, items, users } from "@/db/schema";
import { eq, and, sql } from "drizzle-orm";
import { eq, and, sql, count } from "drizzle-orm";
import { DrizzleClient } from "@/lib/DrizzleClient";
import { economyService } from "@/modules/economy/economy.service";
import { GameConfig } from "@/config/game";
export const inventoryService = {
addItem: async (userId: string, itemId: number, quantity: bigint = 1n, tx?: any) => {
@@ -16,9 +17,14 @@ export const inventoryService = {
});
if (existing) {
const newQuantity = (existing.quantity ?? 0n) + quantity;
if (newQuantity > GameConfig.inventory.maxStackSize) {
throw new Error(`Cannot exceed max stack size of ${GameConfig.inventory.maxStackSize}`);
}
const [entry] = await txFn.update(inventory)
.set({
quantity: sql`${inventory.quantity} + ${quantity}`,
quantity: newQuantity,
})
.where(and(
eq(inventory.userId, BigInt(userId)),
@@ -27,6 +33,20 @@ export const inventoryService = {
.returning();
return entry;
} else {
// Check Slot Limit
const [inventoryCount] = await txFn
.select({ count: count() })
.from(inventory)
.where(eq(inventory.userId, BigInt(userId)));
if (inventoryCount.count >= GameConfig.inventory.maxSlots) {
throw new Error(`Inventory full (Max ${GameConfig.inventory.maxSlots} slots)`);
}
if (quantity > GameConfig.inventory.maxStackSize) {
throw new Error(`Cannot exceed max stack size of ${GameConfig.inventory.maxStackSize}`);
}
const [entry] = await txFn.insert(inventory)
.values({
userId: BigInt(userId),
@@ -98,23 +118,9 @@ export const inventoryService = {
const totalPrice = item.price * quantity;
// Deduct Balance using economy service (passing tx ensures atomicity)
await economyService.modifyUserBalance(userId, -totalPrice, 'PURCHASE', `Bought ${quantity}x ${item.name}`, txFn);
await economyService.modifyUserBalance(userId, -totalPrice, 'PURCHASE', `Bought ${quantity}x ${item.name}`, null, txFn);
// Add Item (using local logic to keep in same tx, or could refactor addItem to take tx too and call it)
// Let's refactor addItem below to accept tx, then call it here?
// Since we are modifying buyItem, we can just inline the item addition or call addItem if we update it.
// Let's assume we update addItem next. For now, inline the add logic but cleaner.
const existingInv = await txFn.query.inventory.findFirst({
where: and(eq(inventory.userId, BigInt(userId)), eq(inventory.itemId, itemId)),
});
if (existingInv) {
await txFn.update(inventory).set({ quantity: sql`${inventory.quantity} + ${quantity}` })
.where(and(eq(inventory.userId, BigInt(userId)), eq(inventory.itemId, itemId)));
} else {
await txFn.insert(inventory).values({ userId: BigInt(userId), itemId, quantity });
}
await inventoryService.addItem(userId, itemId, quantity, txFn);
return { success: true, item, totalPrice };
};

View File

@@ -1,18 +1,12 @@
import { users, cooldowns } from "@/db/schema";
import { users, userTimers } from "@/db/schema";
import { eq, sql, and } from "drizzle-orm";
import { DrizzleClient } from "@/lib/DrizzleClient";
// Simple configurable curve: Base * (Level ^ Exponent)
const XP_BASE = 100;
const XP_EXPONENT = 2.5;
const CHAT_XP_COOLDOWN_MS = 60000; // 1 minute
const MIN_CHAT_XP = 15;
const MAX_CHAT_XP = 25;
import { GameConfig } from "@/config/game";
export const levelingService = {
// Calculate XP required for a specific level
getXpForLevel: (level: number) => {
return Math.floor(XP_BASE * Math.pow(level, XP_EXPONENT));
return Math.floor(GameConfig.leveling.base * Math.pow(level, GameConfig.leveling.exponent));
},
// Pure XP addition - No cooldown checks
@@ -64,36 +58,38 @@ export const levelingService = {
processChatXp: async (id: string, tx?: any) => {
const execute = async (txFn: any) => {
// check if an xp cooldown is in place
const cooldown = await txFn.query.cooldowns.findFirst({
const cooldown = await txFn.query.userTimers.findFirst({
where: and(
eq(cooldowns.userId, BigInt(id)),
eq(cooldowns.actionKey, 'xp')
eq(userTimers.userId, BigInt(id)),
eq(userTimers.type, 'COOLDOWN'),
eq(userTimers.key, 'chat_xp')
),
});
const now = new Date();
if (cooldown && cooldown.readyAt > now) {
if (cooldown && cooldown.expiresAt > now) {
return { awarded: false, reason: 'cooldown' };
}
// Calculate random XP
const amount = BigInt(Math.floor(Math.random() * (MAX_CHAT_XP - MIN_CHAT_XP + 1)) + MIN_CHAT_XP);
const amount = BigInt(Math.floor(Math.random() * (GameConfig.leveling.chat.maxXp - GameConfig.leveling.chat.minXp + 1)) + GameConfig.leveling.chat.minXp);
// Add XP
const result = await levelingService.addXp(id, amount, txFn);
// Update/Set Cooldown
const nextReadyAt = new Date(now.getTime() + CHAT_XP_COOLDOWN_MS);
const nextReadyAt = new Date(now.getTime() + GameConfig.leveling.chat.cooldownMs);
await txFn.insert(cooldowns)
await txFn.insert(userTimers)
.values({
userId: BigInt(id),
actionKey: 'xp',
readyAt: nextReadyAt,
type: 'COOLDOWN',
key: 'chat_xp',
expiresAt: nextReadyAt,
})
.onConflictDoUpdate({
target: [cooldowns.userId, cooldowns.actionKey],
set: { readyAt: nextReadyAt },
target: [userTimers.userId, userTimers.type, userTimers.key],
set: { expiresAt: nextReadyAt },
});
return { awarded: true, amount, ...result };

View File

@@ -62,7 +62,7 @@ export const questService = {
if (rewards?.balance) {
const bal = BigInt(rewards.balance);
await economyService.modifyUserBalance(userId, bal, 'QUEST_REWARD', `Reward for quest ${questId}`, txFn);
await economyService.modifyUserBalance(userId, bal, 'QUEST_REWARD', `Reward for quest ${questId}`, null, txFn);
results.balance = bal;
}

View File

@@ -0,0 +1,57 @@
import { userTimers } from "@/db/schema";
import { eq, and, lt } from "drizzle-orm";
import { DrizzleClient } from "@/lib/DrizzleClient";
/**
* The Janitor responsible for cleaning up expired ACCESS timers
* and revoking privileges.
*/
export const schedulerService = {
start: () => {
console.log("🕒 Scheduler started: Janitor loop running every 60s");
// Run immediately on start
schedulerService.runJanitor();
// Loop every 60 seconds
setInterval(() => {
schedulerService.runJanitor();
}, 60 * 1000);
},
runJanitor: async () => {
try {
// Find all expired ACCESS timers
// We do this in a transaction to ensure we read and delete atomically if possible,
// though for this specific case, fetching then deleting is fine as long as we handle race conditions gracefully.
const now = new Date();
const expiredAccess = await DrizzleClient.query.userTimers.findMany({
where: and(
eq(userTimers.type, 'ACCESS'),
lt(userTimers.expiresAt, now)
)
});
if (expiredAccess.length === 0) return;
console.log(`🧹 Janitor: Found ${expiredAccess.length} expired access timers.`);
for (const timer of expiredAccess) {
// TODO: Here we would call Discord API to remove roles/overwrites.
const meta = timer.metadata as any;
console.log(`🚫 Revoking access for User ${timer.userId}: Key=${timer.key} (Channel: ${meta?.channelId || 'N/A'})`);
// Delete the timer row
await DrizzleClient.delete(userTimers)
.where(and(
eq(userTimers.userId, timer.userId),
eq(userTimers.type, timer.type),
eq(userTimers.key, timer.key)
));
}
} catch (error) {
console.error("Janitor Error:", error);
}
}
};

View File

@@ -0,0 +1,335 @@
import {
ButtonInteraction,
ModalSubmitInteraction,
StringSelectMenuInteraction,
type Interaction,
EmbedBuilder,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
StringSelectMenuBuilder,
ModalBuilder,
TextInputBuilder,
TextInputStyle,
ThreadChannel,
TextChannel,
} from "discord.js";
import { TradeService } from "./trade.service";
import { inventoryService } from "@/modules/inventory/inventory.service";
import { createErrorEmbed, createWarningEmbed, createSuccessEmbed, createInfoEmbed } from "@lib/embeds";
const EMBED_COLOR = 0xFFD700; // Gold
export async function handleTradeInteraction(interaction: Interaction) {
if (!interaction.isButton() && !interaction.isStringSelectMenu() && !interaction.isModalSubmit()) return;
const { customId } = interaction;
const threadId = interaction.channelId;
if (!threadId) return;
try {
if (customId === 'trade_cancel') {
await handleCancel(interaction, threadId);
} else if (customId === 'trade_lock') {
await handleLock(interaction, threadId);
} else if (customId === 'trade_confirm') {
// Confirm logic is handled implicitly by both locking or explicitly if needed.
// For now, locking both triggers execution, so no separate confirm handler is actively used
// unless we re-introduce a specific button. keeping basic handler stub if needed.
} else if (customId === 'trade_add_money') {
await handleAddMoneyClick(interaction);
} else if (customId === 'trade_money_modal') {
await handleMoneySubmit(interaction as ModalSubmitInteraction, threadId);
} else if (customId === 'trade_add_item') {
await handleAddItemClick(interaction as ButtonInteraction, threadId);
} else if (customId === 'trade_select_item') {
await handleItemSelect(interaction as StringSelectMenuInteraction, threadId);
} else if (customId === 'trade_remove_item') {
await handleRemoveItemClick(interaction as ButtonInteraction, threadId);
} else if (customId === 'trade_remove_item_select') {
await handleRemoveItemSelect(interaction as StringSelectMenuInteraction, threadId);
}
} catch (error: any) {
const errorEmbed = createErrorEmbed(error.message);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ embeds: [errorEmbed], ephemeral: true });
} else {
await interaction.reply({ embeds: [errorEmbed], ephemeral: true });
}
}
}
async function handleCancel(interaction: ButtonInteraction | StringSelectMenuInteraction | ModalSubmitInteraction, threadId: string) {
const session = TradeService.getSession(threadId);
const user = interaction.user;
TradeService.endSession(threadId);
await interaction.deferUpdate();
if (interaction.channel?.isThread()) {
const embed = createInfoEmbed(`Trade cancelled by ${user.username}.`, "Trade Cancelled");
await scheduleThreadCleanup(interaction.channel, "This thread will be deleted in 5 seconds.", 5000, embed);
}
}
async function handleLock(interaction: ButtonInteraction | StringSelectMenuInteraction | ModalSubmitInteraction, threadId: string) {
await interaction.deferUpdate();
const isLocked = TradeService.toggleLock(threadId, interaction.user.id);
await updateTradeDashboard(interaction, threadId);
// Check if trade executed (both locked)
const session = TradeService.getSession(threadId);
if (session && session.state === 'COMPLETED') {
// Trade executed during updateTradeDashboard
return;
}
await interaction.followUp({ content: isLocked ? "🔒 You locked your offer." : "<22> You unlocked your offer.", ephemeral: true });
}
async function handleAddMoneyClick(interaction: Interaction) {
if (!interaction.isButton()) return;
const modal = new ModalBuilder()
.setCustomId('trade_money_modal')
.setTitle('Add Money');
const input = new TextInputBuilder()
.setCustomId('amount')
.setLabel("Amount to trade")
.setStyle(TextInputStyle.Short)
.setPlaceholder("100")
.setRequired(true);
const row = new ActionRowBuilder<TextInputBuilder>().addComponents(input);
modal.addComponents(row);
await interaction.showModal(modal);
}
async function handleMoneySubmit(interaction: ModalSubmitInteraction, threadId: string) {
const amountStr = interaction.fields.getTextInputValue('amount');
const amount = BigInt(amountStr);
if (amount < 0n) throw new Error("Amount must be positive");
TradeService.updateMoney(threadId, interaction.user.id, amount);
await interaction.deferUpdate(); // Acknowledge modal
await updateTradeDashboard(interaction, threadId);
}
async function handleAddItemClick(interaction: ButtonInteraction, threadId: string) {
const inventory = await inventoryService.getInventory(interaction.user.id);
if (inventory.length === 0) {
await interaction.reply({ embeds: [createWarningEmbed("Your inventory is empty.")], ephemeral: true });
return;
}
// Slice top 25 for select menu
const options = inventory.slice(0, 25).map(entry => ({
label: `${entry.item.name} (${entry.quantity})`,
value: entry.item.id.toString(),
description: `Rarity: ${entry.item.rarity}`
}));
const select = new StringSelectMenuBuilder()
.setCustomId('trade_select_item')
.setPlaceholder('Select an item to add')
.addOptions(options);
const row = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(select);
await interaction.reply({ content: "Select an item to add:", components: [row], ephemeral: true });
}
async function handleItemSelect(interaction: StringSelectMenuInteraction, threadId: string) {
const value = interaction.values[0];
if (!value) return;
const itemId = parseInt(value);
// Assuming implementation implies adding 1 item for now
const item = await inventoryService.getItem(itemId);
if (!item) throw new Error("Item not found");
TradeService.addItem(threadId, interaction.user.id, { id: item.id, name: item.name }, 1n);
await interaction.update({ content: `Added ${item.name} x1`, components: [] });
await updateTradeDashboard(interaction, threadId);
}
async function handleRemoveItemClick(interaction: ButtonInteraction, threadId: string) {
const session = TradeService.getSession(threadId);
if (!session) return;
const participant = session.userA.id === interaction.user.id ? session.userA : session.userB;
if (participant.offer.items.length === 0) {
await interaction.reply({ embeds: [createWarningEmbed("No items in offer to remove.")], ephemeral: true });
return;
}
const options = participant.offer.items.slice(0, 25).map(i => ({
label: `${i.name} (${i.quantity})`,
value: i.id.toString(),
}));
const select = new StringSelectMenuBuilder()
.setCustomId('trade_remove_item_select')
.setPlaceholder('Select an item to remove')
.addOptions(options);
const row = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(select);
await interaction.reply({ content: "Select an item to remove:", components: [row], ephemeral: true });
}
async function handleRemoveItemSelect(interaction: StringSelectMenuInteraction, threadId: string) {
const value = interaction.values[0];
if (!value) return;
const itemId = parseInt(value);
TradeService.removeItem(threadId, interaction.user.id, itemId);
await interaction.update({ content: `Removed item.`, components: [] });
await updateTradeDashboard(interaction, threadId);
}
// --- DASHBOARD UPDATER ---
export async function updateTradeDashboard(interaction: Interaction, threadId: string) {
const session = TradeService.getSession(threadId);
if (!session) return;
// Check Auto-Execute (If both locked)
if (session.userA.locked && session.userB.locked) {
// Execute Trade
try {
await TradeService.executeTrade(threadId);
const embed = new EmbedBuilder()
.setTitle("✅ Trade Completed")
.setColor("Green")
.addFields(
{ name: session.userA.username, value: formatOffer(session.userA), inline: true },
{ name: session.userB.username, value: formatOffer(session.userB), inline: true }
)
.setTimestamp();
await updateDashboardMessage(interaction, { embeds: [embed], components: [] });
// Notify and Schedule Cleanup
if (interaction.channel?.isThread()) {
const successEmbed = createSuccessEmbed("Trade executed successfully. Items and funds have been transferred.", "Trade Complete");
await scheduleThreadCleanup(
interaction.channel,
`🎉 Trade successful! <@${session.userA.id}> <@${session.userB.id}>\nThis thread will be deleted in 10 seconds.`,
10000,
successEmbed
);
}
return;
} catch (e: any) {
console.error("Trade Execution Error:", e);
const errorEmbed = createErrorEmbed(e.message, "Trade Failed");
if (interaction.channel?.isThread()) {
await scheduleThreadCleanup(
interaction.channel,
"❌ Trade failed due to an error. This thread will be deleted in 10 seconds.",
10000,
errorEmbed
);
}
return;
}
}
// Build Status Embed
const embed = new EmbedBuilder()
.setTitle("🤝 Trading Session")
.setColor(EMBED_COLOR)
.addFields(
{
name: `${session.userA.username} ${session.userA.locked ? '✅ (Ready)' : '✏️ (Editing)'}`,
value: formatOffer(session.userA),
inline: true
},
{
name: `${session.userB.username} ${session.userB.locked ? '✅ (Ready)' : '✏️ (Editing)'}`,
value: formatOffer(session.userB),
inline: true
}
)
.setFooter({ text: "Both parties must click Lock to confirm trade." });
const row = new ActionRowBuilder<ButtonBuilder>()
.addComponents(
new ButtonBuilder().setCustomId('trade_add_item').setLabel('Add Item').setStyle(ButtonStyle.Secondary),
new ButtonBuilder().setCustomId('trade_add_money').setLabel('Add Money').setStyle(ButtonStyle.Success),
new ButtonBuilder().setCustomId('trade_remove_item').setLabel('Remove Item').setStyle(ButtonStyle.Secondary),
new ButtonBuilder().setCustomId('trade_lock').setLabel('Lock / Unlock').setStyle(ButtonStyle.Primary),
new ButtonBuilder().setCustomId('trade_cancel').setLabel('Cancel').setStyle(ButtonStyle.Danger),
);
await updateDashboardMessage(interaction, { embeds: [embed], components: [row] });
}
async function updateDashboardMessage(interaction: Interaction, payload: any) {
if (interaction.isButton() && interaction.message) {
// If interaction came from the dashboard itself, we can edit directly
try {
await interaction.message.edit(payload);
} catch (e) {
console.error("Failed to edit message directly", e);
}
} else {
// Find dashboard in channel
const channel = interaction.channel as ThreadChannel;
if (channel && channel.isThread()) {
try {
const messages = await channel.messages.fetch({ limit: 10 });
const dashboardFn = messages.find(m => m.embeds[0]?.title === "🤝 Trading Session");
if (dashboardFn) {
await dashboardFn.edit(payload);
}
} catch (e) {
console.error("Failed to fetch/edit dashboard", e);
}
}
}
}
function formatOffer(participant: any) {
let text = "";
if (participant.offer.money > 0n) {
text += `💰 ${participant.offer.money} 🪙\n`;
}
if (participant.offer.items.length > 0) {
text += participant.offer.items.map((i: any) => `- ${i.name} (x${i.quantity})`).join("\n");
}
if (text === "") text = "*Empty Offer*";
return text;
}
async function scheduleThreadCleanup(channel: ThreadChannel | TextChannel, message: string, delayMs: number = 10000, embed?: EmbedBuilder) {
try {
const payload: any = { content: message };
if (embed) payload.embeds = [embed];
await channel.send(payload);
setTimeout(async () => {
try {
if (channel.isThread()) {
console.log(`Deleting thread: ${channel.id}`);
await channel.delete("Trade Session Ended");
}
} catch (e) {
console.error("Failed to delete thread", e);
}
}, delayMs);
} catch (e) {
console.error("Failed to send cleanup notification", e);
}
}

View File

@@ -0,0 +1,189 @@
import type { TradeSession, TradeParticipant } from "./trade.types";
import { DrizzleClient } from "@/lib/DrizzleClient";
import { economyService } from "@/modules/economy/economy.service";
import { inventoryService } from "@/modules/inventory/inventory.service";
import { itemTransactions } from "@/db/schema";
export class TradeService {
private static sessions = new Map<string, TradeSession>();
/**
* Creates a new trade session
*/
static createSession(threadId: string, userA: { id: string, username: string }, userB: { id: string, username: string }): TradeSession {
const session: TradeSession = {
threadId,
userA: {
id: userA.id,
username: userA.username,
locked: false,
offer: { money: 0n, items: [] }
},
userB: {
id: userB.id,
username: userB.username,
locked: false,
offer: { money: 0n, items: [] }
},
state: 'NEGOTIATING',
lastInteraction: Date.now()
};
this.sessions.set(threadId, session);
return session;
}
static getSession(threadId: string): TradeSession | undefined {
return this.sessions.get(threadId);
}
static endSession(threadId: string) {
this.sessions.delete(threadId);
}
/**
* Updates an offer. If allowed, validation checks should be done BEFORE calling this.
* unlocking logic is handled here (if offer changes, unlock both).
*/
static updateMoney(threadId: string, userId: string, amount: bigint) {
const session = this.getSession(threadId);
if (!session) throw new Error("Session not found");
if (session.state !== 'NEGOTIATING') throw new Error("Trade is not active");
const participant = session.userA.id === userId ? session.userA : session.userB.id === userId ? session.userB : null;
if (!participant) throw new Error("User not in trade");
participant.offer.money = amount;
this.unlockAll(session);
session.lastInteraction = Date.now();
}
static addItem(threadId: string, userId: string, item: { id: number, name: string }, quantity: bigint) {
const session = this.getSession(threadId);
if (!session) throw new Error("Session not found");
if (session.state !== 'NEGOTIATING') throw new Error("Trade is not active");
const participant = session.userA.id === userId ? session.userA : session.userB.id === userId ? session.userB : null;
if (!participant) throw new Error("User not in trade");
const existing = participant.offer.items.find(i => i.id === item.id);
if (existing) {
existing.quantity += quantity;
} else {
participant.offer.items.push({ id: item.id, name: item.name, quantity });
}
this.unlockAll(session);
session.lastInteraction = Date.now();
}
static removeItem(threadId: string, userId: string, itemId: number) {
const session = this.getSession(threadId);
if (!session) throw new Error("Session not found");
const participant = session.userA.id === userId ? session.userA : session.userB.id === userId ? session.userB : null;
if (!participant) throw new Error("User not in trade");
participant.offer.items = participant.offer.items.filter(i => i.id !== itemId);
this.unlockAll(session);
session.lastInteraction = Date.now();
}
static toggleLock(threadId: string, userId: string): boolean {
const session = this.getSession(threadId);
if (!session) throw new Error("Session not found");
const participant = session.userA.id === userId ? session.userA : session.userB.id === userId ? session.userB : null;
if (!participant) throw new Error("User not in trade");
participant.locked = !participant.locked;
session.lastInteraction = Date.now();
return participant.locked;
}
private static unlockAll(session: TradeSession) {
session.userA.locked = false;
session.userB.locked = false;
}
/**
* Executes the trade atomically.
* 1. Validates balances/inventory for both users.
* 2. Swaps money.
* 3. Swaps items.
* 4. Logs transactions.
*/
static async executeTrade(threadId: string): Promise<void> {
const session = this.getSession(threadId);
if (!session) throw new Error("Session not found");
if (!session.userA.locked || !session.userB.locked) {
throw new Error("Both players must accept the trade first.");
}
session.state = 'COMPLETED'; // Prevent double execution
await DrizzleClient.transaction(async (tx) => {
// -- Validate & Execute User A -> User B --
await this.processTransfer(tx, session.userA, session.userB, session.threadId);
// -- Validate & Execute User B -> User A --
await this.processTransfer(tx, session.userB, session.userA, session.threadId);
});
this.endSession(threadId);
}
private static async processTransfer(tx: any, from: TradeParticipant, to: TradeParticipant, threadId: string) {
// 1. Money
if (from.offer.money > 0n) {
await economyService.modifyUserBalance(
from.id,
-from.offer.money,
'TRADE_OUT',
`Trade with ${to.username} (Thread: ${threadId})`,
to.id,
tx
);
await economyService.modifyUserBalance(
to.id,
from.offer.money,
'TRADE_IN',
`Trade with ${from.username} (Thread: ${threadId})`,
from.id,
tx
);
}
// 2. Items
for (const item of from.offer.items) {
// Remove from sender
await inventoryService.removeItem(from.id, item.id, item.quantity, tx);
// Add to receiver
await inventoryService.addItem(to.id, item.id, item.quantity, tx);
// Log Item Transaction (Sender)
await tx.insert(itemTransactions).values({
userId: BigInt(from.id),
relatedUserId: BigInt(to.id),
itemId: item.id,
quantity: -item.quantity,
type: 'TRADE_OUT',
description: `Traded to ${to.username}`,
});
// Log Item Transaction (Receiver)
await tx.insert(itemTransactions).values({
userId: BigInt(to.id),
relatedUserId: BigInt(from.id),
itemId: item.id,
quantity: item.quantity,
type: 'TRADE_IN',
description: `Received from ${from.username}`,
});
}
}
}

View File

@@ -0,0 +1,28 @@
export interface TradeItem {
id: number;
name: string; // Cache name for UI display
quantity: bigint;
}
export interface TradeOffer {
money: bigint;
items: TradeItem[]; // easier to iterate for UI than Map
}
export interface TradeParticipant {
id: string;
username: string;
locked: boolean;
offer: TradeOffer;
}
export type TradeState = 'NEGOTIATING' | 'COMPLETED' | 'CANCELLED';
export interface TradeSession {
threadId: string;
userA: TradeParticipant;
userB: TradeParticipant;
state: TradeState;
lastInteraction: number;
}

View File

@@ -0,0 +1,96 @@
import { userTimers } from "@/db/schema";
import { eq, and, lt } from "drizzle-orm";
import { DrizzleClient } from "@/lib/DrizzleClient";
export type TimerType = 'COOLDOWN' | 'EFFECT' | 'ACCESS';
export const userTimerService = {
/**
* Set a timer for a user.
* Upserts the timer (updates expiration if exists).
*/
setTimer: async (userId: string, type: TimerType, key: string, durationMs: number, metadata: any = {}, tx?: any) => {
const execute = async (txFn: any) => {
const expiresAt = new Date(Date.now() + durationMs);
await txFn.insert(userTimers)
.values({
userId: BigInt(userId),
type,
key,
expiresAt,
metadata,
})
.onConflictDoUpdate({
target: [userTimers.userId, userTimers.type, userTimers.key],
set: { expiresAt, metadata }, // Update metadata too on re-set
});
return expiresAt;
};
if (tx) {
return await execute(tx);
} else {
return await DrizzleClient.transaction(async (t) => {
return await execute(t);
});
}
},
/**
* Check if a timer is active (not expired).
* Returns true if ACTIVE.
*/
checkTimer: async (userId: string, type: TimerType, key: string, tx?: any): Promise<boolean> => {
const uniqueTx = tx || DrizzleClient; // Optimization: Read-only doesn't strictly need transaction wrapper overhead if single query
const timer = await uniqueTx.query.userTimers.findFirst({
where: and(
eq(userTimers.userId, BigInt(userId)),
eq(userTimers.type, type),
eq(userTimers.key, key)
),
});
if (!timer) return false;
return timer.expiresAt > new Date();
},
/**
* Get timer details including metadata and expiry.
*/
getTimer: async (userId: string, type: TimerType, key: string, tx?: any) => {
const uniqueTx = tx || DrizzleClient;
return await uniqueTx.query.userTimers.findFirst({
where: and(
eq(userTimers.userId, BigInt(userId)),
eq(userTimers.type, type),
eq(userTimers.key, key)
),
});
},
/**
* Manually clear a timer.
*/
clearTimer: async (userId: string, type: TimerType, key: string, tx?: any) => {
const execute = async (txFn: any) => {
await txFn.delete(userTimers)
.where(and(
eq(userTimers.userId, BigInt(userId)),
eq(userTimers.type, type),
eq(userTimers.key, key)
));
};
if (tx) {
return await execute(tx);
} else {
return await DrizzleClient.transaction(async (t) => {
return await execute(t);
});
}
}
};