#!/usr/bin/env python3 """ Setup Bot Commands Script Automatically registers bot commands with Telegram API. This script should be run after deploying the bot or when updating commands. Usage: python setup_bot_commands.py Requirements: - TELEGRAM_BOT_TOKEN in .env file - requests library (pip install requests) """ import os import sys import requests from dotenv import load_dotenv from pathlib import Path # Load environment variables env_path = Path(__file__).parent / '.env' load_dotenv(env_path) # Get bot token BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN') if not BOT_TOKEN: print("❌ ERROR: TELEGRAM_BOT_TOKEN not found in .env file") print("Please set TELEGRAM_BOT_TOKEN in your .env file") sys.exit(1) # Define bot commands # Order matters - this is how they'll appear in the Telegram UI COMMANDS = [ { "command": "start", "description": "Link cont sau pornire bot" }, { "command": "help", "description": "Informații și ajutor" }, { "command": "companies", "description": "Vezi companiile tale" }, { "command": "selectcompany", "description": "Selectează/caută companie activă" }, { "command": "dashboard", "description": "Dashboard financiar" }, { "command": "sold", "description": "Vezi sold și situație financiară" }, { "command": "facturi", "description": "Listă facturi (opțional: status)" }, { "command": "trezorerie", "description": "Date trezorerie și cash flow" }, { "command": "export", "description": "Export rapoarte (Excel/PDF/CSV)" }, { "command": "clear", "description": "Șterge conversație" }, { "command": "unlink", "description": "Deconectează contul" } ] def set_bot_commands(token: str, commands: list) -> bool: """ Set bot commands via Telegram Bot API. Args: token: Telegram bot token commands: List of command dictionaries with 'command' and 'description' keys Returns: True if successful, False otherwise """ url = f"https://api.telegram.org/bot{token}/setMyCommands" try: print(f"📡 Sending commands to Telegram API...") print(f" Commands to register: {len(commands)}") response = requests.post( url, json={"commands": commands}, timeout=10 ) response.raise_for_status() result = response.json() if result.get('ok'): print("✅ SUCCESS: Bot commands registered successfully!") print(f"\n📋 Registered commands:") for cmd in commands: print(f" /{cmd['command']} - {cmd['description']}") return True else: print(f"❌ ERROR: API returned ok=false") print(f" Response: {result}") return False except requests.exceptions.RequestException as e: print(f"❌ ERROR: Failed to connect to Telegram API") print(f" {type(e).__name__}: {e}") return False except Exception as e: print(f"❌ ERROR: Unexpected error occurred") print(f" {type(e).__name__}: {e}") return False def get_bot_commands(token: str) -> dict: """ Get current bot commands from Telegram API. Args: token: Telegram bot token Returns: API response dictionary """ url = f"https://api.telegram.org/bot{token}/getMyCommands" try: response = requests.get(url, timeout=10) response.raise_for_status() return response.json() except Exception as e: print(f"⚠️ WARNING: Could not fetch current commands: {e}") return {} def verify_bot_token(token: str) -> bool: """ Verify that the bot token is valid by calling getMe. Args: token: Telegram bot token Returns: True if token is valid, False otherwise """ url = f"https://api.telegram.org/bot{token}/getMe" try: print("🔑 Verifying bot token...") response = requests.get(url, timeout=10) response.raise_for_status() result = response.json() if result.get('ok'): bot_info = result.get('result', {}) print(f"✅ Token valid for bot: @{bot_info.get('username', 'unknown')}") print(f" Bot ID: {bot_info.get('id')}") print(f" First name: {bot_info.get('first_name')}") return True else: print("❌ Token verification failed") return False except Exception as e: print(f"❌ Token verification error: {e}") return False def main(): """Main entry point.""" print("=" * 60) print("🤖 ROA2WEB Telegram Bot - Command Setup") print("=" * 60) print() # Verify token if not verify_bot_token(BOT_TOKEN): print("\n❌ FAILED: Invalid bot token") sys.exit(1) print() # Get current commands (for comparison) print("📥 Fetching current commands...") current = get_bot_commands(BOT_TOKEN) if current.get('ok'): current_commands = current.get('result', []) print(f" Current commands: {len(current_commands)}") if current_commands: for cmd in current_commands: print(f" - /{cmd['command']}: {cmd['description']}") print() # Set new commands success = set_bot_commands(BOT_TOKEN, COMMANDS) print() print("=" * 60) if success: print("✅ SETUP COMPLETE!") print() print("📱 Next steps:") print(" 1. Open Telegram and go to your bot") print(" 2. Type '/' to see the command menu") print(" 3. Verify all commands appear correctly") print() print("🔗 Bot: @ROA2WEBDEVBot") sys.exit(0) else: print("❌ SETUP FAILED!") print() print("🔧 Troubleshooting:") print(" 1. Verify TELEGRAM_BOT_TOKEN in .env file") print(" 2. Check internet connection") print(" 3. Ensure bot token has correct permissions") print() print("📖 See TELEGRAM_COMMANDS.md for manual setup instructions") sys.exit(1) if __name__ == "__main__": main()