Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .claude/settings.local.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
"Bash(npm run typecheck:*)",
"Bash(npm run lint:*)",
"Bash(npm run:*)",
"WebFetch(domain:zipline.diced.sh)"
"WebFetch(domain:zipline.diced.sh)",
"Bash(npm test)",
"Bash(npx tsc:*)"
],
"deny": [],
"ask": []
}
}
}
6 changes: 6 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,9 @@
/temp
/src/db/schema.js
/src/db/schema.d.ts

# Config files
vitest.config.ts
vitest.config.js
vitest.config.d.ts
vitest.config.js.map
14 changes: 13 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,5 +91,17 @@
}
],
"unicorn/prefer-node-protocol": "error"
}
},
"overrides": [
{
"files": ["tests/**/*.ts"],
"parserOptions": {
"project": "./tsconfig.test.json"
},
"rules": {
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/typedef": "off"
}
}
]
}
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,8 @@ jobs:
- name: Type check
run: npx tsc --noEmit

- name: Run tests
run: npm run test

- name: Build project
run: npm run build
171 changes: 136 additions & 35 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,74 +4,175 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co

## Project Overview

This is a TypeScript-based Markov chain text generation system with OpenAI integration. The project generates text using Markov chains trained on input data and can optionally use OpenAI's API for enhanced text generation and conversation handling.
This is a Discord.js bot written in TypeScript, built on the Discord Bot TypeScript Template. The bot features a fishing game with an economy system, AI-powered image generation, and OpenAI integration for enhanced interactions.

## Development Commands

### Build and Development
```bash
npm run build # Compile TypeScript to JavaScript
npm run dev # Run development server with hot reload
npm start # Start the production server
npm start # Start the bot (single instance)
npm run start:manager # Start with shard manager for multiple shards
npm run start:pm2 # Start with PM2 process manager
```

### Code Quality
```bash
npm run lint # Run ESLint for code linting
npm run lint:fix # Fix auto-fixable linting issues
npm run typecheck # Run TypeScript type checking
npm run format # Check code formatting with Prettier
npm run format:fix # Fix code formatting issues
```

### Testing
```bash
npm test # Run all tests
npm run test:unit # Run unit tests only
npm run test:integration # Run integration tests only
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage report
```

## Architecture Overview

### Core Components
### Database Management
```bash
npm run db:generate # Generate database migrations
npm run db:push # Push schema changes to database
npm run db:migrate # Run database migrations
npm run db:seed # Seed database with initial data
npm run db:setup # Push schema and seed data
npm run db:studio # Open Drizzle Studio for database management
```

- **MarkovChain** (`src/MarkovChain.ts`): The main class implementing Markov chain text generation
- Handles state transitions and probability calculations
- Supports configurable order (n-gram size) for chain complexity
- Provides text generation with customizable parameters
### Command Management
```bash
npm run commands:view [GUILD_ID] # View registered commands
npm run commands:register [GUILD_ID] # Register commands (guild-specific if ID provided)
npm run commands:clear [GUILD_ID] # Clear registered commands
npm run commands:rename # Rename a command
npm run commands:delete # Delete a specific command
```

- **OpenAI Integration** (`src/openai.ts`): Handles OpenAI API interactions
- Thread management for conversation context
- Response generation and processing
- Credit tracking and usage monitoring
## Architecture Overview

- **Type Definitions** (`src/types.ts`): Core TypeScript interfaces and types
- `MarkovState`: Represents chain states and transitions
- `GenerationOptions`: Configuration for text generation
- OpenAI-related types for API integration
### Core Components

- **Utilities** (`src/utils.ts`): Helper functions for data processing
- Text preprocessing and tokenization
- File I/O operations
- Data validation and sanitization
- **Bot Initialization** (`src/start-bot.ts`, `src/start-manager.ts`): Entry points for bot and shard manager
- Bot setup and configuration
- Command registration
- Event handler initialization
- Service initialization (OpenAI, Database)

- **Commands** (`src/commands/`): Discord slash commands
- **Chat Commands**: `/fish`, `/fishing`, `/shop`, `/buy`, `/inventory`, `/generate-image`, `/help`, `/info`, `/test`, `/dev`
- **Context Menu Commands**: View date sent (message), View date joined (user)
- Command metadata and argument definitions in `metadata.ts` and `args.ts`

- **Services** (`src/services/`): Business logic layer
- **FishingService**: Core fishing mechanics and catch logic
- **UserService**: User data management
- **GuildService**: Server settings and configuration
- **DatabaseService**: Database connection and query management (Drizzle ORM)
- **OpenAIService**: OpenAI API integration for AI features
- **ImageUpload**: Image upload to fal.ai for AI-generated images
- **ItemEffectsService**: Item effect calculations (rarity boosts, worth multipliers)
- **FishingCooldownService**: Rate limiting for fishing commands
- **ShopService**: Shop and purchase management

