# Coup Plus Telegram Bot

A complete Telegram Bot implementation of Coup Plus card game with Persian UI support.

## Features

- ✅ Complete Coup Plus game (Classic + Reforms/Factions + Ambassador/Inquisitor + Anarchist/Bomb)
- ✅ 1-8 players (humans + AI bots)
- ✅ Three AI difficulty levels (easy/medium/hard)
- ✅ Full Persian interface
- ✅ Optimistic locking for race condition prevention
- ✅ Turn timer system with auto-actions
- ✅ Lobby chat with 10-second rate limiting
- ✅ FSM-based game engine
- ✅ Shared hosting compatible (webhook + cron)

## Requirements

- PHP 8.2+
- MySQL 8.0+
- Composer
- Telegram Bot Token

## Installation

### 1. Clone the Repository

```bash
git clone <repository-url>
cd coup-telegram-bot
```

### 2. Install Dependencies

```bash
composer install
```

### 3. Configure Environment

Copy `.env.example` to `.env`:

```bash
cp .env.example .env
```

Edit `.env` with your settings:

```env
TELEGRAM_BOT_TOKEN=8705403228:AAHlHH-Omw3Y-3L0hIvW995IB5KQT9FvSI4
TELEGRAM_WEBHOOK_URL=https://your-domain.com/public/webhook.php
DB_HOST=localhost
DB_NAME=coup_game
DB_USER=coup_user
DB_PASS=secure_password
DB_CHARSET=utf8mb4
DEFAULT_TURN_TIME=60
DEFAULT_CHALLENGE_TIME=30
MAX_PLAYERS=8
```

### 4. Setup Database

```bash
php bot.php setup
```

### 5. Set Webhook

```bash
php bot.php webhook
```

### 6. Setup Cron Job

Add this cron job to your server (every 30 seconds):

```bash
*/30 * * * * /usr/bin/php /path/to/coup-telegram-bot/cron_processor.php > /dev/null 2>&1
```

For cPanel:
1. Go to cPanel > Cron Jobs
2. Add the above command

## Project Structure

```
coup-telegram-bot/
├── composer.json          # Dependencies and autoloading
├── .env                  # Environment variables
├── bot.php               # CLI management tool
├── cron_processor.php    # Cron job for timeout processing
├── config/
│   └── database.php      # Database connection
├── database/
│   └── migrations/       # SQL migration files
├── public/
│   └── webhook.php       # Telegram webhook endpoint
├── src/
│   ├── Domain/           # Domain models (Game, Player, Card, etc.)
│   ├── Engine/           # Game engine (FSM, ActionHandler, etc.)
│   ├── Controller/       # Request handlers (Webhook, Game, Lobby)
│   ├── Repository/       # Database access layer
│   ├── Service/          # Telegram and messaging services
│   ├── AI/               # Bot AI decision making
│   └── Utils/            # Utilities (DatabaseSetup, TimeoutProcessor)
└── logs/                 # Log files
```

## Usage

### Telegram Commands

- `/start` - Start the bot and see welcome message
- `/create` - Create a new game room
- `/join CODE` - Join a game with room code
- `/lobby` - Show current lobby status
- `/help` - Show help message
- `/rules` - Show game rules

### CLI Commands

```bash
# Setup database tables
php bot.php setup

# Set webhook
php bot.php webhook

# Delete webhook
php bot.php delete-webhook

# Get webhook info
php bot.php info

# Test connection
php bot.php test

# Process expired turns manually
php bot.php process-timeout
```

### Creating a Game

1. Send `/create` to the bot in private chat
2. Answer setup questions:
   - Number of players (2-8)
   - Human players count
   - Bot players count
   - Ambassador/Inquisitor mode
   - Anarchist mode (bomb)
   - Bot difficulty (easy/medium/hard)
   - Turn time limit
   - Challenge time limit
3. Get your room code (e.g., COUP-ABC123)
4. Share the code with friends
5. Wait for all players to join
6. Game starts automatically!

### Playing the Game

1. When it's your turn, select an action from the keyboard
2. If targeting another player, select your target
3. Other players can challenge or block
4. If challenged and you have the card, show it
5. If you don't have the card, lose one card
6. Last player with cards wins!

## Game Rules

### Actions

- **درآمد (Income)**: Take 1 coin
- **کمک خارجی (Foreign Aid)**: Take 2 coins (blockable by Duke)
- **کودتا (Coup)**: Pay 7 coins, force a player to lose a card
- **ترور (Assassinate)**: Pay 3 coins, force a player to lose a card (blockable by Contessa)
- **دزدی (Steal)**: Take 2 coins from another player (blockable by Captain/Ambassador)
- **مالیات (Tax)**: Take 3 coins (requires Duke)
- **تعویض کارت (Exchange)**: Exchange 2 cards (requires Ambassador)
- **خرید بمب (Buy Bomb)**: Pay 5 coins, give bomb to another player (Anarchist mode)

### Cards

- **دوک (Duke)**: Tax, block Foreign Aid
- **آدم‌کش (Assassin)**: Assassinate
- **فرمانده (Captain)**: Steal, block Steal
- **سفیر (Ambassador)**: Exchange, block Steal
- **کنتسا (Contessa)**: Block Assassinate, block Bomb
- **بازرس (Inquisitor)**: Look at 1 card + exchange 1, block Steal/Assassinate

### Winning

The last player with at least one unrevealed card wins!

## Database Schema

### Tables

- `users` - Telegram users registry
- `games` - Game sessions with settings
- `game_players` - Player information
- `player_influences` - Player cards
- `deck_cards` - Current deck state
- `faction_cards` - Faction cards for Reforms expansion
- `game_actions_log` - Complete action history
- `pending_interactions` - Awaiting player responses

All tables use optimistic locking (`version` column) to prevent race conditions.

## AI Bot System

Bots make decisions based on difficulty level:

### Easy
- Random action selection
- High bluff rate (50%)
- Poor challenge decisions

### Medium
- Smart coin management
- Moderate bluff rate (20%)
- Basic challenge logic

### Hard
- Optimal strategy
- Low bluff rate (10%)
- Perfect card tracking
- Adaptive blocking

## Shared Hosting Deployment

This project is designed for shared hosting environments:

1. **No background processes**: All timer checks run via cron
2. **Webhook-only**: No long-polling required
3. **File permissions**: Ensure webhook.php is executable (755)
4. **Cron job**: Run cron_processor.php every 30 seconds
5. **PHP extensions**: Required extensions: PDO, JSON, CURL, mbstring

## Troubleshooting

### Bot doesn't respond

1. Check webhook is set: `php bot.php info`
2. Check logs: `tail -f logs/cron.log`
3. Verify database connection
4. Check PHP error logs

### Players can't join

1. Check if game is full
2. Verify room code is correct
3. Ensure game hasn't started yet

### Timeouts not working

1. Verify cron job is running
2. Check database timezone settings
3. Review pending_interactions table

## Development

### Running Tests

```bash
# Currently no automated tests
# Manual testing via Telegram
```

### Adding New Features

1. Update domain models in `src/Domain/`
2. Add game logic in `src/Engine/`
3. Update handlers in `src/Controller/`
4. Add Persian messages in `src/Service/MessageService.php`

## License

This project is for educational and personal use.

## Credits

- Coup card game by Rikki Tahta
- Telegram Bot API
- PHP Community

## Support

For issues and questions, please check the logs and documentation first.

---

**Note**: This bot is for entertainment purposes only. Have fun playing Coup! 🎮
