# Telegram Setup Guide Complete guide for setting up Telegram signal monitoring in Lancelot Bot using the web-based setup wizard. ## Table of Contents - [Overview](#overview) - [Prerequisites](#prerequisites) - [Setup Methods](#setup-methods) - [Web UI Setup (Recommended)](#web-ui-setup-recommended) - [Command Line Setup](#command-line-setup) - [Troubleshooting](#troubleshooting) - [FAQ](#faq) - [Security Best Practices](#security-best-practices) ## Overview Lancelot Bot can monitor Telegram channels for trading signals using your personal Telegram account. This allows you to: - ✅ Monitor any public or private channel you're a member of - ✅ Automatically extract token contract addresses from messages - ✅ Validate signals against liquidity and safety metrics - ✅ Execute or simulate trades based on channel signals - ✅ No need to add bots to channels or request admin permissions The setup process authenticates your Telegram account once, creating a persistent session file that survives container restarts. ## Prerequisites Before starting Telegram setup, ensure you have: ### 1. Telegram API Credentials You need an API ID and API Hash from Telegram: 1. Go to **https://my.telegram.org/apps** 2. Log in with your phone number 3. Click "API development tools" 4. Fill in the form: - **App title**: Any name (e.g., "Lancelot Bot") - **Short name**: Any short name (e.g., "lancelot") - **Platform**: Other - **Description**: Optional 5. Click "Create application" 6. Save your **API ID** (numeric) and **API Hash** (32-character hex string) **Example**: ``` API ID: 1234567 API Hash: abcdef1234567890abcdef1234567890 ``` ### 2. Telegram Account - Active Telegram account with phone number - Access to receive verification codes (Telegram app on phone/desktop) - If you have 2FA enabled, you'll need your cloud password ### 3. Environment Configuration Add your API credentials to `.env`: ```bash # Telegram Configuration TELEGRAM_API_ID=1234567 TELEGRAM_API_HASH=abcdef1234567890abcdef1234567890 TELEGRAM_CHANNELS=channel1,channel2,channel3 ``` **Important**: Channel names should be **without the @ symbol**. ### 4. Running Application The Lancelot Bot application must be running: ```bash docker compose up -d # OR docker-compose up -d ``` ## Setup Methods You can set up Telegram using either: 1. **Web UI** (Recommended) - User-friendly wizard with validation 2. **Command Line** - Traditional CLI method ## Web UI Setup (Recommended) The web-based setup wizard provides the easiest and most reliable way to authenticate Telegram. ### Step-by-Step Guide #### Step 1: Access the Setup Wizard 1. **Open your browser** to: http://localhost:8000 2. **Look for the notification banner**: - If Telegram is not configured, you'll see a yellow notification at the top - Message: "⚠️ Telegram Not Configured" 3. **Click "Setup Telegram Now"**: - This opens the setup wizard at http://localhost:8000/setup/telegram **Alternative direct access**: Navigate directly to http://localhost:8000/setup/telegram #### Step 2: Welcome Screen The wizard shows: - Overview of the setup process - Requirements checklist (phone, Telegram app access, 2FA password if enabled) - Time estimate (~2 minutes) **Actions**: - Click **"Get Started"** to begin - Or click **"Skip for Now"** if you want to set up later #### Step 3: Enter Phone Number **Form**: - Phone number field with international format validation - Example: `+15551234567` **Format Requirements**: - Must start with `+` and country code - No spaces or dashes - Valid format: `+[1-9][0-9]{1,14}` **Examples**: ``` ✅ Correct: +15551234567 ✅ Correct: +447700900123 ✅ Correct: +61412345678 ❌ Wrong: 5551234567 (missing +) ❌ Wrong: +1 555 123 4567 (spaces) ``` **Actions**: - Enter your phone number - Click **"Send Code"** - Wait for verification code to arrive in Telegram app **What happens**: - Wizard sends authentication request to Telegram - Telegram sends you a 5-6 digit code via the app - Progress advances to code verification step #### Step 4: Enter Verification Code **Form**: - Verification code field (5-6 digits) - Display shows phone number code was sent to - Resend code button (with 60-second cooldown) **Requirements**: - Code must be 5-6 digits - Only numbers allowed **Actions**: - Check your Telegram app for the verification code - Enter the code - Click **"Verify"** **Resending the code**: - If code doesn't arrive, wait 60 seconds - Click **"Resend Code"** - New code will be sent **What happens**: - Wizard verifies the code with Telegram - If you have 2FA enabled → proceeds to password step - If no 2FA → proceeds directly to success #### Step 5: Enter 2FA Password (If Enabled) **Note**: This step only appears if you have Two-Factor Authentication enabled on your Telegram account. **Form**: - Password field (masked input) - Cloud password hint **Requirements**: - This is your Telegram cloud password - Not your device passcode - Set in Telegram Settings → Privacy & Security → Two-Step Verification **Actions**: - Enter your Telegram cloud password - Click **"Verify"** **Forgot password?**: - You must reset it through Telegram app - Settings → Privacy & Security → Two-Step Verification → Forgot Password - Follow Telegram's recovery process #### Step 6: Success! **Confirmation screen shows**: - Success icon and message - List of configured channels - Note about accessing settings from dashboard **Actions**: - Click **"Continue to Dashboard"** **What was created**: - `.telethon.session` file in application directory - Session file encrypted by Telethon library - File permissions set to 600 (owner read/write only) - Session persists across container restarts ### Error Handling The web UI provides clear error messages: **Common Errors**: | Error | Cause | Solution | |-------|-------|----------| | "Invalid phone format" | Phone number doesn't match international format | Add country code with `+` prefix | | "Code must be 5-6 digits" | Invalid code format | Enter only numbers, 5-6 digits | | "Invalid verification code" | Wrong code entered | Check Telegram app, try again or resend | | "Code expired" | Code older than 10 minutes | Click "Resend Code" | | "Invalid password" | Wrong 2FA password | Check password, try again | | "Rate limit exceeded" | Too many requests | Wait 60 seconds and try again | **Global errors** appear at the top of the page and can be dismissed. **Field errors** appear below the specific input field. ## Command Line Setup If you prefer the command line or the web UI is unavailable: ### Method 1: Interactive Container Access ```bash # Ensure API credentials are in .env grep TELEGRAM_API .env # Start the application (if not already running) docker compose up -d # Watch logs to see when authentication is needed docker compose logs -f app # When you see "telethon_disabled" message, connect to container docker compose exec -it app bash # Inside container, trigger authentication # The system will prompt for phone, code, and password (if 2FA) # Follow the prompts # Exit container when complete exit ``` ### Method 2: Python Direct Execution If running outside Docker: ```bash # Activate virtual environment (if using one) source venv/bin/activate # Run the application python -m lancelot.app.api.main # Follow authentication prompts: # 1. Enter phone number (with country code) # 2. Enter verification code from Telegram # 3. Enter password (if 2FA enabled) # Press Ctrl+C to stop after authentication completes ``` ### Verification Check authentication succeeded: ```bash # Look for session file ls -la .telethon.session # Should show file with 600 permissions: # -rw------- 1 user user 8192 Oct 09 12:00 .telethon.session # Check logs for success message docker compose logs app | grep "Monitoring channels" ``` ## Troubleshooting ### Authentication Issues #### "Telegram Not Responding" **Symptoms**: - Wizard times out waiting for response - No verification code received **Solutions**: 1. **Check API credentials**: ```bash grep TELEGRAM_API .env # Verify API_ID is numeric # Verify API_HASH is 32 hex characters ``` 2. **Check internet connection**: ```bash docker compose exec app ping -c 3 telegram.org ``` 3. **Restart application**: ```bash docker compose restart app ``` #### "Invalid API Credentials" **Symptoms**: - Error about API ID or Hash being invalid - "Unauthorized" errors **Solutions**: 1. **Verify credentials at my.telegram.org/apps** 2. **Check .env file format**: ```bash # Correct format: TELEGRAM_API_ID=1234567 TELEGRAM_API_HASH=abcdef1234567890abcdef1234567890 # Wrong (no quotes needed): TELEGRAM_API_ID="1234567" TELEGRAM_API_HASH="abcdef..." ``` 3. **Recreate application** at my.telegram.org if needed #### "Session Expired" or "Unauthorized" **Symptoms**: - Previously working setup stops working - Logs show "session expired" or "unauthorized" **Solutions**: 1. **Delete old session**: ```bash docker compose exec app rm -f .telethon.session ``` 2. **Re-authenticate via web UI**: - Go to http://localhost:8000/setup/telegram - Complete wizard again 3. **Check session file permissions**: ```bash docker compose exec app ls -la .telethon.session # Should be: -rw------- (600) ``` #### "Code Not Received" **Symptoms**: - Verification code doesn't arrive in Telegram app - Waited several minutes with no code **Solutions**: 1. **Check Telegram app is running** and connected 2. **Check spam/archived chats** in Telegram 3. **Wait 60 seconds** and use "Resend Code" 4. **Try different device** for Telegram app 5. **Check phone number** is correct (with country code) #### "Invalid Verification Code" **Symptoms**: - Code entered but marked as invalid - Error: "Invalid verification code" **Solutions**: 1. **Double-check the code** in Telegram app 2. **Ensure code hasn't expired** (valid for ~10 minutes) 3. **Try resending** a new code 4. **Check for typos** (O vs 0, I vs 1) #### "Wrong 2FA Password" **Symptoms**: - Password rejected at 2FA step - Error: "Invalid password" **Solutions**: 1. **Verify it's your cloud password**, not device passcode 2. **Check password** in Telegram Settings → Privacy & Security 3. **Try password recovery** in Telegram app 4. **Disable 2FA temporarily** (in Telegram app) if desperate - Not recommended for security #### "Rate Limited" **Symptoms**: - Error: "Rate limit exceeded" - "Too many attempts" **Solutions**: 1. **Wait 60 seconds** before next attempt 2. **Don't spam** send-code or verify buttons 3. **Use web UI** which enforces rate limits properly 4. **Check logs** for rate limit timing: ```bash docker compose logs app | grep "rate_limit" ``` ### Channel Monitoring Issues #### "Not Receiving Signals" **Symptoms**: - Channels configured but no signals in logs - No messages being processed **Solutions**: 1. **Verify you're a member** of the channels: ```bash # Open Telegram and check you've joined the channels # listed in TELEGRAM_CHANNELS ``` 2. **Check channel names** are correct: ```bash grep TELEGRAM_CHANNELS .env # Should be: channel1,channel2 (no @ symbol) # Should be: channel username, not display name ``` 3. **Check authentication succeeded**: ```bash docker compose logs app | grep "Monitoring channels" # Should show list of channels being monitored ``` 4. **Test with a known-active channel**: ```bash # Temporarily add a very active public channel # to verify monitoring is working ``` #### "Channels Not Found" **Symptoms**: - Error about channel not found - "Cannot find entity" errors **Solutions**: 1. **Use channel username**, not display name: ``` ✅ Correct: cryptosignals ❌ Wrong: Crypto Signals 🚀 ``` 2. **Join the channel** with your Telegram account first 3. **For private channels**, ensure you have access 4. **Check channel username** in channel info or URL: - URL format: t.me/channelname - Use `channelname` part only ### System Issues #### "Web UI Not Accessible" **Symptoms**: - Can't open http://localhost:8000 - Connection refused **Solutions**: 1. **Check application is running**: ```bash docker compose ps app # Should show "Up" status ``` 2. **Check port mapping**: ```bash docker compose port app 8000 # Should show: 0.0.0.0:8000 ``` 3. **Check logs for errors**: ```bash docker compose logs app ``` 4. **Try different port** if 8000 is in use: ```yaml # In docker-compose.yml: ports: - "8080:8000" # Change left side only ``` #### "Static Files Not Loading" **Symptoms**: - Wizard page loads but looks broken - CSS or JavaScript not loading - Console errors in browser **Solutions**: 1. **Check static files exist**: ```bash ls -la lancelot/app/gui/static/css/telegram-setup.css ls -la lancelot/app/gui/static/js/telegram-setup.js ``` 2. **Clear browser cache**: - Hard refresh: Ctrl+Shift+R (Windows/Linux) or Cmd+Shift+R (Mac) - Or open in incognito/private mode 3. **Check FastAPI static mount**: ```bash # Verify in lancelot/app/api/main.py: # app.mount("/static", StaticFiles(directory="lancelot/app/gui/static")) ``` #### "Session File Permission Errors" **Symptoms**: - Errors about unable to read/write session file - Permission denied errors **Solutions**: 1. **Check file ownership**: ```bash docker compose exec app ls -la .telethon.session ``` 2. **Fix permissions**: ```bash docker compose exec app chmod 600 .telethon.session ``` 3. **Recreate session**: ```bash docker compose exec app rm -f .telethon.session # Then re-authenticate via web UI ``` ## FAQ ### General Questions **Q: Do I need to authenticate every time I restart the container?** A: No. Authentication happens once. The `.telethon.session` file persists across restarts. You only need to re-authenticate if: - Session file is deleted - Session expires (rare, usually after months) - You change Telegram account - Telegram detects suspicious activity **Q: Is my Telegram password stored anywhere?** A: No. Passwords are only used during authentication and never stored. The session file contains encrypted authentication tokens, not your password. **Q: Can I monitor channels I'm not a member of?** A: No. You must be a member of each channel with your Telegram account. Join the channels first, then configure monitoring. **Q: How many channels can I monitor?** A: Technically unlimited, but practical limits: - Telegram rate limits apply - More channels = more processing - Recommend starting with 3-5 quality channels - Monitor performance and add more if needed **Q: What happens if I get rate limited by Telegram?** A: The system handles rate limits gracefully: - Logs warnings about rate limits - Automatically waits before retrying - No crashes or data loss - Monitoring resumes when rate limit expires **Q: Can I use this for my Telegram bot?** A: No. This uses a *user account*, not a bot account. For bot functionality, you need a bot token from @BotFather (different setup). ### Security Questions **Q: Is it safe to give my Telegram API credentials?** A: Your API credentials stay on your server only. They're not sent to any third-party services. The credentials are: - Used only to authenticate with Telegram directly - Stored in your `.env` file (never commit to git) - Used by the Telethon library (official Telegram client library) **Q: What data does the bot have access to?** A: The bot can: - ✅ Read messages from channels you've joined - ✅ Read your contact list (not stored or used) - ❌ Cannot send messages without modification - ❌ Cannot access private messages unless configured - ❌ Cannot modify your account settings **Q: Can other people see the bot is monitoring channels?** A: No. You appear as a normal user in channels. There's no indication you're using automation. **Q: Should I enable 2FA?** A: Yes! 2FA (Two-Factor Authentication) adds security: - Protects against unauthorized access - The wizard handles 2FA automatically - Slightly longer setup but worth it for security **Q: What if someone gets access to my session file?** A: Session files are sensitive. If compromised: 1. Delete the session file immediately 2. Re-authenticate to create a new session 3. Check your Telegram "Active Sessions" in app 4. Terminate suspicious sessions 5. Enable 2FA if not already enabled 6. Change Telegram password **Best practice**: Set session file permissions to 600 (owner read/write only). ### Technical Questions **Q: Which Telegram API library is used?** A: Telethon - the official async Python library for Telegram. It's: - Maintained by Telegram - Battle-tested and reliable - Supports all Telegram features - Well-documented and actively developed **Q: Where is the session file stored?** A: In the application root directory as `.telethon.session`. In Docker: ``` Location: /app/.telethon.session (inside container) Permissions: 600 (owner read/write only) Size: ~8KB Format: Binary, encrypted by Telethon ``` **Q: Can I copy the session file to another server?** A: Yes, but not recommended. If you must: 1. Stop both applications 2. Copy `.telethon.session` file 3. Set permissions to 600 on destination 4. Ensure API_ID and API_HASH match 5. Start application Better: Re-authenticate on the new server using the wizard. **Q: How does the web UI communicate with the backend?** A: Via REST API: - `/api/telegram/setup/status` - Check setup status - `/api/telegram/setup/send-code` - Send verification code - `/api/telegram/setup/verify-code` - Verify code - `/api/telegram/setup/verify-password` - Verify 2FA password - `/api/telegram/setup/skip` - Skip setup All endpoints use JSON and are rate-limited for security. **Q: Can I automate the setup?** A: Partially. You can pre-configure API credentials in `.env`, but phone verification requires user interaction (by design, for security). **Q: What happens during container restart?** A: If session file exists: - Application starts normally - Automatically reconnects to Telegram - Resumes channel monitoring - No user interaction needed If session file missing: - Application starts without Telegram - Logs message: "Complete Telegram setup via web UI" - System works but Telegram monitoring disabled - Set up via web UI when ready ## Security Best Practices ### Protecting Your Session 1. **Never commit session files to git**: ```bash # Add to .gitignore: .telethon.session *.session ``` 2. **Set proper file permissions**: ```bash chmod 600 .telethon.session ``` 3. **Regularly monitor active sessions**: - Open Telegram app - Settings → Privacy & Security → Active Sessions - Review and terminate unknown sessions 4. **Use 2FA**: - Telegram Settings → Privacy & Security → Two-Step Verification - Set a strong, unique password - Add recovery email 5. **Separate accounts** (optional): - Consider using a separate Telegram account for bot activity - Keeps personal and trading accounts isolated - Reduces risk if session is compromised ### API Credentials 1. **Keep API credentials secret**: - Never share API_ID or API_HASH publicly - Don't commit `.env` file to git - Use environment variables in production 2. **Rotate credentials periodically**: - Delete old applications at my.telegram.org - Create new ones every few months - Update `.env` and re-authenticate 3. **Revoke access if compromised**: - Go to my.telegram.org/apps - Delete the compromised application - Create new application with new credentials - Re-authenticate bot ### Channel Safety 1. **Vet channels before monitoring**: - Research channel history - Check for scam warnings - Test in shadow mode first - Monitor for 48+ hours before trusting signals 2. **Limit channel access**: - Only join channels you trust - Remove bot from unused channels - Regularly review channel list 3. **Never share private keys**: - Channels requesting private keys are scams - No legitimate channel needs your wallet seed - Be extremely cautious of "verification" requests ### Operational Security 1. **Use shadow mode for testing**: ```bash MODE=shadow # In .env ``` 2. **Monitor bot activity**: ```bash docker compose logs -f app | grep telegram ``` 3. **Regular security audits**: - Review active Telegram sessions weekly - Check bot logs for anomalies - Verify channel list is current - Update dependencies regularly 4. **Backup strategy**: - Back up configuration (`.env`) - Document API credentials securely (password manager) - Don't backup session files (re-authenticate instead) ## Additional Resources - **Telegram API Documentation**: https://core.telegram.org/ - **Telethon Documentation**: https://docs.telethon.dev/ - **Lancelot Bot Docs**: [docs/usage/](../usage/) - **Quick Start Guide**: [docs/usage/QUICKSTART.md](../usage/QUICKSTART.md) - **Troubleshooting**: [docs/usage/08-troubleshooting.md](../usage/08-troubleshooting.md) ## Support If you encounter issues not covered in this guide: 1. **Check application logs**: ```bash docker compose logs app ``` 2. **Search existing issues** in the repository 3. **Create a new issue** with: - Description of the problem - Steps to reproduce - Relevant log excerpts (redact sensitive info) - System information (OS, Docker version) --- **Remember**: Your Telegram credentials and session file are sensitive. Treat them with the same care as passwords or private keys. When in doubt, re-authenticate rather than troubleshooting session issues.