- **Database Schema** (`src/db/schema.ts`): PostgreSQL schema using Drizzle ORM
- **users**: Discord user profiles with money and auto-fishing status
- **catchables**: Fish and items that can be caught (rarity, worth, images)
- **catches**: Record of user catches
- **items**: Purchasable items with effects (consumable/passive)
- **shop**: Items available for purchase
- **purchases**: Purchase history
- **inventory**: User item inventory
- **guilds**: Server-specific settings (cooldown limits)

- **Events** (`src/events/`): Discord event handlers
- **CommandHandler**: Slash command execution
- **ButtonHandler**: Button interaction handling
- **MessageHandler**: Message event processing
- **ReactionHandler**: Reaction event processing
- **TriggerHandler**: Custom trigger system
- **GuildJoinHandler**: New server welcome messages
- **GuildLeaveHandler**: Server leave cleanup

- **Utilities** (`src/utils/`): Helper functions
- **ClientUtils**: Discord client helpers
- **CommandUtils**: Command processing utilities
- **MessageUtils**: Message formatting and sending
- **PermissionUtils**: Permission checking
- **DbUtils**: Database query helpers
- **FormatUtils**: Data formatting
- **StringUtils**: String manipulation
- **MathUtils**: Mathematical calculations
- **RandomUtils**: Random number generation

- **Models** (`src/models/`): Data models and type definitions
- **ConfigModels**: Configuration types
- **InternalModels**: Internal data structures
- **API Models**: REST API request/response types for cluster API

### Key Features

1. **Fishing Game**
- Catch various fish/items with different rarities
- Economy system with money and purchasable items
- Item effects (rarity boosts, worth multipliers)
- Auto-fishing capability
- Cooldown system to prevent spam

2. **AI Integration**
- OpenAI API for enhanced interactions
- Image generation via fal.ai
- Thread management for conversation context

3. **Scalability**
- Sharding support for large bot deployments (2500+ servers)
- Clustering support for multi-machine deployment
- PM2 process manager integration
- Cluster API for cross-shard communication

4. **Developer Features**
- TypeScript with strict type checking
- ESM modules for modern JavaScript
- Comprehensive testing with Vitest
- Database migrations with Drizzle Kit
- Localization support via `lang/` directory

### Data Flow

1. Input text is processed and tokenized in utilities
2. MarkovChain builds state transition tables from processed data
3. Text generation uses probability-based state transitions
4. OpenAI integration can enhance or supplement generated content
5. Results are processed and returned to the caller
1. User invokes slash command in Discord
2. CommandHandler receives interaction and routes to appropriate Command
3. Command validates permissions and arguments
4. Command calls relevant Service(s) for business logic
5. Service queries/updates database via DatabaseService
6. Service applies game logic (e.g., fishing mechanics, item effects)
7. Results formatted and sent back to Discord user via MessageUtils

### Key Design Patterns

- **Probabilistic State Machine**: Markov chains use statistical transitions between states
- **Strategy Pattern**: Different generation strategies (pure Markov vs OpenAI-enhanced)
- **Builder Pattern**: Configurable generation options and chain parameters
- **Handler Pattern**: Event handlers process Discord events and route to appropriate components
- **Service Layer**: Business logic separated from command/event handling
- **Repository Pattern**: DatabaseService abstracts database operations
- **Factory Pattern**: Command and event handler registration
- **Singleton Pattern**: Services like OpenAIService and DatabaseService

## Configuration

- TypeScript configuration in `tsconfig.json` with strict type checking
- ESLint configuration for code quality enforcement
- Build output to `dist/` directory
- **TypeScript**: `tsconfig.json` with strict type checking, ESM modules
- **ESLint**: `.eslintrc.json` for code quality
- **Prettier**: `.prettierrc.json` for code formatting
- **Vitest**: `vitest.config.ts` for testing configuration
- **Drizzle**: `src/drizzle.config.ts` for database configuration
- **Bot Config**: `config/config.json` (see `config/*.example.json` for templates)
- **Build Output**: `dist/` directory

## Environment Variables

The application expects OpenAI API configuration through environment variables or configuration files for AI-enhanced features.
Required environment variables (typically in `.env`):
- Discord bot token and client ID
- Database connection string (PostgreSQL)
- OpenAI API key (for AI features)
- fal.ai API key (for image generation)
- Bot developer Discord user ID(s)
Loading
Loading