Skip to content

Telegram Bot Integration — per-agent bots with media, public link sharing #216

Closed

Description

@vybe

Summary

Each Trinity agent can have its own Telegram bot (1:1 mapping), configurable per agent. Users chat with agents via Telegram — text, photos, documents, and voice messages (transcribed to text). Agents are shareable via t.me/BotUsername links.

Motivation

  • Reach: Telegram has 900M+ users — largest messaging platform without corporate gatekeeping
  • Media-rich: Native support for images, voice messages, documents — enables multimodal agent interactions
  • Public sharing: Telegram bot links (t.me/YourBotName) are the simplest "share an agent" UX — no auth walls, no workspace invites
  • Parity with Slack: Slack integration (SLACK-001/002) already exists via the ChannelAdapter pattern — Telegram should follow the same architecture

Architecture Decision: Prove the Channel Abstraction

The ChannelAdapter and ChannelTransport abstractions exist but have never been tested with a second implementation. The ChannelMessageRouter has 6 Slack-specific hardcodings that must be generalized first. This issue is scoped as two phases of work:

  1. Phase 0: Generalize the router (prerequisite — ~20 lines changed in existing files)
  2. Phase 1: Add Telegram as a clean, separate module (all new files)

Prerequisites: Router Generalization (Phase 0)

The ChannelMessageRouter currently has these Slack-specific references that must be made channel-agnostic:

Location Hardcoded Fix
message_router.py:123 rate_key = f"slack:{team_id}:{sender_id}" Call adapter.get_rate_key(message)
message_router.py:161 session type = "slack" Call adapter.channel_type
message_router.py:175 source_email = f"slack:{team_id}:{sender_id}" Call adapter.get_source_identifier(message)
message_router.py:189 triggered_by="slack" Use adapter.channel_type
message_router.py:257-261 get_bot_token(team_id) Call adapter.get_bot_token(message)
message_router.py:263-267 _build_session_identifier uses team_id Call adapter.get_session_identifier(message)

Changes to adapters/base.py — add to ChannelAdapter:

  • channel_type property (returns "slack", "telegram", etc.)
  • get_rate_key(message) -> str
  • get_session_identifier(message) -> str
  • get_source_identifier(message) -> str
  • get_bot_token(message) -> Optional[str]

SlackAdapter overrides these to return current behavior — zero behavior change for existing Slack users.

Also fix: router passes agent_name as link_id to get_or_create_public_chat_session — create synthetic link IDs for channel sessions (e.g., telegram:{agent_name}).

Implementation: Telegram Module (Phase 1)

One Bot Per Agent (1:1)

  • Agent owner configures a Telegram bot token via Settings UI (stored encrypted via AES-256-GCM, same as Slack)
  • Backend stores binding in telegram_bindings table: {agent_name, bot_token_encrypted, bot_username, bot_id, webhook_secret, last_update_id}
  • One bot per agent, configurable per agent
  • Bot token stored encrypted in DB AND injected into agent .env via CRED-002

Transport: Webhook + Polling

  • Webhook mode (default): Telegram sends updates to POST /api/telegram/webhook/{webhook_secret} on the same public URL used for public links
    • Returns 200 immediately, processes via asyncio.create_task (same pattern as Slack webhook)
    • Validates X-Telegram-Bot-Api-Secret-Token header (set via setWebhook API secret_token param) — URL secret for routing, header for auth
    • Auto-registers webhook URL when bot token is configured
  • Polling mode (dev fallback): Long-polling via background task when no public URL available
    • Track update_id offset per bot in telegram_bindings.last_update_id for deduplication
    • Semaphore per bot (max 3 in-flight tasks)
    • Exponential backoff on errors (invalid token, network)
    • Graceful shutdown: cancel polling loops, drain in-flight with timeout

TelegramAdapter (extends ChannelAdapter)

class TelegramAdapter(ChannelAdapter):
    channel_type = "telegram"

    def parse_message(self, raw_event: dict) -> Optional[NormalizedMessage]:
        # Extract text, media, sender info from Telegram Update
        # Map: user_id → sender_id, chat_id → channel_id, reply_to → thread_id
        # Handle /start, /help, /reset commands
        # Return None for bot messages, unsupported types

    async def send_response(self, channel_id, response, thread_id=None):
        # telegram.sendMessage() with parse_mode=HTML
        # Split long responses at 4096 char limit (paragraph boundaries)
        # Support reply_to_message_id for thread continuity

    async def get_agent_name(self, message) -> Optional[str]:
        # Lookup bot_id in telegram_bindings → agent_name

    async def indicate_processing(self, message):
        # telegram.sendChatAction("typing")

    def get_rate_key(self, message) -> str:
        # f"telegram:{bot_id}:{sender_id}"

    def get_session_identifier(self, message) -> str:
        # f"{bot_id}:{sender_id}:{chat_id}"

    def get_source_identifier(self, message) -> str:
        # f"telegram:{bot_id}:{sender_id}"

    def get_bot_token(self, message) -> Optional[str]:
        # Lookup from telegram_bindings by bot_id (encrypted, cached)

