Change hardcoded default backend URL from development port (8001) to production port (8000) in Telegram bot API client. This fixes the issue where Telegram bot would try to connect to wrong port when BACKEND_URL environment variable is not properly loaded from .env file, causing "Cannot connect to backend" errors during account linking. Root cause: When .env file is not loaded correctly by Windows Service, the code falls back to the hardcoded default value which was incorrectly set to the development port 8001 instead of production port 8000. Changes: - reports-app/telegram-bot/app/api/client.py: Change default from 8001 to 8000 - Add comment explaining this is for production deployment This ensures the bot connects to the correct backend port even if .env configuration has issues during service startup on Windows Server. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
ROA2WEB Telegram Bot
Telegram Frontend for ROA2WEB ERP System with Direct Command Interface
Overview
ROA2WEB Telegram Bot provides a command-based interface to the ROA2WEB Financial ERP system through Telegram. Users can access dashboards, invoices, treasury data, and company information using simple slash commands.
Key Features
- Direct Command Interface: Simple
/commands for all operations - Simplified Authentication 🆕: Multiple linking methods (Deep Link, QR Code, Manual) - 77% faster than before!
- One-Click Connection: Deep link automatically opens Telegram with pre-populated code
- QR Code Support: Scan from mobile to link instantly (cross-device)
- Secure Authentication: Account linking with Oracle backend and JWT token management
- Financial Data Access: Query dashboards, invoices, treasury data, and company information
- Company Selection: Set active company for all subsequent queries
- Multi-language: Romanian and English support
- Session Management: Active company persistence with SQLite database
- Docker Ready: Containerized deployment with Docker Compose
Architecture
System Components
telegram-bot/
├── app/
│ ├── agent/ # Session management
│ │ └── session.py # Active company persistence
│ ├── api/ # Backend API client
│ │ └── client.py # HTTP client for ROA2WEB backend
│ ├── auth/ # Authentication & linking
│ │ └── linking.py # Account linking logic
│ ├── bot/ # Telegram bot handlers
│ │ ├── handlers.py # Command handlers
│ │ ├── helpers.py # Helper functions
│ │ ├── formatters.py # Response formatting
│ │ └── keyboards.py # Inline keyboard helpers
│ ├── db/ # SQLite database (standalone)
│ │ ├── database.py # Connection & schema
│ │ └── operations.py # CRUD operations
│ ├── internal_api.py # FastAPI for backend communication
│ └── main.py # Main entry point
├── data/ # SQLite database storage (gitignored)
├── tests/ # Unit & integration tests
├── Dockerfile # Container configuration
├── requirements.txt # Python dependencies
└── .env.example # Environment variables template
Data Flow
- User sends command → Telegram → Bot Command Handlers
- Authentication check → SQLite database → JWT validation
- API calls → ROA2WEB Backend → Oracle database
- Response formatting → Telegram user
Database Schema (SQLite)
The bot uses a standalone SQLite database for:
- telegram_users: User accounts and Oracle account linking
- telegram_auth_codes: Temporary 8-character linking codes (15 min expiry)
- telegram_sessions: Active company selection and session state
Installation & Setup
Prerequisites
- Python 3.11+
- Telegram account
- ROA2WEB backend API running (default: http://localhost:8001)
Step 1: Create Telegram Bot
- Open Telegram and search for
@BotFather - Send
/newbotcommand - Follow prompts to create bot
- Save the bot token provided
Step 2: Install Dependencies
# Navigate to telegram-bot directory
cd reports-app/telegram-bot
# Create virtual environment
python3 -m venv venv
# Activate virtual environment
source venv/bin/activate # Linux/Mac
# or
venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
Step 3: Configure Environment
# Copy environment template
cp .env.example .env
# Edit .env file with your configuration
nano .env
Required configuration in .env:
# Required
TELEGRAM_BOT_TOKEN=your_bot_token_from_botfather
BACKEND_URL=http://localhost:8001
# Database
SQLITE_DB_PATH=./data/telegram_bot.db
# Internal API (for backend communication)
INTERNAL_API_PORT=8002
# Optional
LOG_LEVEL=INFO
SENTRY_DSN=https://your-sentry-dsn
ENVIRONMENT=production
Step 4: Run the Bot
# Make sure backend is running first
# Backend should be at http://localhost:8001 (or configured BACKEND_URL)
# Run the bot
python -m app.main
Usage
Available Commands
| Command | Description |
|---|---|
/start [code] |
Start bot or link account with 8-char code |
/help |
Show available commands and usage guide |
/companies |
View accessible companies/firms |
/selectcompany [name] |
Select or search for active company |
/dashboard |
View financial dashboard for active company |
/sold |
View balance (alias for /dashboard) |
/facturi [filter] |
View invoices (optional filters: neplatite, platite) |
/trezorerie |
View treasury/payment data |
/clear |
Clear active company selection |
/unlink |
Unlink Telegram account from Oracle |
Authentication Flow (Updated 2025 - FAZA 1 Improvements)
The bot now supports 3 easy methods for account linking:
Method 1: Deep Link (Recommended - One Click) 🚀
- Login to ROA2WEB web application at http://localhost:3000
- Navigate to
/telegram(Settings → Telegram) - Click "Generează Cod" button
- Click "🚀 Deschide în Telegram" button
- Telegram opens automatically with code pre-populated
- Done! Account linked in <30 seconds
Benefits:
- ⚡ Zero manual copying - code is pre-filled
- 🎯 One click - Telegram opens automatically
- ⏱️ Super fast - complete in ~30 seconds
- 📱 Works on desktop and mobile (same device)
Method 2: QR Code (Cross-Device) 📷
Perfect when working on desktop but have Telegram on mobile:
- Login to ROA2WEB web app (desktop)
- Navigate to
/telegram - Click "Generează Cod"
- Scan QR Code displayed on screen with Telegram on mobile
- Telegram opens with code pre-populated
- Done! Account linked
Benefits:
- 📱 Cross-device - desktop browser → mobile Telegram
- 📷 Easy scanning - just point camera at screen
- ✅ No typing - code automatically loaded
Method 3: Manual (Traditional Fallback) ⌨️
If deep link or QR code don't work:
- Login to ROA2WEB web application
- Navigate to
/telegram - Click "Generează Cod"
- Click copy button (📋) to copy code
- Open Telegram manually
- Send code to bot:
- Direct input:
ABC123XY(just paste) - Classic format:
/start ABC123XY
- Direct input:
- Done! Account linked
Technical Details:
- Backend generates 8-character code (valid 15 minutes)
- Backend saves code to telegram-bot via internal API (
POST /internal/save-code) - Bot verifies code and links accounts in SQLite database
- Bot receives JWT token from backend
- User can now use commands to query financial data
Improvement Metrics:
- ⏱️ Time: 3 minutes → 40 seconds (77% reduction)
- 📉 Steps: 7 → 4 (43% reduction)
- ✅ Manual copying: Eliminated (with Method 1 or 2)
Usage Examples
User: /companies
Bot: Lists all accessible companies with ID, name, and CUI
User: /selectcompany ACME
Bot: Shows selection keyboard for companies matching "ACME"
[User clicks company button]
Bot: Company selected: ACME SRL
User: /dashboard
Bot: Displays dashboard statistics for ACME SRL:
- Total balance
- Invoices issued/paid/unpaid
- Total collections and payments
User: /facturi neplatite
Bot: Shows list of unpaid invoices for ACME SRL
User: /trezorerie
Bot: Displays treasury data (cash balance, bank accounts, etc.)
User: /clear
Bot: Active company cleared. Use /selectcompany to select another.
Docker Deployment
Build Image
# From telegram-bot directory
docker build -t roa-telegram-bot .
Run Container
docker run -d \
--name roa-telegram-bot \
-e TELEGRAM_BOT_TOKEN=your_token \
-e BACKEND_URL=http://backend:8001 \
-v $(pwd)/data:/app/data \
roa-telegram-bot
Docker Compose
See docker-compose.yml in project root for full orchestration with backend and database.
Development
Project Structure
- app/main.py: Bot entry point and Telegram application setup
- app/bot/handlers.py: All command handlers (
/start,/dashboard, etc.) - app/bot/helpers.py: Helper functions for company selection and prompts
- app/bot/formatters.py: Response formatting utilities
- app/auth/linking.py: Account linking and JWT management
- app/api/client.py: HTTP client for backend API calls
- app/agent/session.py: Session management (active company persistence)
- app/db/: SQLite database operations
- app/internal_api.py: FastAPI for backend callbacks
Running Tests
# Run all tests
pytest tests/ -v
# Run specific test suites
pytest tests/test_auth.py -v # Authentication tests
pytest tests/test_session_company.py -v # Session & company tests
pytest tests/test_helpers.py -v # Helper function tests
pytest tests/test_formatters.py -v # Formatter tests
# Run with coverage
pytest tests/ --cov=app --cov-report=html
Adding New Commands
- Add handler function in
app/bot/handlers.py:
async def my_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
# Implementation
pass
- Register handler in
app/main.py:
application.add_handler(CommandHandler("mycommand", my_command))
- Add to
__all__export inhandlers.py
User Experience Improvements (2025)
FAZA 1: Authentication Simplification ✅
Implemented: January 2025 Status: Production Ready
What Changed:
- Added Deep Link button - one-click Telegram opening
- Added QR Code generation for cross-device linking
- Improved Manual method with copy button
- Reduced linking time by 77% (3 min → 40 sec)
- Reduced steps by 43% (7 → 4 steps)
Documentation:
- Complete Plan: TELEGRAM_AUTH_IMPROVEMENT_PLAN.md
- Testing Guide: TESTING_INSTRUCTIONS_FAZA1.md
- Implementation Summary: FAZA1_IMPLEMENTATION_SUMMARY.md
Frontend Changes:
reports-app/frontend/src/views/TelegramView.vue- Complete UI refactor- Added
qrcode.vuedependency for QR generation - Environment variable:
VITE_TELEGRAM_BOT_USERNAME
FAZA 2: Email Magic Link (Optional - Future)
Status: Planned Estimated: 3.5 hours development
What's Planned:
- Email with magic link option
- Professional HTML email template
- Auto-detect SMTP configuration
- Checkbox "Send code via email"
Prerequisites:
- SMTP server configuration (Gmail, SendGrid, AWS SES)
- User email addresses in Oracle database
Note: FAZA 2 is completely optional. FAZA 1 provides excellent UX for most users.
Troubleshooting
Bot Not Responding
- Check bot is running:
ps aux | grep python.*main.py - Check logs:
tail -f logs/telegram-bot.log - Verify TELEGRAM_BOT_TOKEN is correct
- Ensure backend is accessible at BACKEND_URL
Authentication Issues
- Check auth code expiry (15 minutes)
- Verify backend internal API is accessible (port 8002)
- Check SQLite database permissions
- Deep Link not working? Browser may block protocol handler - click "Allow" when prompted
- QR Code not scanning? Ensure good lighting and camera focus
- Manual method always works as fallback
Database Issues
- Ensure
data/directory exists and is writable - Check database file:
sqlite3 data/telegram_bot.db ".schema" - Automatic cleanup runs hourly for expired data
Deep Link Issues (FAZA 1)
Problem: Deep link button doesn't open Telegram
Solutions:
- Desktop: Browser may ask permission - click "Allow" to open Telegram
- Mobile: Ensure Telegram app is installed
- Fallback: Use QR Code (Method 2) or Manual (Method 3)
Browser Compatibility:
- ✅ Chrome/Edge - Works perfectly
- ⚠️ Firefox - May show permission prompt
- ⚠️ Safari - May show permission prompt
- ✅ Mobile browsers - Works on all major browsers
Problem: QR Code doesn't display
Solutions:
- Check browser console for errors (F12)
- Ensure
qrcode.vuepackage is installed:npm list qrcode.vue - Rebuild frontend:
cd frontend && npm run build - Fallback: Use Manual method (always works)
API Integration
The bot communicates with ROA2WEB backend via HTTP API:
POST /api/telegram/auth/verify-user- Verify user_idPOST /api/telegram/auth/refresh-token- Refresh JWTGET /api/companies- Get user companiesGET /api/dashboard/{company_id}- Dashboard dataGET /api/invoices/{company_id}- Invoice listGET /api/treasury/{company_id}- Treasury data
All requests include JWT token in Authorization header (except verify-user endpoint).
Security
- JWT tokens are stored encrypted in SQLite
- Auth codes expire after 15 minutes
- Sessions are automatically cleaned up
- Environment variables never committed to git
- Rate limiting on authentication endpoints
License
See main project LICENSE file.
Support
For issues, questions, or contributions, see the main ROA2WEB project documentation.