Architecture cleanup after migration to ultrathin monolith: - Remove INTERNAL_API_PORT from .env files (was port 8002) - Clean up bot_main.py: remove uvicorn, Thread, run_internal_api() - Update validate.md to check /api/telegram/health instead of port 8002 - Add deprecation notices to old Windows deployment docs - Update docs/telegram/README.md with architecture note The Telegram internal API is now served at /api/telegram/internal/* on the main backend port (8000/8001) instead of separate port 8002. Also includes: menu updates, ServerLogsView improvements, script fixes 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
856 lines
24 KiB
Markdown
856 lines
24 KiB
Markdown
# ROA2WEB Telegram Bot - Windows Server Deployment Guide
|
|
|
|
> ⚠️ **DEPRECATED ARCHITECTURE**
|
|
>
|
|
> This documentation refers to the OLD microservices architecture where the Telegram bot
|
|
> ran as a separate service on port 8002. The current architecture is an **ultrathin monolith**
|
|
> where everything runs on a single port (8000/8001) via `backend/main.py`.
|
|
>
|
|
> **Current Architecture**: Telegram bot runs as a background task within the unified backend.
|
|
> Internal API endpoints are now at `/api/telegram/internal/*` on the main port.
|
|
>
|
|
> See `CLAUDE.md` and `QUICK-START.md` for the current architecture.
|
|
|
|
**Target Server**: Windows Server (10.0.20.36)
|
|
**Deployment Method**: Windows Service (NSSM) - No Docker
|
|
**Service Name**: ROA2WEB-TelegramBot
|
|
**Internal API Port**: ~~8002~~ (DEPRECATED - now via main backend)
|
|
**Created**: 2025-10-22
|
|
**Last Updated**: 2025-10-22
|
|
|
|
---
|
|
|
|
## Table of Contents
|
|
|
|
1. [Overview](#overview)
|
|
2. [Prerequisites](#prerequisites)
|
|
3. [Deployment Architecture](#deployment-architecture)
|
|
4. [Installation Steps](#installation-steps)
|
|
5. [Configuration](#configuration)
|
|
6. [Service Management](#service-management)
|
|
7. [Database Backup](#database-backup)
|
|
8. [Monitoring & Troubleshooting](#monitoring--troubleshooting)
|
|
9. [Security Considerations](#security-considerations)
|
|
10. [Maintenance Procedures](#maintenance-procedures)
|
|
|
|
---
|
|
|
|
## Overview
|
|
|
|
The ROA2WEB Telegram Bot is deployed as a Windows Service on the same server as the backend (10.0.20.36). It provides an alternative conversational interface to ROA2WEB using Claude Agent SDK.
|
|
|
|
### Key Features
|
|
|
|
- **Conversational AI**: Claude Agent SDK with 5 custom tools
|
|
- **Account Linking**: Secure linking between Telegram and Oracle accounts
|
|
- **Real-time Queries**: Dashboard, invoices, treasury, exports
|
|
- **Database**: Standalone SQLite for Telegram-specific data
|
|
- **Internal API**: FastAPI endpoint for backend callbacks (port 8002)
|
|
- **Production Ready**: All components use real backend integration (no mocks)
|
|
|
|
### Deployment Method
|
|
|
|
- **Windows Service**: Runs via NSSM (Non-Sucking Service Manager)
|
|
- **No Docker**: Direct Windows deployment (same pattern as backend)
|
|
- **Auto-start**: Service starts automatically on server boot
|
|
- **Auto-recovery**: Service restarts automatically on failure
|
|
|
|
---
|
|
|
|
## Prerequisites
|
|
|
|
### Server Requirements
|
|
|
|
- **Operating System**: Windows Server 2016+ or Windows 10/11
|
|
- **Python**: 3.11 or higher
|
|
- **RAM**: Minimum 512 MB (dedicated to service)
|
|
- **Disk Space**: Minimum 500 MB
|
|
- **Network**: Access to localhost:8000 (backend API)
|
|
|
|
### Required Credentials
|
|
|
|
1. **Telegram Bot Token**
|
|
- Get from @BotFather on Telegram
|
|
- Command: `/newbot` or `/mybots`
|
|
- Example: `123456789:ABCdefGHIjklMNOpqrsTUVwxyz`
|
|
|
|
2. **Claude Authentication** (Choose ONE method)
|
|
|
|
**Method A: Claude Pro/Max Subscription** ⭐ **RECOMMENDED**
|
|
- ✅ **NO API key needed**
|
|
- ✅ **NO additional costs** (included in your subscription)
|
|
- ✅ Uses browser authentication
|
|
- See: [Claude Authentication Setup](#claude-authentication-setup) below
|
|
|
|
**Method B: Claude API Key** (Alternative)
|
|
- Get from Anthropic Console: https://console.anthropic.com/settings/keys
|
|
- Example: `sk-ant-api03-XXXXXXXX...`
|
|
- ⚠️ Usage-based billing applies
|
|
- Takes precedence over Method A if both are configured
|
|
|
|
3. **Backend Access**
|
|
- Backend should be running on http://localhost:8000
|
|
- Verify: `Invoke-WebRequest http://localhost:8000/health`
|
|
|
|
### Software Prerequisites
|
|
|
|
- **PowerShell 5.1+**: Built into Windows Server
|
|
- **Python 3.11+**: Will be installed if missing (via Chocolatey)
|
|
- **NSSM**: Will be installed automatically by installation script
|
|
|
|
---
|
|
|
|
## Deployment Architecture
|
|
|
|
### Directory Structure
|
|
|
|
```
|
|
C:\inetpub\wwwroot\roa2web\telegram-bot\
|
|
├── app\ # Application source code
|
|
│ ├── main.py # Entry point, Claude Agent wrapper
|
|
│ ├── bot\ # Telegram bot handlers
|
|
│ ├── agent\ # Claude Agent tools and sessions
|
|
│ ├── auth\ # Account linking logic
|
|
│ ├── db\ # SQLite database operations
|
|
│ ├── api\ # Backend API client
|
|
│ └── internal_api.py # FastAPI internal API
|
|
├── venv\ # Python virtual environment
|
|
├── data\ # SQLite database
|
|
│ └── telegram_bot.db # Main database file
|
|
├── logs\ # Application logs
|
|
│ ├── stdout.log # Service output
|
|
│ ├── stderr.log # Service errors
|
|
│ └── backup.log # Backup operations
|
|
├── backups\ # Database backups
|
|
├── temp\ # Temporary files
|
|
├── scripts\ # PowerShell management scripts
|
|
├── config\ # Configuration templates
|
|
├── requirements.txt # Python dependencies
|
|
└── .env # Environment configuration
|
|
```
|
|
|
|
### Service Integration
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────────┐
|
|
│ Windows Server 10.0.20.36 │
|
|
│ │
|
|
│ ┌──────────────────┐ ┌──────────────────┐ │
|
|
│ │ IIS (Port 80) │ │ ROA2WEB-Backend │ │
|
|
│ │ Frontend Static │ │ (Port 8000) │ │
|
|
│ └──────────────────┘ └────────┬─────────┘ │
|
|
│ │ │
|
|
│ │ HTTP API Calls │
|
|
│ │ │
|
|
│ ┌─────────────────▼──────────────┐ │
|
|
│ │ ROA2WEB-TelegramBot │ │
|
|
│ │ (Port 8002 - Internal API) │ │
|
|
│ │ - Telegram Bot Handlers │ │
|
|
│ │ - Claude Agent SDK │ │
|
|
│ │ - SQLite Database │ │
|
|
│ └────────────────────────────────┘ │
|
|
│ │
|
|
└─────────────────────────────────────────────────────────────┘
|
|
│
|
|
│ Telegram Bot API
|
|
▼
|
|
┌─────────────────┐
|
|
│ Telegram │
|
|
│ Cloud │
|
|
└─────────────────┘
|
|
```
|
|
|
|
---
|
|
|
|
## Installation Steps
|
|
|
|
### Step 1: Build Deployment Package (Development Machine)
|
|
|
|
On your development machine (WSL/Linux), run:
|
|
|
|
```bash
|
|
cd /mnt/e/proiecte/roa2web/roa2web/deployment/windows/scripts
|
|
./Build-TelegramBot.ps1
|
|
```
|
|
|
|
This creates the deployment package at:
|
|
```
|
|
../deploy-package/telegram-bot/
|
|
```
|
|
|
|
**Package Contents**:
|
|
- `app/` - Application source code
|
|
- `requirements.txt` - Python dependencies
|
|
- `.env.example` - Configuration template
|
|
- `scripts/` - PowerShell management scripts
|
|
- `config/` - Production config templates
|
|
- `README.txt` - Deployment instructions
|
|
|
|
### Step 2: Transfer Package to Server
|
|
|
|
**Option A: Network Share** (Recommended)
|
|
```powershell
|
|
# On development machine
|
|
Copy-Item -Path ./deploy-package/telegram-bot -Destination \\10.0.20.36\C$\Temp\telegram-bot-deploy -Recurse
|
|
```
|
|
|
|
**Option B: RDP**
|
|
1. Connect to server via RDP: `mstsc /v:10.0.20.36`
|
|
2. Manually copy deployment package to `C:\Temp\telegram-bot-deploy`
|
|
|
|
### Step 3: Run Installation Script
|
|
|
|
On Windows Server (10.0.20.36), open PowerShell as Administrator:
|
|
|
|
```powershell
|
|
cd C:\Temp\telegram-bot-deploy\scripts
|
|
.\Install-TelegramBot.ps1
|
|
```
|
|
|
|
**Installation Process**:
|
|
1. ✅ Checks Python 3.11+ installation
|
|
2. ✅ Installs NSSM (service manager)
|
|
3. ✅ Creates directory structure
|
|
4. ✅ Creates Python virtual environment
|
|
5. ✅ Installs Python dependencies
|
|
6. ✅ Creates Windows Service (ROA2WEB-TelegramBot)
|
|
7. ✅ Creates .env configuration template
|
|
|
|
**Installation Output**:
|
|
```
|
|
====================================================================
|
|
ROA2WEB TELEGRAM BOT INSTALLATION COMPLETED
|
|
====================================================================
|
|
|
|
Installation Details:
|
|
Install Path: C:\inetpub\wwwroot\roa2web\telegram-bot
|
|
Service Name: ROA2WEB-TelegramBot
|
|
Internal API Port: 8002
|
|
|
|
Next Steps:
|
|
1. Edit configuration: C:\inetpub\wwwroot\roa2web\telegram-bot\.env
|
|
2. Start service: .\Start-TelegramBot.ps1
|
|
```
|
|
|
|
### Step 4: Configure Environment
|
|
|
|
Edit the `.env` file:
|
|
|
|
```powershell
|
|
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
|
|
```
|
|
|
|
**Required Configuration**:
|
|
```env
|
|
# CRITICAL: Update this value
|
|
TELEGRAM_BOT_TOKEN=your_production_bot_token_from_@BotFather
|
|
|
|
# Claude Authentication: Leave empty to use Claude Pro/Max subscription
|
|
CLAUDE_API_KEY=
|
|
|
|
# Verify these are correct
|
|
BACKEND_URL=http://localhost:8000
|
|
SQLITE_DB_PATH=C:\inetpub\wwwroot\roa2web\telegram-bot\data\telegram_bot.db
|
|
INTERNAL_API_PORT=8002
|
|
LOG_LEVEL=INFO
|
|
ENVIRONMENT=production
|
|
```
|
|
|
|
**Get Bot Token**:
|
|
1. Open Telegram, search for `@BotFather`
|
|
2. Send `/newbot` or `/mybots`
|
|
3. Copy token to `TELEGRAM_BOT_TOKEN`
|
|
|
|
### Step 4a: Claude Authentication Setup
|
|
|
|
**Choose ONE authentication method:**
|
|
|
|
#### **Method A: Claude Pro/Max Subscription** ⭐ **RECOMMENDED**
|
|
|
|
If you have a Claude Pro or Claude Max subscription, use this method (NO API key needed!):
|
|
|
|
```powershell
|
|
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
|
|
.\Setup-ClaudeAuth.ps1
|
|
```
|
|
|
|
**What happens:**
|
|
1. Script installs `claude-code` CLI (if not already installed)
|
|
2. Opens your browser for authentication
|
|
3. Log in with your Claude Pro/Max account
|
|
4. Authorize the application
|
|
5. Credentials are saved to: `%APPDATA%\claude\credentials.json`
|
|
|
|
**Expected Output:**
|
|
```
|
|
====================================================================
|
|
IMPORTANT: Browser Authentication Required
|
|
====================================================================
|
|
|
|
1. A browser window will open
|
|
2. Log in with your Claude Pro/Max account
|
|
3. Authorize the application
|
|
4. Return to this window after authentication
|
|
|
|
====================================================================
|
|
|
|
[*] Opening browser for authentication...
|
|
[OK] Authentication successful!
|
|
[OK] Credentials file found and valid
|
|
[OK] .env will use Claude Pro subscription (browser login)
|
|
|
|
====================================================================
|
|
CLAUDE AUTHENTICATION SETUP COMPLETE
|
|
====================================================================
|
|
```
|
|
|
|
**Alternative: Copy credentials from development machine**
|
|
|
|
If the server doesn't have browser access, authenticate on your local machine and copy credentials:
|
|
|
|
```powershell
|
|
# On local machine (with browser):
|
|
npm install -g @anthropic-ai/claude-code
|
|
claude-code login
|
|
|
|
# Copy credentials file to server
|
|
Copy-Item "$env:APPDATA\claude\credentials.json" -Destination "\\10.0.20.36\C$\Temp\claude-credentials.json"
|
|
|
|
# On server:
|
|
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
|
|
.\Setup-ClaudeAuth.ps1 -Method copy -CredentialsPath "C:\Temp\claude-credentials.json"
|
|
```
|
|
|
|
#### **Method B: Claude API Key** (Alternative)
|
|
|
|
If you prefer to use an API key instead:
|
|
|
|
1. Visit https://console.anthropic.com/settings/keys
|
|
2. Create new key
|
|
3. Edit `.env` and set `CLAUDE_API_KEY=sk-ant-api03-XXXXXXXX...`
|
|
4. ⚠️ Usage-based billing applies
|
|
|
|
**Note:** API key takes precedence over browser login if both are configured.
|
|
|
|
### Step 5: Start Service
|
|
|
|
```powershell
|
|
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
|
|
.\Start-TelegramBot.ps1
|
|
```
|
|
|
|
**Expected Output**:
|
|
```
|
|
[*] Starting ROA2WEB Telegram Bot Service...
|
|
[*] Service start command issued
|
|
[*] Waiting for service to start... (5/30)
|
|
[OK] Service started successfully
|
|
[OK] Health check passed: healthy
|
|
[OK] Database: connected
|
|
```
|
|
|
|
### Step 6: Verify Installation
|
|
|
|
**Check Service Status**:
|
|
```powershell
|
|
Get-Service ROA2WEB-TelegramBot
|
|
```
|
|
|
|
Expected: `Status = Running`
|
|
|
|
**Check Health Endpoint**:
|
|
```powershell
|
|
Invoke-WebRequest http://localhost:8002/internal/health | ConvertFrom-Json
|
|
```
|
|
|
|
Expected Output:
|
|
```json
|
|
{
|
|
"status": "healthy",
|
|
"timestamp": "2025-10-22T14:30:00",
|
|
"database": {
|
|
"status": "connected",
|
|
"users": 0,
|
|
"pending_codes": 0
|
|
}
|
|
}
|
|
```
|
|
|
|
**Test Bot on Telegram**:
|
|
1. Open Telegram
|
|
2. Search for your bot (name from @BotFather)
|
|
3. Send `/start`
|
|
4. Expected: Welcome message with linking instructions
|
|
|
|
---
|
|
|
|
## Configuration
|
|
|
|
### Environment Variables Reference
|
|
|
|
See `.env.production.windows.telegram` in `config/` directory for complete reference.
|
|
|
|
**Key Settings**:
|
|
|
|
| Variable | Default | Description |
|
|
|----------|---------|-------------|
|
|
| `TELEGRAM_BOT_TOKEN` | *required* | Bot token from @BotFather |
|
|
| `CLAUDE_API_KEY` | *required* | API key from Anthropic |
|
|
| `BACKEND_URL` | `http://localhost:8000` | Backend API URL |
|
|
| `SQLITE_DB_PATH` | `C:\...\telegram_bot.db` | Database file location |
|
|
| `INTERNAL_API_PORT` | `8002` | Internal API port |
|
|
| `LOG_LEVEL` | `INFO` | Logging level (DEBUG/INFO/WARN/ERROR) |
|
|
| `ENVIRONMENT` | `production` | Environment name |
|
|
| `AUTH_CODE_EXPIRY_MINUTES` | `15` | Linking code expiry time |
|
|
| `SESSION_TIMEOUT_MINUTES` | `60` | User session timeout |
|
|
| `MAX_CONVERSATION_HISTORY` | `20` | Max messages per session |
|
|
|
|
### Applying Configuration Changes
|
|
|
|
After editing `.env`:
|
|
|
|
```powershell
|
|
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
|
|
.\Restart-TelegramBot.ps1
|
|
```
|
|
|
|
---
|
|
|
|
## Service Management
|
|
|
|
### Start Service
|
|
|
|
```powershell
|
|
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
|
|
.\Start-TelegramBot.ps1
|
|
```
|
|
|
|
### Stop Service
|
|
|
|
```powershell
|
|
.\Stop-TelegramBot.ps1
|
|
```
|
|
|
|
### Restart Service
|
|
|
|
```powershell
|
|
.\Restart-TelegramBot.ps1
|
|
```
|
|
|
|
### Check Service Status
|
|
|
|
```powershell
|
|
Get-Service ROA2WEB-TelegramBot
|
|
|
|
# Detailed info
|
|
Get-Service ROA2WEB-TelegramBot | Select-Object *
|
|
```
|
|
|
|
### View Logs
|
|
|
|
**Real-time Logs** (tail -f equivalent):
|
|
```powershell
|
|
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stdout.log -Tail 50 -Wait
|
|
```
|
|
|
|
**Error Logs**:
|
|
```powershell
|
|
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stderr.log -Tail 100
|
|
```
|
|
|
|
**Backup Logs**:
|
|
```powershell
|
|
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\backup.log -Tail 50
|
|
```
|
|
|
|
---
|
|
|
|
## Database Backup
|
|
|
|
### Manual Backup
|
|
|
|
```powershell
|
|
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
|
|
.\Backup-TelegramDB.ps1
|
|
```
|
|
|
|
**Output**:
|
|
- Backup file: `backups/telegram_bot_backup_YYYYMMDD-HHMMSS.db.zip`
|
|
- Compressed and timestamped
|
|
- Integrity tested automatically
|
|
|
|
### Setup Automated Daily Backup
|
|
|
|
```powershell
|
|
cd C:\inetpub\wwwroot\roa2web\telegram-bot\scripts
|
|
.\Setup-DailyBackup.ps1
|
|
```
|
|
|
|
**Configuration**:
|
|
- Runs daily at 2:00 AM
|
|
- Keeps last 30 days of backups
|
|
- Runs as SYSTEM account
|
|
- Logs all operations
|
|
|
|
**Verify Scheduled Task**:
|
|
```powershell
|
|
Get-ScheduledTask -TaskName "ROA2WEB-TelegramBot-Backup"
|
|
```
|
|
|
|
**Run Backup Manually** (via Task Scheduler):
|
|
```powershell
|
|
Start-ScheduledTask -TaskName "ROA2WEB-TelegramBot-Backup"
|
|
```
|
|
|
|
### Restore from Backup
|
|
|
|
1. Stop service:
|
|
```powershell
|
|
.\Stop-TelegramBot.ps1
|
|
```
|
|
|
|
2. Find backup file:
|
|
```powershell
|
|
Get-ChildItem C:\inetpub\wwwroot\roa2web\telegram-bot\backups | Sort-Object LastWriteTime -Descending
|
|
```
|
|
|
|
3. Extract backup (if compressed):
|
|
```powershell
|
|
Expand-Archive -Path "backups\telegram_bot_backup_YYYYMMDD-HHMMSS.db.zip" -DestinationPath "temp\"
|
|
```
|
|
|
|
4. Replace database:
|
|
```powershell
|
|
Copy-Item -Path "temp\telegram_bot_backup_YYYYMMDD-HHMMSS.db" -Destination "data\telegram_bot.db" -Force
|
|
```
|
|
|
|
5. Start service:
|
|
```powershell
|
|
.\Start-TelegramBot.ps1
|
|
```
|
|
|
|
---
|
|
|
|
## Monitoring & Troubleshooting
|
|
|
|
### Health Checks
|
|
|
|
**Service Health**:
|
|
```powershell
|
|
Get-Service ROA2WEB-TelegramBot | Select-Object Name, Status, StartType
|
|
```
|
|
|
|
**API Health**:
|
|
```powershell
|
|
Invoke-WebRequest http://localhost:8002/internal/health
|
|
```
|
|
|
|
**Database Stats**:
|
|
```powershell
|
|
(Invoke-WebRequest http://localhost:8002/internal/stats).Content | ConvertFrom-Json
|
|
```
|
|
|
|
### Common Issues
|
|
|
|
#### Service Won't Start
|
|
|
|
**Symptoms**: Service shows "Stopped" or "Starting" forever
|
|
|
|
**Diagnosis**:
|
|
```powershell
|
|
Get-Content C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stderr.log -Tail 100
|
|
```
|
|
|
|
**Common Causes**:
|
|
1. **Missing .env file** → Create from `.env.example`
|
|
2. **Invalid bot token** → Check `TELEGRAM_BOT_TOKEN`
|
|
3. **Invalid Claude API key** → Check `CLAUDE_API_KEY`
|
|
4. **Port 8002 already in use** → Change `INTERNAL_API_PORT`
|
|
5. **Backend not running** → Start ROA2WEB-Backend service
|
|
|
|
**Solutions**:
|
|
```powershell
|
|
# Fix config
|
|
notepad C:\inetpub\wwwroot\roa2web\telegram-bot\.env
|
|
|
|
# Check port availability
|
|
Get-NetTCPConnection -LocalPort 8002
|
|
|
|
# Restart service
|
|
.\Restart-TelegramBot.ps1
|
|
```
|
|
|
|
#### Bot Not Responding on Telegram
|
|
|
|
**Symptoms**: Bot doesn't reply to messages
|
|
|
|
**Diagnosis**:
|
|
1. Check service status:
|
|
```powershell
|
|
Get-Service ROA2WEB-TelegramBot
|
|
```
|
|
2. Check health endpoint:
|
|
```powershell
|
|
Invoke-WebRequest http://localhost:8002/internal/health
|
|
```
|
|
3. Check logs for errors:
|
|
```powershell
|
|
Get-Content logs\stderr.log -Tail 50
|
|
```
|
|
|
|
**Common Causes**:
|
|
1. **Service stopped** → Start service
|
|
2. **Invalid bot token** → Update `.env`
|
|
3. **Network issues** → Check internet connectivity
|
|
4. **Bot blocked by user** → User must /start bot again
|
|
|
|
#### Account Linking Fails
|
|
|
|
**Symptoms**: `/link CODE` returns error
|
|
|
|
**Diagnosis**:
|
|
```powershell
|
|
# Check internal API
|
|
Invoke-WebRequest http://localhost:8002/internal/stats
|
|
|
|
# Check backend connectivity
|
|
Invoke-WebRequest http://localhost:8000/health
|
|
```
|
|
|
|
**Common Causes**:
|
|
1. **Code expired** (15 min) → Generate new code
|
|
2. **Backend unreachable** → Check ROA2WEB-Backend service
|
|
3. **Database error** → Check SQLite file permissions
|
|
|
|
#### Database Errors
|
|
|
|
**Symptoms**: "Database locked" or "Cannot open database"
|
|
|
|
**Diagnosis**:
|
|
```powershell
|
|
# Check database file
|
|
Test-Path C:\inetpub\wwwroot\roa2web\telegram-bot\data\telegram_bot.db
|
|
|
|
# Check file permissions
|
|
icacls C:\inetpub\wwwroot\roa2web\telegram-bot\data\telegram_bot.db
|
|
```
|
|
|
|
**Solutions**:
|
|
```powershell
|
|
# Stop service
|
|
.\Stop-TelegramBot.ps1
|
|
|
|
# Fix permissions
|
|
icacls C:\inetpub\wwwroot\roa2web\telegram-bot\data /grant "SYSTEM:(OI)(CI)F" /T
|
|
|
|
# Restart service
|
|
.\Start-TelegramBot.ps1
|
|
```
|
|
|
|
---
|
|
|
|
## Security Considerations
|
|
|
|
### Secrets Management
|
|
|
|
**NEVER**:
|
|
- Commit `.env` to git
|
|
- Share bot token or API keys
|
|
- Log sensitive data
|
|
|
|
**ALWAYS**:
|
|
- Keep backups of `.env` in secure location
|
|
- Rotate API keys periodically
|
|
- Use strong file permissions
|
|
|
|
**File Permissions**:
|
|
```powershell
|
|
# Restrict .env to SYSTEM and Administrators only
|
|
icacls C:\inetpub\wwwroot\roa2web\telegram-bot\.env /grant "SYSTEM:F" /grant "Administrators:F" /inheritance:r
|
|
```
|
|
|
|
### Network Security
|
|
|
|
- **Internal API (8002)**: Bind to 127.0.0.1 (localhost only)
|
|
- **Backend API (8000)**: Already on localhost
|
|
- **No Firewall Rules Needed**: All communication is local
|
|
|
|
### Bot Security
|
|
|
|
- **Account Linking**: 8-character codes, 15-minute expiry
|
|
- **JWT Tokens**: Signed and verified by backend
|
|
- **Rate Limiting**: Built into authentication middleware
|
|
- **Session Timeout**: 60 minutes of inactivity
|
|
|
|
---
|
|
|
|
## Maintenance Procedures
|
|
|
|
### Updates and Deployments
|
|
|
|
1. **Build new deployment package** (dev machine):
|
|
```bash
|
|
./Build-TelegramBot.ps1
|
|
```
|
|
|
|
2. **Transfer to server**:
|
|
```powershell
|
|
Copy-Item -Path ./deploy-package/telegram-bot -Destination \\10.0.20.36\C$\Temp\telegram-bot-update -Recurse
|
|
```
|
|
|
|
3. **Deploy update** (server):
|
|
```powershell
|
|
cd C:\Temp\telegram-bot-update\scripts
|
|
.\Deploy-TelegramBot.ps1
|
|
```
|
|
|
|
**Deployment Features**:
|
|
- ✅ Automatic backup before deployment
|
|
- ✅ Stops service, updates files, restarts service
|
|
- ✅ Preserves `.env` configuration
|
|
- ✅ Automatic rollback on failure
|
|
- ✅ Health check after deployment
|
|
|
|
### Log Rotation
|
|
|
|
Logs are automatically rotated by Python logging:
|
|
- **Max size**: 10 MB per file
|
|
- **Backups**: 5 old log files kept
|
|
- **Location**: `C:\inetpub\wwwroot\roa2web\telegram-bot\logs\`
|
|
|
|
**Manual cleanup**:
|
|
```powershell
|
|
# Delete old logs (older than 30 days)
|
|
Get-ChildItem C:\inetpub\wwwroot\roa2web\telegram-bot\logs\*.log |
|
|
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) } |
|
|
Remove-Item -Force
|
|
```
|
|
|
|
### Database Maintenance
|
|
|
|
**Cleanup expired data** (automatic via scheduled task):
|
|
- Expired auth codes (older than 15 minutes)
|
|
- Old sessions (inactive for 60+ minutes)
|
|
- Runs hourly automatically
|
|
|
|
**Manual cleanup**:
|
|
```sql
|
|
-- Connect to database
|
|
sqlite3 C:\inetpub\wwwroot\roa2web\telegram-bot\data\telegram_bot.db
|
|
|
|
-- Delete expired codes
|
|
DELETE FROM telegram_auth_codes WHERE created_at < datetime('now', '-15 minutes');
|
|
|
|
-- Delete old sessions
|
|
DELETE FROM telegram_sessions WHERE updated_at < datetime('now', '-60 minutes');
|
|
```
|
|
|
|
### Service Health Monitoring
|
|
|
|
**Daily Checks** (manual or script):
|
|
```powershell
|
|
# Service status
|
|
Get-Service ROA2WEB-TelegramBot
|
|
|
|
# Health endpoint
|
|
Invoke-WebRequest http://localhost:8002/internal/health
|
|
|
|
# Check logs for errors
|
|
Get-Content logs\stderr.log -Tail 50 | Select-String "ERROR"
|
|
|
|
# Check database size
|
|
(Get-Item data\telegram_bot.db).Length / 1MB
|
|
```
|
|
|
|
**Weekly Checks**:
|
|
- Review backup logs
|
|
- Check backup retention (30 days)
|
|
- Review disk space usage
|
|
- Check for Windows updates
|
|
|
|
---
|
|
|
|
## Appendix
|
|
|
|
### PowerShell Scripts Reference
|
|
|
|
| Script | Purpose |
|
|
|--------|---------|
|
|
| `Install-TelegramBot.ps1` | Initial installation |
|
|
| `Deploy-TelegramBot.ps1` | Deploy updates |
|
|
| `Build-TelegramBot.ps1` | Build deployment package |
|
|
| `Start-TelegramBot.ps1` | Start service |
|
|
| `Stop-TelegramBot.ps1` | Stop service |
|
|
| `Restart-TelegramBot.ps1` | Restart service |
|
|
| `Backup-TelegramDB.ps1` | Manual database backup |
|
|
| `Setup-DailyBackup.ps1` | Configure automated backups |
|
|
|
|
### API Endpoints
|
|
|
|
| Endpoint | Method | Description |
|
|
|----------|--------|-------------|
|
|
| `/internal/health` | GET | Health check |
|
|
| `/internal/stats` | GET | Database statistics |
|
|
| `/internal/save-code` | POST | Save auth code (from backend) |
|
|
| `/internal/verify-code` | POST | Verify auth code |
|
|
|
|
### Database Schema
|
|
|
|
**telegram_users**:
|
|
```sql
|
|
CREATE TABLE telegram_users (
|
|
telegram_user_id INTEGER PRIMARY KEY,
|
|
oracle_user_id INTEGER NOT NULL,
|
|
oracle_username TEXT NOT NULL,
|
|
jwt_token TEXT NOT NULL,
|
|
jwt_refresh_token TEXT,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
```
|
|
|
|
**telegram_auth_codes**:
|
|
```sql
|
|
CREATE TABLE telegram_auth_codes (
|
|
code TEXT PRIMARY KEY,
|
|
oracle_user_id INTEGER NOT NULL,
|
|
oracle_username TEXT NOT NULL,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
expires_at TIMESTAMP NOT NULL,
|
|
used INTEGER DEFAULT 0
|
|
);
|
|
```
|
|
|
|
**telegram_sessions**:
|
|
```sql
|
|
CREATE TABLE telegram_sessions (
|
|
telegram_user_id INTEGER PRIMARY KEY,
|
|
conversation_history TEXT, -- JSON
|
|
session_data TEXT, -- JSON
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);
|
|
```
|
|
|
|
---
|
|
|
|
## Support
|
|
|
|
**Documentation**:
|
|
- Project README: `/mnt/e/proiecte/roa2web/roa2web/backend/modules/telegram/README.md`
|
|
- Progress Tracker: `/mnt/e/proiecte/roa2web/roa2web/development/TELEGRAM_BOT_PROGRESS.md`
|
|
- Production Deployment Plan: `/mnt/e/proiecte/roa2web/roa2web/development/TELEGRAM_BOT_PRODUCTION_DEPLOYMENT.md`
|
|
|
|
**Logs Location**:
|
|
- Service Output: `C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stdout.log`
|
|
- Service Errors: `C:\inetpub\wwwroot\roa2web\telegram-bot\logs\stderr.log`
|
|
- Backups: `C:\inetpub\wwwroot\roa2web\telegram-bot\logs\backup.log`
|
|
|
|
**Contact**: ROA2WEB Development Team
|
|
|
|
---
|
|
|
|
**Document Version**: 1.0
|
|
**Last Updated**: 2025-10-22
|
|
**Status**: Production Ready
|