Telegram bot API

Introduction#

This page provides detailed documentation for the Telegram Bot API endpoints and command handlers. It covers user commands (/start, /stop, /status, /stats, /web), admin commands (/users, /boo, /fu, /logs), dual-mode operation (long-polling and webhook), command routing, user session management, subscription handling, MongoDB integration, and the message formatting system. Practical examples, error handling, and troubleshooting guidance are included.

Project structure#

The project is organized around a modular architecture with clear separation of concerns:

  • CLI entry point orchestrating servers and jobs
  • Telegram bot server with command handlers
  • Webhook/FastAPI server exposing REST endpoints
  • Services for database, notifications, formatting, and administration
  • Configuration and database client modules

Core components#

  • BotServer: Implements long-polling Telegram bot with command handlers for user and admin commands.
  • WebhookServer: FastAPI-based server exposing health, push subscription, notification, and stats endpoints.
  • DatabaseService: Wraps MongoDB operations for notices, jobs, placement offers, users, and policies.
  • TelegramService: Handles Telegram messaging, formatting, and broadcasting.
  • NotificationService: Routes notifications to configured channels and manages unsent notices.
  • AdminTelegramService: Provides admin-only commands with authentication via chat ID.
  • Configuration and DB Client: Centralized settings and MongoDB connectivity.

Architecture overview#

The system supports two operational modes:

  • Long-polling Telegram bot server (BotServer) with command handlers.
  • Webhook/FastAPI server (WebhookServer) with REST endpoints for health, push subscriptions, notifications, and stats.

Detailed component analysis#

Telegram bot commands#

/start#

  • Purpose: Register user for notifications.
  • Request: /start
  • Response: Welcome message with available commands and links.
  • Database actions:
    • Insert or update user record in Users collection.
    • Set active subscription and timestamps.

/stop#

  • Purpose: Unsubscribe user from notifications.
  • Request: /stop
  • Response: Confirmation or inactive message.
  • Database actions:
    • Deactivate user subscription.

/status#

  • Purpose: Check subscription status.
  • Request: /status
  • Response: Active/inactive status with registration date and user ID.
  • Database actions:
    • Retrieve user by ID.

/stats#

  • Purpose: View placement statistics.
  • Request: /stats
  • Response: Formatted statistics including overall placement percentage, packages, and branch-wise stats.
  • Database actions:
    • Compute and return placement statistics.

/web#

  • Purpose: Get useful links to JIIT tools.
  • Request: /web
  • Response: HTML-formatted links.

Admin commands#

Authentication and permission checks#

  • Admin commands are restricted to a specific chat ID configured in settings.
  • The AdminTelegramService validates the sender’s chat ID against the configured admin chat ID.

/users#

  • Purpose: List all users and subscription stats.
  • Request: /users
  • Response: User list with status and counts.

/boo #

  • Purpose: Broadcast message to all active users or targeted user.
  • Request: /boo broadcast or /boo <chat_id>
  • Response: Broadcast result summary.

/fu and /scrapyyy#

  • Purpose: Force immediate update from all sources and broadcast.
  • Request: /fu or /scrapyyy
  • Response: Progress and results summary.

/logs [lines]#

  • Purpose: View recent log entries.
  • Request: /logs [lines]
  • Response: Log content (HTML escaped and truncated if needed).

Dual-Mode operation: long-polling and webhook#

  • Long-polling mode: BotServer initializes and runs an asynchronous polling loop.
  • Webhook mode: WebhookServer exposes endpoints for health, push subscriptions, notifications, and stats.

Command routing mechanism#

  • BotServer registers command handlers for user and admin commands.
  • Admin commands are conditionally registered when AdminTelegramService is available.

User session management and subscription handling#

  • User registration and deactivation handled by DatabaseService.
  • Active user retrieval for broadcasting.

MongoDB integration#

  • DBClient establishes and manages MongoDB connections.
  • DatabaseService encapsulates CRUD operations across collections: Notices, Jobs, PlacementOffers, Users, Policies, OfficialPlacementData.

Message formatting system#

  • TelegramService converts Markdown to HTML/Telegram-compatible formats and handles long message splitting.
  • NoticeFormatterService formats notices using LLM-based extraction and structured templates.

Dependency analysis#

The system exhibits strong dependency injection and separation of concerns:

  • BotServer depends on DatabaseService, NotificationService, TelegramService, AdminTelegramService, and PlacementStatsCalculatorService.
  • WebhookServer depends on DatabaseService, NotificationService, and TelegramService.
  • DatabaseService depends on DBClient.
  • Configuration is centralized via Settings with caching.

Performance considerations#

  • Message chunking: TelegramService splits long messages (>4000 chars) and retries without formatting if needed.
  • Rate limiting: Broadcast loops include small delays to avoid rate limits.
  • Asynchronous polling: BotServer uses asyncio for non-blocking operations.
  • Database indexing: Recommended indexes on frequently queried fields (e.g., notices.id, users.user_id, placement_offers.company).

Troubleshooting guide#

Common issues and resolutions:

  • Telegram bot token missing or invalid: Ensure TELEGRAM_BOT_TOKEN is set and valid.
  • Admin command unauthorized: Verify TELEGRAM_CHAT_ID matches the admin chat ID.
  • MongoDB connection failures: Check MONGO_CONNECTION_STR and network/firewall settings.
  • Long message delivery failures: Messages are split automatically; if formatting fails, fallback to plain text.
  • Webhook endpoint not reachable: Confirm server is running and port is open.

Conclusion#

The Telegram Bot API provides reliable user and admin command handling with dual-mode operation, detailed MongoDB integration, and a flexible notification routing system. The documented endpoints, commands, and workflows enable reliable deployment and maintenance of placement notifications across Telegram and web push channels.

Appendices#

API endpoints summary#

  • GET /health: Health check
  • POST /api/push/subscribe: Subscribe to web push
  • POST /api/push/unsubscribe: Unsubscribe from web push
  • GET /api/push/vapid-key: Get VAPID public key
  • POST /api/notify: Send notification to specified channels
  • POST /api/notify/telegram: Send Telegram-only notification
  • POST /api/notify/web-push: Send Web Push-only notification
  • GET /api/stats: Get all statistics
  • GET /api/stats/placements: Get placement statistics
  • GET /api/stats/notices: Get notice statistics
  • GET /api/stats/users: Get user statistics
  • POST /webhook/update: Trigger update job via webhook

Configuration reference#

Key environment variables:

  • MONGO_CONNECTION_STR: MongoDB connection URI
  • TELEGRAM_BOT_TOKEN: Telegram bot token
  • TELEGRAM_CHAT_ID: Default chat/channel ID
  • SUPERSET_CREDENTIALS: JSON array of SuperSet credentials
  • GOOGLE_API_KEY: Gemini LLM API key
  • VAPID_PRIVATE_KEY, VAPID_PUBLIC_KEY, VAPID_EMAIL: Web push VAPID keys
  • WEBHOOK_PORT, WEBHOOK_HOST: Webhook server configuration
  • LOG_LEVEL, LOG_FILE: Logging configuration