Skip to content
Open
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
10 changes: 10 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
target/
.env
.git/
.github/
.vscode/
.idea/
*.log
.DS_Store
Thumbs.db
.replit_envtarget
2 changes: 0 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# Telegram Dice Bot configuration
BOT_TOKEN=your_bot_token_here
PORT=5000
# MODE can be: polling or webhook (webhook not yet enabled)
MODE=polling
92 changes: 90 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,29 @@ This file contains guidelines for agentic coding assistants working on the Teleg

### Build & Run
```bash
cargo build # Build the project
cargo run # Run the bot (requires BOT_TOKEN env var)
cargo build # Build project
cargo run # Run bot (requires BOT_TOKEN env var)
RUST_LOG=debug cargo run # Run with debug logging
```

### Docker Deployment
```bash
make build # Build Docker image
make run # Build and start container
make up # Start container
make down # Stop container
make logs # View logs (follow mode)
make status # Check container status
make restart # Restart container
make prune # Clean unused Docker resources
make clean # Remove containers and images
```

### Environment Variables for Docker
- `BOT_TOKEN`: Telegram bot token (required for bot to work)
- `PORT`: Health check port (default: 5000)
- `RUST_LOG`: Log level (info, debug, warn, error)

### Code Quality
```bash
cargo fmt --all # Format all code
Expand Down Expand Up @@ -260,10 +278,21 @@ src/
└── state.rs # State enums, types
```

Docker/
├── Dockerfile # Multi-stage build with Rust 1.82
├── docker-compose.yml # Service configuration
├── Makefile # Docker management commands
└── .dockerignore # Build context optimization
```

- `main.rs`: Bootstrapping, tokio runtime, HTTP server
- `bot.rs`: All Telegram interaction (500+ lines, split if larger)
- `game.rs`: Pure game logic with comprehensive tests
- `state.rs`: Type definitions, enums, structs
- `Dockerfile`: Multi-stage build (Rust 1.82, debian:bookworm-slim runtime)
- `docker-compose.yml`: Service configuration with health checks and restart policy
- `Makefile`: Convenient commands for Docker operations
- `.dockerignore`: Excludes unnecessary files from build context

## Internationalization

Expand Down Expand Up @@ -301,6 +330,7 @@ Before pushing, run:
cargo fmt --all
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-features --workspace
make build # Ensure Docker build passes (recommended)
```

## Git Commit Guidelines
Expand Down Expand Up @@ -328,6 +358,7 @@ Always run these commands before making changes:
cargo test --all-features --workspace # Ensure baseline tests pass
cargo clippy --all-targets --all-features -- -D warnings
cargo fmt -- --check
make build # Ensure Docker build passes (optional but recommended)
```

After making changes:
Expand Down Expand Up @@ -383,6 +414,27 @@ Monitor what messages the bot receives:
- Verify dice animation timing
- Check keyboard buttons work correctly

### Docker Debugging
```bash
# Check container logs
make logs

# Check container status
make status

# Run container directly with debug logging
docker run --rm -e RUST_LOG=debug dice-bot

# Check Docker logs for errors
docker logs telegram-dice-bot --tail 50

# Enter container shell (for debugging)
docker exec -it telegram-dice-bot /bin/sh

# Test health check endpoint
curl http://localhost:5000/health
```

## Performance Considerations

- Avoid blocking operations in async handlers
Expand All @@ -406,3 +458,39 @@ Monitor what messages the bot receives:
- **Language**: Rust 2021 edition
- **Framework**: teloxide 0.12
- **Maintainer**: Alxy Dev

## Docker Deployment Best Practices

### Image Optimization
- Use multi-stage builds to minimize runtime image size (~75MB)
- Always include `Cargo.lock` for reproducible builds
- Use `--locked` flag with `cargo install` to prevent dependency updates
- Clean up build artifacts after compilation

### Container Security
- Run as non-root user (`appuser` with UID 10001)
- Never commit `.env` files with real tokens
- Use environment variables for sensitive data (BOT_TOKEN)
- Set restart policy to `unless-stopped` for production

### Health Checks
- Health endpoint: `GET /health` on port 5000
- Returns HTML with status: `<h1>Telegram Dice Bot is running</h1>`
- Use for monitoring and autoscale deployment

### Logging in Docker
- Use `RUST_LOG` environment variable to control log level
- Logs are sent to stdout/stderr (Docker can capture them)
- View logs with: `make logs` or `docker logs telegram-dice-bot`
- Recommended levels: `info` (production), `debug` (troubleshooting)

### Resource Cleanup
- Run `make prune` to clean unused Docker resources
- Use `make clean` to remove containers and images
- Periodically run `docker system prune -a -f --volumes` for aggressive cleanup

### Troubleshooting
1. **Container exits immediately**: Check BOT_TOKEN is valid
2. **No logs visible**: Set `RUST_LOG=debug` or `RUST_LOG_FORMAT=always`
3. **Port already in use**: Change `PORT` in docker-compose.yml
4. **Image too large**: Rebuild with `--no-cache` flag
10 changes: 5 additions & 5 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
# syntax=docker/dockerfile:1

ARG RUST_VERSION=1.79
ARG RUST_VERSION=1.82
ARG APP_NAME=telegram-dice-bot

FROM rust:${RUST_VERSION}-slim AS builder
ARG APP_NAME
WORKDIR /app

# Cache dependencies
Expand All @@ -12,19 +13,18 @@ RUN mkdir -p src && echo "fn main(){}" > src/main.rs && \
cargo build --release && \
rm -rf src

# Build application
# Build application and install directly (use --locked to prevent dependency updates)
COPY . .
RUN cargo build --release --bin ${APP_NAME}
RUN cargo install --path . --root /usr/local --locked

FROM debian:bookworm-slim AS runtime
ENV RUST_LOG=info
ENV PORT=5000

# Create non-root user
RUN useradd -u 10001 -m appuser

WORKDIR /app
COPY --from=builder /app/target/release/${APP_NAME} /usr/local/bin/${APP_NAME}
COPY --from=builder /usr/local/bin/${APP_NAME} /usr/local/bin/${APP_NAME}

EXPOSE 5000
USER appuser
Expand Down
28 changes: 28 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
.PHONY: build up down restart logs clean status prune

build:
docker-compose build

up:
docker-compose up -d

run: build up

down:
docker-compose down

restart:
docker-compose restart

logs:
docker-compose logs -f

clean:
docker-compose down -v
docker rmi telegram-dice-bot 2>/dev/null || true

status:
docker-compose ps

prune:
docker system prune -f
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,69 @@ PORT=5000
cargo run
```

## Запуск через Docker

### Сборка и запуск

1. Создайте файл `.env` с токеном бота:
```bash
cp .env.example .env
# Отредактируйте .env и укажите ваш токен:
BOT_TOKEN=ваш_токен_бота
PORT=5000
```

2. Запустите через Makefile:
```bash
make run
```

Или используя docker-compose напрямую:
```bash
docker-compose up -d
```

### Управление контейнером

```bash
make logs # Просмотр логов
make down # Остановка контейнера
make restart # Перезапуск контейнера
make status # Статус контейнера
make clean # Очистка контейнеров и образов
```

### Очистка пространства

Для освобождения дискового пространства от неиспользуемых Docker ресурсов:

```bash
make prune # Очистить неиспользуемые ресурсы (контейнеры, сети, images)
make clean # Удалить контейнеры и образы проекта
```

Агрессивная очистка (удаляет ALL unused resources):
```bash
docker system prune -a -f --volumes
```

### Настройка логирования

Уровень логирования задается через переменную окружения:
```bash
# В .env файле
RUST_LOG=info # Базовый уровень (по умолчанию)
RUST_LOG=debug # Детальное логирование
RUST_LOG=warn # Только предупреждения и ошибки
```

### Проверка работоспособности

```bash
# Health check
curl http://localhost:5000/health
```

## Использование

1. Найдите вашего бота в Telegram
Expand Down
15 changes: 15 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
version: '3.8'

services:
bot:
build:
context: .
dockerfile: Dockerfile
container_name: telegram-dice-bot
ports:
- "${PORT:-5000}:5000"
environment:
- BOT_TOKEN=${BOT_TOKEN}
- PORT=${PORT:-5000}
- RUST_LOG=${RUST_LOG}
restart: unless-stopped
Loading