PYTHON 3.9+ • FLASK • BOT AUTOMATION
Telegram Story Downloader Bot
A resilient Python automation service enabling Telegram users to search, view, and download active public stories via direct messages or global inline search mode.
1. The Problem: Disappearing Ephemeral Media
Telegram Stories provide a vibrant way for channels and individuals to share quick 24-hour video and photo updates. However, the standard Telegram client does not provide a native one-click save button for public stories. Users who wish to archive useful design tutorials, announcements, or community media were forced to use screen recording software, resulting in degraded quality and cumbersome manual cropping.
2. Architecture & Execution Pipeline
The bot is built to handle concurrent user requests efficiently while respecting Telegram's strict API rate quotas:
Request Pipeline:
User Query (@username) → Force-Join Validation (Cached) → HTTP Pooled API Call → Media Extraction → Inline / Chat Delivery
Key Architectural Features:
- Dual Deployment Modes: Supports lightweight production serving via a Flask WSGI webhook server, alongside zero-configuration long-polling for local testing.
- HTTP Connection Pooling: Utilizes a shared
requests.Session()pool with customized retry adapters, eliminating socket creation overhead on repetitive API handshakes. - Inline Search Mode: Users can invoke the bot in any personal or group chat by typing
@BotUsername username, allowing quick story previewing without opening a direct bot chat. - Atomic State Persistence: Employs atomic file replacement patterns when persisting subscriber statistics into
users.json, preventing file corruption on sudden process terminations. - Structured Logging with Loguru: Detailed color-coded observability capturing error traces and admin notifications in real time.
3. Technical Challenges & Solutions
Challenge A: Telegram API Rate Limits & Chat Membership Verification
Checking if a user has joined the prerequisite channel before processing a story query requires calling get_chat_member on every single message, which rapidly triggers Telegram 429 Too Many Requests errors.
Solution:
Implemented an in-memory TTL (Time-To-Live) cache for channel membership verifications. Once a user's membership is confirmed, their verification status is cached for 10 minutes, eliminating redundant API round-trips by over 90%.
Challenge B: Safe High-Concurrency User Tracking
Appending user IDs directly to a flat JSON file under high traffic can cause race conditions and corrupted JSON syntax.
Solution:
Wrote a thread-safe atomic write routine: serialized JSON is written to a temporary file (.users.json.tmp) and atomically renamed using OS-level os.replace(), guaranteeing zero half-written files.
4. Results & Code Quality
The project is actively maintained on GitHub at tegegndev/telegram-story-downloader, demonstrating practical backend engineering, network resilience, and modular Python system design.