Response Formatting

  • Use parse_mode=HTML (NOT MarkdownV2 — MarkdownV2 requires escaping .()-!>#+={} which breaks on typical LLM output)
  • Convert agent Markdown to Telegram HTML (**bold** → <b>bold</b>, etc.)
  • Plain text fallback if conversion fails (never drop a response due to formatting)

Media Processing

Telegram Type Processing Agent Receives
Photo Download via getFile API Image passed to multimodal model
Document Download + extract text (PDF, TXT) Text content in message
Voice/Audio Download + transcribe via API (e.g., OpenAI Whisper API) Transcribed text
Video Download thumbnail + metadata Description text
Sticker Map to emoji/description Text description
Location Extract lat/lng Structured location data

File handling:

  • Download only from api.telegram.org domain (SSRF prevention)
  • Temp file cleanup after processing (including on error paths)
  • Respect Telegram's 20MB download / 50MB upload limits

Voice transcription: Use external API (OpenAI Whisper API or similar) — no local model needed. Simple: download OGG → send to transcription API → return text.

Session Persistence

  • Reuse public_chat_sessions with identifier_type = 'telegram'
  • Session keyed by {bot_id}:{telegram_user_id}:{chat_id}
  • Conversation history maintained per user

Bot Commands

Command Action
/start Welcome message + agent introduction
/help List capabilities
/reset Clear conversation history

Database Schema

CREATE TABLE telegram_bindings (
    id INTEGER PRIMARY KEY,
    agent_name TEXT NOT NULL UNIQUE,
    bot_token_encrypted TEXT NOT NULL,
    bot_username TEXT,
    bot_id TEXT,
    webhook_secret TEXT NOT NULL,
    webhook_url TEXT,
    telegram_secret_token TEXT,          -- For X-Telegram-Bot-Api-Secret-Token validation
    polling_enabled BOOLEAN DEFAULT FALSE,
    last_update_id INTEGER DEFAULT 0,    -- For dedup on retries/restarts
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP
);

CREATE TABLE telegram_chat_links (
    id INTEGER PRIMARY KEY,
    binding_id INTEGER REFERENCES telegram_bindings(id),
    telegram_user_id TEXT NOT NULL,
    telegram_username TEXT,
    session_id TEXT,
    message_count INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_active TIMESTAMP
);

New Files

src/backend/
├── adapters/
│   ├── telegram_adapter.py           # TelegramAdapter (extends ChannelAdapter)
│   └── transports/
│       ├── telegram_webhook.py       # Webhook receiver (returns 200 immediately)
│       └── telegram_polling.py       # Long-polling fallback (dev mode)
├── routers/
│   └── telegram.py                   # API endpoints
├── services/
│   └── telegram_media.py             # Media download + processing + voice transcription
└── db/
    └── telegram_channels.py          # TelegramChannelOperations (encrypted tokens, bindings)

Files Modified (minimal)

src/backend/
├── adapters/
│   ├── base.py                       # Add channel_type, get_rate_key, get_session_identifier, get_source_identifier, get_bot_token
│   ├── message_router.py             # Replace 6 Slack-specific refs with adapter method calls
│   └── slack_adapter.py              # Add overrides for new base methods (backward-compatible)
└── main.py                           # Add Telegram startup block + include_router

API Endpoints

Method Path Auth Purpose
POST /api/telegram/webhook/{secret} X-Telegram-Bot-Api-Secret-Token header Receive Telegram updates
GET /api/agents/{name}/telegram JWT Get bot binding status
PUT /api/agents/{name}/telegram JWT (owner) Configure bot token
DELETE /api/agents/{name}/telegram JWT (owner) Remove bot binding
POST /api/agents/{name}/telegram/test JWT (owner) Send test message

Security

  • Bot tokens: AES-256-GCM encrypted in DB (same CredentialEncryptionService as Slack)
  • Webhook auth: X-Telegram-Bot-Api-Secret-Token header validation (set via Telegram setWebhook API)
  • Webhook URL secret: Random 256-bit token for URL routing
  • SSRF prevention: Media downloads only from api.telegram.org
  • Tool restriction: Telegram users get restricted tools only (WebSearch, WebFetch — same as Slack)
  • No credential exposure: Bot token values never logged
  • Update dedup: last_update_id tracking prevents duplicate processing on retries

Implementation Dependencies

  • No new Python packages: Use httpx (already in codebase) for all Telegram Bot API calls
  • Existing: ChannelAdapter, ChannelTransport, ChannelMessageRouter, CRED-002, public_chat_sessions, TaskExecutionService
  • External API: Telegram Bot API (HTTPS), optional Whisper API for voice transcription

Acceptance Criteria

  • Router generalized: ChannelMessageRouter uses adapter methods, not Slack-specific hardcoding
  • SlackAdapter backward-compatible: all existing Slack functionality unchanged
  • Agent owner can configure a Telegram bot token via UI
  • Bot token validated via getMe API on configuration
  • Messages sent to the bot are processed by the correct agent
  • Agent responses sent back to Telegram chat (HTML formatted)
  • Long responses split at 4096 char boundaries
  • Conversation history persists per Telegram user
  • Photos downloaded and passed to agent
  • Documents downloaded and text extracted
  • Voice messages transcribed to text and passed to agent
  • Rate limiting prevents abuse (per bot_id:user_id)
  • Webhook mode: returns 200 immediately, processes async
  • Webhook auth: validates X-Telegram-Bot-Api-Secret-Token header
  • Polling mode works for local development
  • Update deduplication via last_update_id tracking
  • Bot link (t.me/BotUsername) displayed in agent settings
  • /start, /help, /reset commands work
  • No new Python dependencies (httpx only)

Out of Scope (Deferred)

  • Deep links with start parameters (t.me/Bot?start=ref_campaign1) → Phase 2
  • Email linking for per-user memory (MEM-001) → Phase 2
  • Inline keyboards / interactive buttons → Phase 2
  • Multi-bot-per-agent → Not planned
  • Single Trinity bot with command routing → Rejected (1:1 is cleaner)

References

  • Existing Slack adapter: src/backend/adapters/slack_adapter.py
  • Channel adapter base: src/backend/adapters/base.py
  • Message router: src/backend/adapters/message_router.py
  • Transport base: src/backend/adapters/transports/base.py
  • Slack DB operations: src/backend/db/slack_channels.py
  • Telegram Bot API docs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementpriority-p2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions