# FinanceGPT — Telegram AI Rewriter with Admin Panel

A production-ready service that monitors Telegram source channels, rewrites messages with an AI model, and forwards the result to Telegram and Bale destination channels — all managed through a full-featured web admin panel.

---

## Features

- **Telegram listener** — real-time event handler + periodic polling fallback
- **AI rewriting** — configurable prompt, model, and endpoint (OpenAI-compatible API)
- **Bale forwarding** — sends text and media to a Bale bot channel
- **Image/media forwarding** — downloads and re-sends media with the AI caption
- **Admin panel** (Flask, port 5000) — dashboard, settings, channel management, logs, reports, prompts, users
- **SQLite database** — zero external dependencies, backup by file copy
- **Structured logging** — rotating file + DB storage, searchable from the panel

---

## Quick Start

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

# 2. Run (creates DB, seeds defaults, starts admin panel + Telegram service)
python run.py
```

Admin panel: **http://localhost:5000**  
Default credentials: `admin` / `admin123` ← **change immediately**

---

## Project Structure

```
run.py                  ← entry point
init_app.py             ← first-run database seeder
requirements.txt
setup_guide.html        ← offline Persian installation guide
README.md

app/
  core/
    database.py         ← SQLAlchemy engine + session factory
    logger.py           ← rotating file + DB log handler
    config.py           ← dynamic settings from DB
    security.py         ← password hashing
    state.py            ← shared in-process service state
  models/
    user.py             ← admin users
    settings.py         ← key/value settings store
    channel.py          ← source & destination channels
    log_entry.py        ← structured log records
    message_record.py   ← per-message processing audit trail
    prompt_history.py   ← versioned AI prompts
  services/
    ai_service.py       ← OpenAI-compatible rewriting
    bale_service.py     ← Bale HTTP API
    message_processor.py← orchestrates receive → AI → send
    telegram_service.py ← Telethon client, event handler, poller
  admin/
    app.py              ← Flask app factory
    routes/             ← dashboard, settings, channels, logs,
    │                      reports, prompts, users, service_status
    templates/          ← Bootstrap 5 RTL HTML templates

data/
  app.db                ← SQLite database (auto-created)
  secret.key            ← Flask session secret (auto-generated)
logs/
  app.log               ← rotating log file (auto-created)
downloaded_media/       ← temporary media cache (auto-created)
```

---

## Admin Panel Pages

| URL | Description |
|-----|-------------|
| `/` | Dashboard — statistics & charts |
| `/settings` | Telegram, Bale, AI, and system settings |
| `/channels` | Source and destination channel management |
| `/prompts` | AI prompt editor with version history |
| `/logs` | Searchable, filterable log viewer |
| `/reports` | Time-range reports with charts |
| `/service-status` | Live connection status for all services |
| `/users` | Admin user management |

---

## Configuration

All configuration is stored in the SQLite database and editable from the admin panel — no file editing required after the initial run.

### Key Settings

| Key | Description |
|-----|-------------|
| `telegram.api_id` | Telegram API ID |
| `telegram.api_hash` | Telegram API Hash |
| `telegram.session_string` | Telethon session string |
| `telegram.use_proxy` | `true` / `false` |
| `telegram.proxy_host` | SOCKS5 proxy host |
| `telegram.proxy_port` | SOCKS5 proxy port |
| `bale.bot_token` | Bale bot token |
| `bale.chat_id` | Bale destination chat ID |
| `ai.api_key` | AI service API key |
| `ai.base_url` | AI service endpoint |
| `ai.model` | Model name (e.g. `qwen3-32b`) |
| `system.poll_interval` | Polling interval in seconds |
| `system.admin_port` | Admin panel port (default 5000) |

---

## Database Backup

```bash
cp data/app.db data/app.db.backup
```

The entire state of the application (settings, channels, logs, reports, prompts, users) is contained in `data/app.db`.

---

## Running as a systemd Service (Linux VPS)

```ini
[Unit]
Description=FinanceGPT Telegram Bot
After=network.target

[Service]
Type=simple
WorkingDirectory=/opt/financegpt
ExecStart=/opt/financegpt/venv/bin/python run.py
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
```

```bash
sudo systemctl enable financegpt
sudo systemctl start financegpt
sudo journalctl -u financegpt -f
```

---

## Security Notes

- Passwords are hashed with **bcrypt** (via Werkzeug)
- Flask session secret is auto-generated and stored in `data/secret.key`
- Sensitive values (API keys, tokens) are masked in the settings UI
- SQL injection is prevented by SQLAlchemy's parameterised queries
- Change the default admin password immediately after first login
