# Echoes of the Ashes - Telegram RPG Bot

A post-apocalyptic survival RPG Telegram bot built with Python, featuring turn-based exploration, resource management, and a persistent world.

![Python](https://img.shields.io/badge/python-3.11-blue)
![Telegram Bot API](https://img.shields.io/badge/telegram--bot--api-21.0.1-blue)
![PostgreSQL](https://img.shields.io/badge/postgresql-15-blue)
![Docker](https://img.shields.io/badge/docker-compose-blue)

## 🎮 Features

### Core Gameplay
- **🗺️ Exploration**: Navigate through 7 interconnected locations
- **👀 Interact**: Search and interact with 24+ unique objects
- **🎒 Inventory**: Collect, use, and manage 28 different items
- **⚡️ Stamina System**: Actions require stamina management with automatic regeneration
- **❤️ Survival**: Heal using consumables, avoid damage
- **🔄 Cooldowns**: Per-action cooldown system prevents spam
- **♻️ Auto-Recovery**: Stamina regenerates over time (1+ per 5 minutes based on endurance)

### Visual Experience
- **📸 Location Images**: Every location has a unique image
- **🖼️ Smart Caching**: Images cached in database for instant loading
- **✨ Smooth Transitions**: Uses `edit_message_media` for seamless navigation
- **🧭 Context-Aware**: Location images persist across menus

### Game World
- **7 Locations**: Downtown, Gas Station, Residential, Clinic, Plaza, Park, Overpass
- **5 Interactable Types**: Rubble, Sedans, Houses, Medical Cabinets, Tool Sheds, Dumpsters, Vending Machines
- **28 Items**: Resources, consumables, weapons, equipment, quest items
- **Risk vs Reward**: Higher risk actions can cause damage but yield better loot

## 🚀 Quick Start

### Prerequisites
- Docker and Docker Compose
- Telegram Bot Token (from [@BotFather](https://t.me/botfather))

### Installation

1. Clone the repository:
```bash
cd /opt/dockers/telegram-rpg
```

2. Create `.env` file:
```env
TELEGRAM_BOT_TOKEN=your_bot_token_here
DATABASE_URL=postgresql+psycopg://user:password@echoes_of_the_ashes_db:5432/telegram_rpg
POSTGRES_USER=user
POSTGRES_PASSWORD=password
POSTGRES_DB=telegram_rpg
```

3. Start the bot:
```bash
docker compose up -d --build
```

4. Check logs:
```bash
docker logs echoes_of_the_ashes_bot -f
```

## 🎯 How to Play

### Basic Commands
- `/start` - Start your journey or return to main menu

### Main Menu
- **🗺️ Move** - Travel to connected locations
- **👀 Inspect Area** - View and interact with objects
- **👤 Profile** - View your character stats
- **🎒 Inventory** - Manage your items

### Actions
- **Search/Loot** - Find items in the environment (costs stamina)
- **Use Items** - Consume food/medicine to restore HP/stamina
- **Drop Items** - Leave items at current location
- **Pick Up** - Collect items from the ground

### Stats
- **HP**: Health Points (die at 0)
- **Stamina**: Required for actions (regenerates over time)
- **Weight/Volume**: Inventory capacity limits

## 🗺️ World Map

```
        🛣️ Highway Overpass
             |
    🏥 Clinic --- ⛽️ Gas Station
         |            |
    🏘️ Residential --- 🌆 Downtown --- 🏬 Plaza
         |                                |
         +------------ 🌳 Park ------------+
```

## 📦 Items

### Consumables
| Item | Effect | Emoji |
|------|--------|-------|
| First Aid Kit | +50 HP | 🩹 |
| Mystery Pills | +30 HP | 💊 |
| Canned Beans | +20 HP, +5 Stamina | 🥫 |
| Energy Bar | +15 Stamina | 🍫 |
| Bottled Water | +10 Stamina | 💧 |

### Resources
- ⚙️ Scrap Metal
- 🪵 Wood Planks
- 📌 Rusty Nails
- 🧵 Cloth Scraps
- 🍶 Plastic Bottles

### Equipment
- 🎒 Hiking Backpack (+20 capacity)
- 🔦 Flashlight
- 🔧 Tire Iron
- ⚾ Baseball Bat

## 🏗️ Architecture

### Tech Stack
- **Language**: Python 3.11
- **Bot Framework**: python-telegram-bot 21.0.1
- **Database**: PostgreSQL 15 (async with SQLAlchemy)
- **Deployment**: Docker Compose
- **Scheduler**: APScheduler (for stamina regeneration)

### Project Structure
```
telegram-rpg/
├── bot/
│   ├── database.py      # Database operations
│   ├── handlers.py      # Telegram event handlers
│   ├── keyboards.py     # Inline keyboard layouts
│   └── logic.py         # Game logic
├── data/
│   ├── items.py         # Item definitions
│   ├── models.py        # Game world models
│   └── world_loader.py  # World construction
├── docs/                # Comprehensive documentation
├── images/              # Location and interactable images
├── main.py             # Entry point
└── docker-compose.yml  # Container orchestration
```

### Database Schema
- **players**: Character stats and state
- **inventory**: Player item storage
- **dropped_items**: World item storage
- **cooldowns**: Per-action cooldown tracking
- **image_cache**: Telegram file_id caching

## 📚 Documentation

Detailed documentation in `docs/`:
- **INVENTORY_USE.md** - Item usage system
- **EXPANDED_WORLD.md** - All locations and items
- **WORLD_MAP.md** - Map visualization and strategy
- **IMAGE_SYSTEM.md** - Image caching implementation
- **UX_IMPROVEMENTS.md** - Clean chat mechanics
- **ACTION_FEEDBACK.md** - Action result display
- **SMOOTH_TRANSITIONS.md** - Message editing system
- **UPDATE_SUMMARY.md** - Latest changes

## 🎨 Adding Content

### New Item
Edit `data/items.py`:
```python
"new_item": {
    "name": "New Item",
    "weight": 1.0,
    "volume": 0.5,
    "type": "consumable",
    "effects": {"hp": 20},
    "emoji": "🎁"
}
```

### New Interactable
Edit `data/world_loader.py`:
```python
NEW_TEMPLATE = Interactable(
    id="new_object",
    name="New Object",
    image_path="images/interactables/new.png"
)
action = Action(id="search", label="🔎 Search", stamina_cost=2)
action.add_outcome("success", Outcome(
    text="You find something!",
    items_reward={"new_item": 1}
))
NEW_TEMPLATE.add_action(action)
```

### New Location
```python
new_location = Location(
    id="new_place",
    name="🏛️ New Place",
    description="Description here",
    image_path="images/locations/new_place.png"
)
new_location.add_interactable("new_place_object", NEW_TEMPLATE)
new_location.add_exit("north", "other_location")
world.add_location(new_location)
```

## 🔧 Development

### Local Development
```bash
# Install dependencies
pip install -r requirements.txt

# Run bot
python main.py
```

### Database Management
```bash
# Access database
docker exec -it echoes_of_the_ashes_db psql -U user -d telegram_rpg

# Backup database
docker exec echoes_of_the_ashes_db pg_dump -U user telegram_rpg > backup.sql

# Restore database
docker exec -i echoes_of_the_ashes_db psql -U user telegram_rpg < backup.sql
```

### Logs
```bash
# Follow bot logs
docker logs echoes_of_the_ashes_bot -f

# Database logs
docker logs echoes_of_the_ashes_db -f
```

## 🎲 Game Mechanics

### Outcome Probability
- **Critical Failure**: Rare, negative effects
- **Failure**: Common, no reward
- **Success**: Common, standard rewards

Configured in `bot/logic.py`:
```python
def roll_outcome(action: Action):
    roll = random.random()
    if roll < 0.1: return "critical_failure"
    elif roll < 0.5: return "failure"
    else: return "success"
```

### Stamina Regeneration
- **Rate**: 1 stamina per 5 minutes
- **Maximum**: Defined by player stats
- **Automatic**: Background scheduler

### Cooldowns
- **Per-Action**: Each action has independent cooldown
- **Duration**: Configured per action (30-60 minutes typical)
- **Storage**: Composite key `instance_id:action_id`

## 🚧 Future Plans

### Planned Features
- [ ] Combat system
- [ ] Crafting mechanics
- [ ] Quest system
- [ ] NPC interactions
- [ ] Base building
- [ ] Equipment slots
- [ ] Status effects
- [ ] Day/night cycle
- [ ] Weather system
- [ ] Trading economy

### Balance Improvements
- [ ] Dynamic difficulty
- [ ] Rare item spawns
- [ ] Location-based dangers
- [ ] Resource scarcity tuning

## 🤝 Contributing

Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Test thoroughly
5. Submit a pull request

## 📝 License

This project is open source and available under the MIT License.

## 🙏 Acknowledgments

- Built with [python-telegram-bot](https://python-telegram-bot.org/)
- Inspired by classic post-apocalyptic RPGs
- Community feedback and testing

## 📞 Support

For issues or questions:
- Open a GitHub issue
- Check the documentation in `docs/`
- Review error logs with `docker logs`

---

**Current Version**: 1.1.0 (Expanded World Update)
**Last Updated**: October 16, 2025
**Status**: ✅ Active Development
