10 Commits

24 changed files with 527 additions and 136 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

@@ -13,9 +13,9 @@ export const daily = createCommand({
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")

View File

@@ -8,7 +8,7 @@ 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")
@@ -41,7 +41,7 @@ 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();

View File

@@ -8,7 +8,8 @@ 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";
@@ -31,7 +32,7 @@ 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;
@@ -90,7 +91,7 @@ export const sell = createCommand({
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);
@@ -118,7 +119,7 @@ async function handleBuyInteraction(interaction: ButtonInteraction, item: typeof
if (interaction.deferred || interaction.replied) {
await interaction.editReply({ content: "", embeds: [createErrorEmbed("An error occurred while processing your purchase.")] });
} else {
await interaction.reply({ embeds: [createErrorEmbed("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,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] });
}
});

View File

@@ -119,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 ---
@@ -143,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 }) => ({
@@ -183,9 +185,9 @@ 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],
}),
}));

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

@@ -1,76 +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";
import { createErrorEmbed } from "@lib/embeds";
// 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 => {
// Handle Trade Interactions
if (interaction.isButton() || interaction.isStringSelectMenu() || interaction.isModalSubmit()) {
if (interaction.customId.startsWith("trade_") || interaction.customId === "amount") { // "amount" is the text input id, usually interaction wrapper keeps customId of modal?
// Wait, ModalSubmitInteraction customId IS likely 'trade_money_modal'.
// The components INSIDE have IDs. The Interaction has the Modal ID.
// So checking startWith("trade_") is correct for the modal itself.
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], ephemeral: true });
} else {
await interaction.reply({ embeds: [errorEmbed], 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;

View File

@@ -27,3 +27,31 @@ export function createWarningEmbed(message: string, title: string = "Warning"):
.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,4 +1,4 @@
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";
import { GameConfig } from "@/config/game";
@@ -77,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
@@ -99,11 +100,11 @@ 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;
@@ -112,9 +113,6 @@ export const economyService = {
const bonus = (BigInt(streak) - 1n) * GameConfig.economy.daily.streakBonus;
const totalReward = GameConfig.economy.daily.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.
await txFn.update(users)
.set({
balance: sql`${users.balance} + ${totalReward}`,
@@ -126,15 +124,16 @@ export const economyService = {
// Set new cooldown (now + 24h)
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
@@ -157,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
@@ -178,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

@@ -118,15 +118,8 @@ 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.
// Add Item using inner logic or self-call if we refactor properly.
// Calling addItem directly within the same transaction scope:
await inventoryService.addItem(userId, itemId, quantity, txFn);
return { success: true, item, totalPrice };

View File

@@ -1,4 +1,4 @@
import { users, cooldowns } from "@/db/schema";
import { users, userTimers } from "@/db/schema";
import { eq, sql, and } from "drizzle-orm";
import { DrizzleClient } from "@/lib/DrizzleClient";
import { GameConfig } from "@/config/game";
@@ -58,15 +58,16 @@ 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' };
}
@@ -79,15 +80,16 @@ export const levelingService = {
// Update/Set Cooldown
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

@@ -16,7 +16,7 @@ import {
} from "discord.js";
import { TradeService } from "./trade.service";
import { inventoryService } from "@/modules/inventory/inventory.service";
import { createErrorEmbed, createWarningEmbed } from "@lib/embeds";
import { createErrorEmbed, createWarningEmbed, createSuccessEmbed, createInfoEmbed } from "@lib/embeds";
const EMBED_COLOR = 0xFFD700; // Gold
@@ -61,18 +61,21 @@ export async function handleTradeInteraction(interaction: Interaction) {
}
async function handleCancel(interaction: ButtonInteraction | StringSelectMenuInteraction | ModalSubmitInteraction, threadId: string) {
const session = TradeService.getSession(threadId);
const user = interaction.user;
TradeService.endSession(threadId);
await interaction.reply({ content: "🛑 Trade cancelled. Deleting thread in 5 seconds..." });
setTimeout(async () => {
try {
await interaction.channel?.delete();
} catch (e) {
console.error("Failed to delete thread", e);
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);
}
}, 5000);
}
async function handleLock(interaction: ButtonInteraction | StringSelectMenuInteraction | ModalSubmitInteraction, threadId: string) {
await interaction.deferUpdate();
const isLocked = TradeService.toggleLock(threadId, interaction.user.id);
await updateTradeDashboard(interaction, threadId);
@@ -214,12 +217,29 @@ export async function updateTradeDashboard(interaction: Interaction, threadId: s
.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) {
const embed = createErrorEmbed(e.message, "Trade Failed");
console.error("Trade Execution Error:", e);
const errorEmbed = createErrorEmbed(e.message, "Trade Failed");
if (interaction.channel && (interaction.channel.isThread() || interaction.channel instanceof TextChannel)) {
await interaction.channel.send({ embeds: [embed] });
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;
}
@@ -291,3 +311,25 @@ function formatOffer(participant: any) {
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

@@ -144,6 +144,7 @@ export class TradeService {
-from.offer.money,
'TRADE_OUT',
`Trade with ${to.username} (Thread: ${threadId})`,
to.id,
tx
);
await economyService.modifyUserBalance(
@@ -151,6 +152,7 @@ export class TradeService {
from.offer.money,
'TRADE_IN',
`Trade with ${from.username} (Thread: ${threadId})`,
from.id,
tx
);
}

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);
});
}
}
};