---
title: Tyche
---

Tyche (hereinafter the "Application") is a Discord bot designed to roll dice for tabletop gaming, role-playing games, and other scenarios requiring randomized results. The Application provides support for various dice types, modifiers, and advantage/disadvantage mechanics commonly used in tabletop gaming systems.

## 1. User Documentation

This section is for those interacting with a live instance of the Application.

### Adding Tyche to Your Discord Server

To add Tyche to your Discord server, use the following invite link:
https://discord.com/oauth2/authorize?client_id=1436837822656020663

The bot requires the following permissions:
- View Channels (to see where commands are used)
- Send Messages (to respond to commands)
- Use Application Commands (to register and respond to slash commands)

### Using the Roll Command

Tyche provides a single slash command: `/roll`

#### Command Parameters

1. **count** (required): How many dice to roll
   - Type: Integer
   - Range: 1-100
   - Example: `5` to roll 5 dice

2. **die** (required): What kind of dice to roll
   - Type: Choice
   - Options:
     - d2 (2-sided die)
     - d3 (3-sided die)
     - d4 (4-sided die)
     - d6 (6-sided die)
     - d8 (8-sided die)
     - d10 (10-sided die)
     - d12 (12-sided die)
     - d20 (20-sided die)
     - d100 (100-sided die/percentile)

3. **type** (required): What type of roll to perform
   - Type: Choice
   - Options:
     - Normal Roll: Standard dice roll
     - Advantage Roll: Roll twice and take the higher result
     - Disadvantage Roll: Roll twice and take the lower result

4. **modifier** (optional): Numeric modifier to apply to the roll
   - Type: Number
   - Can be positive or negative
   - Example: `5` adds +5 to the result, `-2` subtracts 2 from the result

#### Command Examples

1. **Simple Roll**: Roll a single d20
   ```
   /roll count:1 die:d20 type:Normal Roll
   ```

2. **Multiple Dice**: Roll 3d6 (common for character stats)
   ```
   /roll count:3 die:d6 type:Normal Roll
   ```

3. **Roll with Modifier**: Roll 1d20+5 (attack roll with +5 bonus)
   ```
   /roll count:1 die:d20 type:Normal Roll modifier:5
   ```

4. **Advantage Roll**: Roll 2d20 and take the higher result
   ```
   /roll count:1 die:d20 type:Advantage Roll
   ```

5. **Complex Roll**: Roll 2d6+3 with advantage
   ```
   /roll count:2 die:d6 type:Advantage Roll modifier:3
   ```

#### Understanding Results

The bot will respond with a breakdown of your roll:

**Normal Roll Example:**
```
Rolled 3d6+2:
4 + 3 + 5
Modifier: +2
Total: **14**
```

**Advantage/Disadvantage Roll Example:**
```
Rolled 1d20+5 with advantage:
15
18
Modifier: +5
Total: **23**
```

### Support and Feedback

If you encounter issues or have questions:
- Visit the support server: https://chat.nhcarrigan.com
- Email: contact@nhcarrigan.com
- View the source code: https://git.nhcarrigan.com/NHCarrigan/tyche

## 2. Technical Documentation

This section is for those interested in running their own instance of the Application.

### System Requirements

- Node.js 24.10.0 or higher
- pnpm 10.20.0 (package manager)
- A Discord bot token (obtained from Discord Developer Portal)
- Optional: 1Password CLI for environment variable management

### Architecture Overview

Tyche is built with the following technologies:

- **Discord.js 14.24.2**: Discord API interaction library
- **Fastify 5.6.1**: Web server for health monitoring
- **TypeScript 5.9.3**: Type-safe JavaScript development
- **@nhcarrigan/discord-analytics**: Bot analytics and monitoring
- **@nhcarrigan/logger**: Centralised logging system

#### Project Structure

```
src/
├── commands/
│   └── roll.ts          # Slash command definition for Discord API
├── modules/
│   └── roll.ts          # Core dice rolling logic
├── server/
│   └── serve.ts         # Fastify web server setup
├── utils/
│   └── logger.ts        # Logger configuration
└── index.ts             # Application entry point
```

#### Key Components

**Entry Point** (`src/index.ts:1`)
- Initializes Discord client with Guild intents
- Sets up analytics tracking
- Routes interactions to the roll handler
- Starts the web server

**Roll Command Handler** (`src/modules/roll.ts:14`)
- Parses command options (count, die, modifier, type)
- Uses Node.js `crypto.randomInt()` for secure random number generation
- Implements three roll types:
  - Normal: Single roll with optional modifier
  - Advantage: Two rolls, uses higher result
  - Disadvantage: Two rolls, uses lower result
- Formats and sends results back to Discord

**Web Server** (`src/server/serve.ts:54`)
- Runs on port 8123
- Serves a simple HTML landing page
- Provides health monitoring endpoint
- Includes links to source code, documentation, and support

**Logger** (`src/utils/logger.ts:9`)
- Configured with bot name "Tyche"
- Supports remote logging via LOG_TOKEN
- Used throughout the application for debugging and error tracking

### Installation

1. Clone the repository:
   ```bash
   git clone https://git.nhcarrigan.com/NHCarrigan/tyche.git
   cd tyche
   ```

2. Install dependencies:
   ```bash
   pnpm install
   ```

3. Set up environment variables:
   Create a `prod.env` file with the following variables:
   ```
   BOT_TOKEN=your_discord_bot_token
   LOG_TOKEN=your_logging_token (optional)
   ```

4. Build the TypeScript code:
   ```bash
   pnpm run build
   ```

5. Register the slash command with Discord:
   ```bash
   node prod/commands/roll.js
   ```
   This outputs the JSON needed to register the command via the Discord API.

### Running the Application

**Production Mode:**
```bash
pnpm start
```

This uses the 1Password CLI to load environment variables from `prod.env` and starts the bot.

**Development Mode:**
```bash
pnpm run build
node prod/index.js
```

### Configuration

#### Discord Bot Setup

1. Create a new application at https://discord.com/developers/applications
2. Navigate to the "Bot" section and create a bot
3. Enable the following intents:
   - Server Members Intent (if using analytics features)
4. Copy the bot token and add it to your `prod.env` file
5. Use the OAuth2 URL generator to create an invite link with:
   - Scopes: `bot`, `applications.commands`
   - Permissions: Send Messages, Use Application Commands

#### Environment Variables

- **BOT_TOKEN** (required): Discord bot token for authentication
- **LOG_TOKEN** (optional): Token for remote logging service

### Deployment Considerations

1. **Port Configuration**: The web server runs on port 8123 by default (hardcoded in `src/server/serve.ts:65`)

2. **Security**: The bot uses Node.js's cryptographically secure `randomInt()` function for dice rolls

3. **Rate Limiting**: Discord's built-in rate limiting applies to all interactions

4. **Monitoring**:
   - Web server provides a basic health check endpoint
   - Analytics are tracked via @nhcarrigan/discord-analytics
   - Logging can be centralised using the LOG_TOKEN

5. **Scaling**: As a stateless bot, multiple instances can run behind a load balancer if needed

### Development

**Linting:**
```bash
pnpm run lint
```

Uses ESLint with @nhcarrigan/eslint-config and enforces zero warnings.

**Testing:**
```bash
pnpm test
```

Note: Currently returns success without running tests (test suite not yet implemented).

### API Reference

#### Roll Module (`src/modules/roll.ts`)

```typescript
export const roll = async(interaction: ChatInputCommandInteraction): Promise<void>
```

**Parameters:**
- `interaction`: Discord.js ChatInputCommandInteraction object

**Behavior:**
1. Extracts command options (count, die, modifier, type)
2. Generates random numbers using `crypto.randomInt(1, sides + 1)`
3. For advantage/disadvantage: generates two sets of rolls
4. Calculates total based on roll type
5. Applies modifier to final result
6. Sends formatted response to Discord

**Roll Logic:**
- Normal: Sum all dice + modifier
- Advantage: Max(roll1_sum, roll2_sum) + modifier
- Disadvantage: Min(roll1_sum, roll2_sum) + modifier

## 3. Legal Documentation

This section is for expansions to our legal policies specific to the Application.

### License

Tyche is licensed under Naomi's Public Licence. The full licence text can be found at:
https://docs.nhcarrigan.com/#/license

Copyright is held by Naomi Carrigan.

### Terms of Service

The Application-specific terms of service extend the global terms found at:
https://docs.nhcarrigan.com/#/terms

#### Data Collection

Tyche collects the following data:
- Discord server IDs (for analytics)
- Command usage statistics (for analytics)
- User IDs (only when interacting with commands)

#### Data Usage

Data collected is used solely for:
- Bot analytics and monitoring
- Improving bot functionality
- Debugging and error tracking

#### Data Retention

- Command interaction data is processed in-memory and not permanently stored
- Analytics data follows the retention policy of @nhcarrigan/discord-analytics
- Logs may be retained for debugging purposes

### Privacy Policy

The Application-specific privacy policy extends the global policy found at:
https://docs.nhcarrigan.com/#/privacy

#### User Data

Tyche does not:
- Store message content
- Track individual user behaviour across servers
- Share data with third parties
- Use data for advertising or marketing

Tyche does:
- Process command inputs to generate dice roll results
- Collect aggregate usage statistics
- Log errors for debugging purposes

#### Your Rights

Users have the right to:
- Request information about data collection
- Request deletion of any stored data
- Opt-out by removing the bot from their server

For data requests, contact: contact@nhcarrigan.com

### Security Policy

Security issues should be reported following the guidelines at:
[SECURITY.md](./SECURITY.md)

Do not publicly disclose security vulnerabilities. Instead:
1. Email details to: contact@nhcarrigan.com
2. Include steps to reproduce the vulnerability
3. Allow reasonable time for a fix before public disclosure

## 4. Contributing Documentation

This section is for documentation related to contributing to the Application's codebase.

### Contributing Guidelines

Full contributing guidelines can be found at:
https://docs.nhcarrigan.com/#/contributing

### Code of Conduct

All contributors must adhere to the Code of Conduct found in:
[CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md)

Key principles:
- Be respectful and inclusive
- Welcome newcomers
- Focus on constructive feedback
- No harassment or discriminatory behaviour

### Development Setup

1. Fork the repository
2. Clone your fork locally
3. Install dependencies: `pnpm install`
4. Create a feature branch: `git checkout -b feature/your-feature-name`
5. Make your changes
6. Ensure code passes linting: `pnpm run lint`
7. Build the project: `pnpm run build`
8. Test your changes with a Discord bot token

### Code Style

The project uses:
- **ESLint**: @nhcarrigan/eslint-config (enforces zero warnings)
- **TypeScript**: @nhcarrigan/typescript-config
- **Formatting**: Follow existing code patterns

Key conventions:
- Use TypeScript for all source files
- Include JSDoc comments for exported functions
- Copyright headers required on all source files:
  ```typescript
  /**
   * @copyright NHCarrigan
   * @license Naomi's Public Licence
   * @author Naomi Carrigan
   */
  ```

### Project Structure Conventions

- **commands/**: Discord slash command definitions (for API registration)
- **modules/**: Business logic implementations
- **server/**: Web server and HTTP endpoints
- **utils/**: Shared utilities and helpers

### Adding New Features

When adding new features:

1. **New Dice Commands**: Add to `src/commands/roll.ts` and update the logic in `src/modules/roll.ts`

2. **New Commands**:
   - Create command definition in `src/commands/`
   - Create handler in `src/modules/`
   - Register handler in `src/index.ts`

3. **Server Endpoints**: Add routes in `src/server/serve.ts`

4. **Tests**: While not currently implemented, tests should be added to validate new functionality

### Pull Request Process

1. Ensure your code builds without errors
2. Ensure linting passes with zero warnings
3. Update documentation if adding new features
4. Create a pull request with a clear description of changes
5. Link any related issues
6. Wait for review from maintainers

### Testing Your Changes

To test changes:

1. Create a test Discord server
2. Create a test bot application in Discord Developer Portal
3. Use your test bot token in `prod.env`
4. Build and run the bot: `pnpm run build && node prod/index.js`
5. Test commands in your test server
6. Verify the web server loads at http://localhost:8123

### Reporting Issues

When reporting bugs:
- Post in the #bug-reports forum channel on our Discord community
- Include steps to reproduce
- Include expected vs actual behaviour
- Include relevant error messages or logs
- Specify your environment (Node version, OS, etc.)

### Feature Requests

Feature requests are welcome! Include:
- Clear description of the feature
- Use case explanation
- Why it would benefit users
- Any implementation suggestions

### Getting Help

For questions or support:
- Join the support server: https://chat.nhcarrigan.com
- Email: contact@nhcarrigan.com
- Review documentation: https://docs.nhcarrigan.com

### Resources

- Discord.js Documentation: https://discord.js.org/docs
- Discord Developer Portal: https://discord.com/developers/docs
- TypeScript Documentation: https://www.typescriptlang.org/docs
- Fastify Documentation: https://fastify.dev/docs

---

**Documentation Version**: 1.0.0
**Application Version**: 0.0.0
