# Jackbox Player Count Fetcher

Tools to retrieve the actual player count from a Jackbox game room in real-time.

## Available Implementations

### 1. Go + chromedp (Recommended) 🚀
The most reliable method - automates joining through jackbox.tv to capture WebSocket data.

### 2. Browser HTML Interface 🌐
Quick visual tool for manual testing - no installation required.

### 3. Node.js Script (Limited)
Attempts direct WebSocket connection - may not work due to authentication requirements.

## Features

- 🔍 Automatically joins jackbox.tv to capture WebSocket data
- 📊 Returns actual player count (not just max capacity)
- 👥 Lists all current players and their roles (host/player)
- 🎮 Shows game state, lobby state, and audience count
- 🎨 Pretty-printed output with colors

## Installation

### Go Version (Recommended)

```bash
cd scripts
go mod download
```

**Prerequisites:** Go 1.21+ and Chrome/Chromium browser installed

### Browser Version (No Installation Required!)

Just open `get-player-count.html` in any web browser - no installation needed!

### Node.js Version

```bash
cd scripts
npm install
```

**Note:** The Node.js version may not work reliably due to Jackbox WebSocket authentication requirements.

## Usage

### Go Version (Best) 🚀

```bash
# Navigate to scripts directory
cd scripts

# Run the script
go run get-player-count.go JYET

# Or build and run
go build -o get-player-count get-player-count.go
./get-player-count JYET
```

**How it works:**
1. Opens jackbox.tv in headless Chrome
2. Automatically enters room code and joins as "Observer"
3. Captures WebSocket messages from the browser
4. Extracts player count from `client/welcome` message
5. Enriches with data from REST API

### Browser Version 🌐

```bash
# Just open in browser
open get-player-count.html
```

1. Open `get-player-count.html` in your web browser
2. Enter a room code (e.g., "JYET")
3. Click "Get Player Count"
4. View results instantly

This version runs entirely in the browser and doesn't require any backend!

### Node.js Version (Limited)

```bash
node get-jackbox-player-count.js JYET
```

**Warning:** May fail due to WebSocket authentication requirements. Use the Go version for reliable results.

### JSON Output (for scripting)

```bash
JSON_OUTPUT=true node get-jackbox-player-count.js JYET
```

### As a Module

```javascript
const { getRoomInfo, getPlayerCount } = require('./get-jackbox-player-count');

async function example() {
  const roomCode = 'JYET';
  
  // Get room info
  const roomInfo = await getRoomInfo(roomCode);
  console.log('Game:', roomInfo.appTag);
  
  // Get player count
  const result = await getPlayerCount(roomCode, roomInfo);
  console.log('Players:', result.playerCount);
  console.log('Player list:', result.players);
}

example();
```

## Output Example

```
Jackbox Player Count Fetcher
Room Code: JYET

Fetching room information...
✓ Room found: triviadeath
  Max Players: 8

Connecting to WebSocket...
URL: wss://i-007fc4f534bce7898.play.jackboxgames.com/api/v2/rooms/JYET

✓ WebSocket connected

═══════════════════════════════════════════
  Jackbox Room Status
═══════════════════════════════════════════

Room Code:      JYET
Game:           triviadeath
Game State:     Lobby
Lobby State:    CanStart
Locked:         No
Full:           No

Players:        3 / 8
Audience:       0

Current Players:
  1. Host (host)
  2. E (player)
  3. F (player)

═══════════════════════════════════════════
```

## How It Works

1. **REST API Call**: First queries `https://ecast.jackboxgames.com/api/v2/rooms/{ROOM_CODE}` to get room metadata
2. **WebSocket Connection**: Establishes a WebSocket connection to the game server
3. **Join as Observer**: Sends a `client/connect` message to join as an audience member
4. **Parse Response**: Listens for the `client/welcome` message containing the full lobby state
5. **Extract Player Count**: Counts the players in the `here` object

## API Response Structure

The script returns an object with the following structure:

```javascript
{
  roomCode: "JYET",
  appTag: "triviadeath",
  playerCount: 3,              // Actual player count
  audienceCount: 0,            // Number of audience members
  maxPlayers: 8,               // Maximum capacity
  gameState: "Lobby",          // Current game state
  lobbyState: "CanStart",      // Whether game can start
  locked: false,               // Whether lobby is locked
  full: false,                 // Whether lobby is full
  players: [                   // List of all players
    { id: "1", role: "host", name: "Host" },
    { id: "2", role: "player", name: "E" },
    { id: "3", role: "player", name: "F" }
  ]
}
```

## Integration with Your App

You can integrate this into your Jackbox game picker application:

```javascript
// In your backend API
const { getRoomInfo, getPlayerCount } = require('./scripts/get-jackbox-player-count');

app.get('/api/room-status/:roomCode', async (req, res) => {
  try {
    const roomCode = req.params.roomCode.toUpperCase();
    const roomInfo = await getRoomInfo(roomCode);
    const playerData = await getPlayerCount(roomCode, roomInfo);
    res.json(playerData);
  } catch (error) {
    res.status(404).json({ error: 'Room not found' });
  }
});
```

## Troubleshooting

### "Room not found or invalid"
- Double-check the room code is correct
- Make sure the game is currently running (room codes expire after games end)

### "Connection timeout"
- The game server might be unavailable
- Check your internet connection
- The room might have closed

### WebSocket connection fails
- Ensure you have the `ws` package installed: `npm install`
- Some networks/firewalls might block WebSocket connections

## Dependencies

- `ws` (^8.14.0) - WebSocket client for Node.js

## License

MIT

