Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(telegram): add button-first bot integration

cyh211cb4c6c2bb
diff --git a/config/discovered_chats.py b/config/discovered_chats.py
new file mode 100644
index 000000000..dd39a5ce4
--- /dev/null
+++ b/config/discovered_chats.py
@@ -0,0 +1,177 @@
+from __future__ import annotations
+
+import json
+import logging
+import threading
+from dataclasses import asdict, dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Dict, Optional
+
+from config import paths
+
+logger = logging.getLogger(__name__)
+
+SCHEMA_VERSION = 1
+
+
+def _now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+@dataclass
+class DiscoveredChat:
+ chat_id: str
+ platform: str
+ name: str = ""
+ username: str = ""
+ chat_type: str = ""
+ is_private: bool = False
+ is_forum: bool = False
+ supports_topics: bool = False
+ last_seen_at: str = ""
+
+
+@dataclass
+class DiscoveredChatsState:
+ chats: Dict[str, Dict[str, DiscoveredChat]] = field(default_factory=dict)
+
+
+class DiscoveredChatsStore:
+ _instance: Optional["DiscoveredChatsStore"] = None
+ _instance_lock = threading.Lock()
+
+ @classmethod
+ def get_instance(cls, storage_path: Optional[Path] = None) -> "DiscoveredChatsStore":
+ with cls._instance_lock:
+ if cls._instance is None:
+ cls._instance = cls(storage_path)
+ else:
+ cls._instance.maybe_reload()
+ return cls._instance
+
+ @classmethod
+ def reset_instance(cls) -> None:
+ with cls._instance_lock:
+ cls._instance = None
+
+ def __init__(self, storage_path: Optional[Path] = None):
+ self.storage_path = storage_path or paths.get_discovered_chats_path()
+ self.state = DiscoveredChatsState()
+ self._file_mtime: float = 0
+ self._lock = threading.Lock()
+ self._load()
+
+ def maybe_reload(self) -> None:
+ try:
+ mtime = self.storage_path.stat().st_mtime
+ if mtime > self._file_mtime:
+ self._load()
+ except FileNotFoundError:
+ pass
+
+ def _load(self) -> None:
+ if not self.storage_path.exists():
+ return
+ try:
+ payload = json.loads(self.storage_path.read_text(encoding="utf-8"))
+ except Exception as exc:
+ logger.error("Failed to load discovered chats: %s", exc)
+ return
+ if not isinstance(payload, dict):
+ logger.error("Failed to load discovered chats: invalid format")
+ return
+
+ platforms: Dict[str, Dict[str, DiscoveredChat]] = {}
+ raw_platforms = payload.get("platforms") or {}
+ if isinstance(raw_platforms, dict):
+ for platform, chats in raw_platforms.items():
+ if not isinstance(chats, dict):
+ continue
+ platform_chats: Dict[str, DiscoveredChat] = {}
+ for chat_id, chat_payload in chats.items():
+ if not isinstance(chat_payload, dict):
+ continue
+ platform_chats[str(chat_id)] = DiscoveredChat(
+ chat_id=str(chat_id),
+ platform=str(platform),
+ name=chat_payload.get("name", ""),
+ username=chat_payload.get("username", ""),
+ chat_type=chat_payload.get("chat_type", ""),
+ is_private=bool(chat_payload.get("is_private", False)),
+ is_forum=bool(chat_payload.get("is_forum", False)),
+ supports_topics=bool(chat_payload.get("supports_topics", False)),
+ last_seen_at=chat_payload.get("last_seen_at", ""),
+ )
+ platforms[str(platform)] = platform_chats
+
+ self.state = DiscoveredChatsState(chats=platforms)
+ try:
+ self._file_mtime = self.storage_path.stat().st_mtime
+ except FileNotFoundError:
+ self._file_mtime = 0
+
+ def save(self) -> None:
+ paths.ensure_data_dirs()
+ payload = {
+ "schema_version": SCHEMA_VERSION,
+ "platforms": {
+ platform: {chat_id: asdict(chat) for chat_id, chat in chats.items()}
+ for platform, chats in self.state.chats.items()
+ },
+ }
+ self.storage_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+ try:
+ self._file_mtime = self.storage_path.stat().st_mtime
+ except FileNotFoundError:
+ self._file_mtime = 0
+
+ def remember_chat(
+ self,
+ *,
+ platform: str,
+ chat_id: str,
+ name: str = "",
+ username: str = "",
+ chat_type: str = "",
+ is_private: bool = False,
+ is_forum: bool = False,
+ supports_topics: bool = False,
+ ) -> DiscoveredChat:
+ platform_key = str(platform)
+ chat_key = str(chat_id)
+ with self._lock:
+ self.maybe_reload()
+ platform_chats = self.state.chats.setdefault(platform_key, {})
+ existing = platform_chats.get(chat_key)
+ if existing is None:
+ existing = DiscoveredChat(chat_id=chat_key, platform=platform_key)
+ platform_chats[chat_key] = existing
+
+ if name:
+ existing.name = name
+ if username:
+ existing.username = username
+ if chat_type:
+ existing.chat_type = chat_type
+ existing.is_private = existing.is_private or is_private
+ existing.is_forum = existing.is_forum or is_forum
+ existing.supports_topics = existing.supports_topics or supports_topics
+ existing.last_seen_at = _now_iso()
+ self.save()
+ return existing
+
+ def list_chats(self, platform: str, *, include_private: bool = True) -> list[DiscoveredChat]:
+ self.maybe_reload()
+ chats = list(self.state.chats.get(str(platform), {}).values())
+ if not include_private:
+ chats = [chat for chat in chats if not chat.is_private]
+ chats.sort(
+ key=lambda chat: (
+ chat.last_seen_at or "",
+ chat.name.lower() if chat.name else "",
+ chat.chat_id,
+ ),
+ reverse=True,
+ )
+ return chats
diff --git a/config/paths.py b/config/paths.py
index 90dd3ab33..0069ac95a 100644
--- a/config/paths.py
+++ b/config/paths.py
@@ -57,6 +57,10 @@ def get_sessions_path() -> Path:
return get_state_dir() / "sessions.json"
+def get_discovered_chats_path() -> Path:
+ return get_state_dir() / "discovered_chats.json"
+
+
def ensure_data_dirs() -> None:
get_config_dir().mkdir(parents=True, exist_ok=True)
get_state_dir().mkdir(parents=True, exist_ok=True)
diff --git a/config/v2_compat.py b/config/v2_compat.py
index 0f4ae43a5..8b92af2e6 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass, field
from typing import Optional
-from config.v2_config import V2Config, SlackConfig, DiscordConfig, LarkConfig, WeChatConfig
+from config.v2_config import V2Config, SlackConfig, DiscordConfig, TelegramConfig, LarkConfig, WeChatConfig
@dataclass
@@ -44,6 +44,7 @@ class AppCompatConfig:
language: str
platforms: dict = field(default_factory=lambda: {"enabled": ["slack"], "primary": "slack"})
discord: Optional[DiscordConfig] = None
+ telegram: Optional[TelegramConfig] = None
lark: Optional[LarkConfig] = None
wechat: Optional[WeChatConfig] = None
codex: Optional[CodexCompatConfig] = None
@@ -92,6 +93,7 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:
},
slack=slack,
discord=v2.discord,
+ telegram=v2.telegram,
lark=v2.lark,
wechat=v2.wechat,
claude=claude,
diff --git a/config/v2_config.py b/config/v2_config.py
index b923a94e2..a69eb27d9 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -54,6 +54,23 @@ class DiscordConfig(BaseIMConfig):
raise ValueError("Invalid Discord bot token format")
+@dataclass
+class TelegramConfig(BaseIMConfig):
+ bot_token: str = ""
+ require_mention: bool = True
+ forum_auto_topic: bool = True
+ use_webhook: bool = False
+ webhook_url: Optional[str] = None
+ webhook_secret_token: Optional[str] = None
+ allowed_chat_ids: Optional[List[str]] = None
+ allowed_user_ids: Optional[List[str]] = None
+
+ def validate(self) -> None:
+ # Allow empty token for initial setup
+ if self.bot_token and ":" not in self.bot_token:
+ raise ValueError("Invalid Telegram bot token format")
+
+
@dataclass
class LarkConfig(BaseIMConfig):
app_id: str = ""
@@ -162,7 +179,7 @@ class PlatformsConfig:
primary: str = "slack"
def validate(self) -> None:
- supported = {"slack", "discord", "lark", "wechat"}
+ supported = {"slack", "discord", "telegram", "lark", "wechat"}
normalized: list[str] = []
for platform in self.enabled:
if platform not in supported:
@@ -172,7 +189,7 @@ class PlatformsConfig:
if not normalized:
raise ValueError("Config 'platforms.enabled' must contain at least one platform")
if self.primary not in supported:
- raise ValueError("Config 'platforms.primary' must be 'slack', 'discord', 'lark', or 'wechat'")
+ raise ValueError("Config 'platforms.primary' must be 'slack', 'discord', 'telegram', 'lark', or 'wechat'")
if self.primary not in normalized:
normalized.insert(0, self.primary)
self.enabled = normalized
@@ -188,6 +205,7 @@ class V2Config:
platform: str = "slack"
platforms: PlatformsConfig = field(default_factory=PlatformsConfig)
discord: Optional[DiscordConfig] = None
+ telegram: Optional[TelegramConfig] = None
lark: Optional[LarkConfig] = None
wechat: Optional[WeChatConfig] = None
gateway: Optional[GatewayConfig] = None
@@ -219,8 +237,8 @@ class V2Config:
raise ValueError("Config 'mode' must be 'self_host' or 'saas'")
platform = payload.get("platform") or "slack"
- if platform not in {"slack", "discord", "lark", "wechat"}:
- raise ValueError("Config 'platform' must be 'slack', 'discord', 'lark', or 'wechat'")
+ if platform not in {"slack", "discord", "telegram", "lark", "wechat"}:
+ raise ValueError("Config 'platform' must be 'slack', 'discord', 'telegram', 'lark', or 'wechat'")
platforms_payload = payload.get("platforms")
if platforms_payload is not None and not isinstance(platforms_payload, dict):
@@ -260,6 +278,14 @@ class V2Config:
discord = DiscordConfig(**_filter_dataclass_fields(DiscordConfig, discord_payload))
discord.validate()
+ telegram_payload = payload.get("telegram")
+ if telegram_payload is not None and not isinstance(telegram_payload, dict):
+ raise ValueError("Config 'telegram' must be an object")
+ telegram = None
+ if telegram_payload is not None:
+ telegram = TelegramConfig(**_filter_dataclass_fields(TelegramConfig, telegram_payload))
+ telegram.validate()
+
lark_payload = payload.get("lark")
if lark_payload is not None and not isinstance(lark_payload, dict):
raise ValueError("Config 'lark' must be an object")
@@ -284,6 +310,8 @@ class V2Config:
for _ep in platforms.enabled:
if _ep == "discord" and discord is None:
raise ValueError("Config 'discord' must be provided when discord is enabled")
+ if _ep == "telegram" and telegram is None:
+ raise ValueError("Config 'telegram' must be provided when telegram is enabled")
if _ep == "lark" and lark is None:
raise ValueError("Config 'lark' must be provided when lark is enabled")
if _ep == "wechat" and wechat is None:
@@ -368,6 +396,7 @@ class V2Config:
version=payload.get("version", "v2"),
slack=slack,
discord=discord,
+ telegram=telegram,
lark=lark,
wechat=wechat,
runtime=runtime,
@@ -397,6 +426,7 @@ class V2Config:
"version": self.version,
"slack": self.slack.__dict__,
"discord": self.discord.__dict__ if self.discord else None,
+ "telegram": self.telegram.__dict__ if self.telegram else None,
"lark": self.lark.__dict__ if self.lark else None,
"wechat": self.wechat.__dict__ if self.wechat else None,
"runtime": {
diff --git a/core/controller.py b/core/controller.py
index 4c8b998a7..efa06230b 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -9,7 +9,7 @@ from typing import Optional, Dict, Any
from config import paths
from modules.im import BaseIMClient, MessageContext, IMFactory
from modules.im.multi import MultiIMClient
-from modules.im.formatters import SlackFormatter, DiscordFormatter
+from modules.im.formatters import SlackFormatter, DiscordFormatter, TelegramFormatter
from modules.agent_router import AgentRouter
from modules.agents import AgentService, ClaudeAgent, CodexAgent, OpenCodeAgent
from modules.claude_client import ClaudeClient
@@ -113,6 +113,8 @@ class Controller:
def _create_formatter(self, platform: str):
if platform == "discord":
return DiscordFormatter()
+ if platform == "telegram":
+ return TelegramFormatter()
if platform == "lark":
from modules.im.formatters.feishu_formatter import FeishuFormatter
@@ -173,6 +175,8 @@ class Controller:
im_cfg.require_mention = v2_config.slack.require_mention
elif platform == "discord" and v2_config.discord:
im_cfg.require_mention = v2_config.discord.require_mention
+ elif platform == "telegram" and v2_config.telegram:
+ im_cfg.require_mention = v2_config.telegram.require_mention
elif platform == "wechat" and v2_config.wechat:
im_cfg.require_mention = v2_config.wechat.require_mention
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 6a45f40ac..be28ee6a0 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -102,11 +102,14 @@ class CommandHandlers(BaseHandler):
supports_threads = (
getattr(im_client, "should_use_thread_for_dm_session", lambda: False)()
if is_dm
- else getattr(im_client, "should_use_thread_for_reply", lambda: False)()
+ else (
+ getattr(im_client, "should_use_thread_for_reply", lambda: False)()
+ and getattr(im_client, "should_use_message_id_for_channel_session", lambda _context=None: True)(context)
+ )
)
# For non-interactive platforms, use traditional text message
- if platform not in {"slack", "discord", "lark"}:
+ if platform not in {"slack", "discord", "lark", "telegram"}:
user_name = self._resolve_user_display_name(user_info, self._t("command.start.userFallback"))
show_channel = platform != "wechat"
message_text = self._build_non_interactive_start_message(
@@ -121,7 +124,7 @@ class CommandHandlers(BaseHandler):
await im_client.send_message(channel_context, message_text)
return
- # For Slack/Discord, create interactive buttons
+ # For Slack/Discord/Telegram, create interactive buttons
user_name = self._resolve_user_display_name(user_info, "User")
# Create interactive buttons for commands
@@ -167,6 +170,13 @@ class CommandHandlers(BaseHandler):
"""Handle /new command - reset active session state for a fresh start."""
try:
im_client = self._get_im_client(context)
+ platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platform
+ if platform == "telegram" and hasattr(im_client, "start_new_topic_session"):
+ topic_context = await im_client.start_new_topic_session(context)
+ if topic_context is not None:
+ await im_client.send_message(topic_context, f"🆕 {self._t('command.new.started')}")
+ logger.info("Started new Telegram topic session for user %s", context.user_id)
+ return
session_key = self._get_session_key(context)
await self.controller.agent_service.clear_sessions(session_key)
full_response = f"🆕 {self._t('command.new.started')}"
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index ef40b497f..59cb66833 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -48,7 +48,20 @@ class SessionHandler(BaseHandler):
else:
base_id = context.channel_id or context.user_id
else:
- base_id = context.thread_id or context.message_id or context.channel_id
+ base_id = context.thread_id
+ if not base_id:
+ use_message_id = True
+ getter = getattr(self.controller, "get_im_client_for_context", None)
+ if callable(getter):
+ try:
+ im_client = getter(context)
+ except AttributeError:
+ im_client = getattr(self.controller, "im_client", None)
+ else:
+ im_client = getattr(self.controller, "im_client", None)
+ if im_client and hasattr(im_client, "should_use_message_id_for_channel_session"):
+ use_message_id = bool(im_client.should_use_message_id_for_channel_session(context))
+ base_id = context.message_id if use_message_id and context.message_id else context.channel_id
return f"{platform}_{base_id}"
def get_working_path(self, context: MessageContext) -> str:
diff --git a/docs/plans/telegram-im.md b/docs/plans/telegram-im.md
new file mode 100644
index 000000000..2337e5686
--- /dev/null
+++ b/docs/plans/telegram-im.md
@@ -0,0 +1,523 @@
+# Telegram IM Integration Plan
+
+## Background
+
+Vibe Remote already has the right product direction for Telegram: AI should live in the messaging tools people already use, behave like a colleague, and share one core orchestration layer across multiple transports.
+
+The current codebase is also no longer Slack-shaped:
+
+- `config/v2_config.py` already models multiple enabled platforms and per-platform config blocks.
+- `modules/im/base.py` and `modules/im/factory.py` already provide the IM abstraction seam.
+- `core/controller.py` already boots multiple IM runtimes and routes by `context.platform`.
+- `core/handlers/` already holds most business logic at a platform-agnostic layer.
+- `ui/` and `vibe/api.py` already support platform selection and per-platform setup flows.
+
+That means Telegram should be added as a first-class platform, not as a fork of Slack logic.
+
+## Vision Fit
+
+Telegram is a strong fit for the product vision in `VISION.md`:
+
+- it is mobile-first and message-first
+- it supports DMs, groups, supergroups, and forum topics
+- it supports inline buttons, replies, files, and bot commands
+- it is common in communities where users want to trigger coding agents away from a laptop
+
+The product goal should remain: one shared colleague-like core, multiple messaging transports.
+
+## Architecture Findings
+
+### What is already in good shape
+
+1. Multi-platform runtime already exists.
+ - `Controller` owns `self.im_clients`, `self.primary_platform`, and a `MultiIMClient`.
+ - `IMFactory.create_clients()` already branches by platform.
+
+2. Session routing is already platform-aware.
+ - `SessionHandler.get_base_session_id()` prefixes session ids with the platform.
+ - DM and non-DM session semantics are already separated.
+
+3. Settings and routing are already platform-scoped.
+ - settings keys are resolved via platform-specific managers
+ - session keys are globally unique via `platform::scope`
+
+4. The UI already assumes multiple platform cards and platform-specific setup steps.
+ - `ui/src/lib/platforms.ts`
+ - `ui/src/components/steps/PlatformSelection.tsx`
+ - `ui/src/components/steps/ChannelList.tsx`
+
+### What is not solved yet
+
+1. Platform capability differences are still uneven.
+ - Slack and Discord have rich interactive flows.
+ - WeChat proves the repo can support weaker interaction models, but some flows are still biased toward modal-capable platforms.
+
+2. Channel discovery is not universally abstracted.
+ - Slack/Discord/Lark rely on server-side list APIs.
+ - Telegram Bot API does not provide a generic "list all chats the bot belongs to" endpoint.
+
+3. Platform-specific onboarding is still credential-flow centric.
+ - Telegram will need both token validation and different operator guidance for privacy mode, group usage, and topic behavior.
+
+## Telegram Facts And Constraints
+
+Based on the official Telegram Bot API:
+
+- inbound delivery can use `getUpdates` or `setWebhook`; they are mutually exclusive
+- bots receive `callback_query`, can edit messages, and can send files/documents/media
+- Telegram supports `message_thread_id` for forum topics
+- bots can expose slash commands via `setMyCommands`
+- group visibility is constrained by privacy mode unless the bot is explicitly addressed
+
+Implications for Vibe Remote:
+
+1. Phase 1 should use long polling, not webhooks.
+ - It matches the current single-process local-first runtime.
+ - It avoids introducing inbound public HTTP requirements just to get the first version shipped.
+
+2. Telegram should be treated as a channel-capable platform, but not as a directory-listing platform.
+ - We can manage chats after they are discovered.
+ - We should not pretend we can browse all groups/channels from the setup wizard the way Slack and Discord do.
+
+3. Telegram is interactive enough for reply enhancements.
+ - inline keyboard maps well to quick replies and action buttons
+ - callback queries map well to resume/routing/settings actions
+
+4. Telegram does not have Slack/Discord-style modals.
+ - for free-form input we should prefer conversational follow-up plus `ForceReply`, not platform-specific modal emulation
+
+## Recommended Scope
+
+### Phase 1 scope
+
+Support:
+
+- private chats
+- group chats and supergroups
+- forum topics in supergroups
+- inline buttons / callback queries
+- file upload and file download
+- slash commands as fallback entrypoints
+- mention-gated group interactions
+
+Defer:
+
+- webhook mode
+- Telegram channel broadcast workflows as a first-class use case
+- payments, inline queries, business account features, stickers, polls
+- full parity for every Slack modal flow
+
+### Product stance
+
+Telegram channels are not the best phase-1 target for Vibe Remote. The core product is conversational collaboration, so the first version should optimize for DMs, groups, and forum topics. Pure broadcast-channel support can wait unless there is a concrete user need.
+
+## Proposed Architecture
+
+### 1. Config model
+
+Add `TelegramConfig` to `config/v2_config.py` and extend supported platforms:
+
+- `platform`: allow `"telegram"`
+- `platforms.enabled`: allow `"telegram"`
+- `V2Config.telegram: Optional[TelegramConfig]`
+
+Suggested config shape:
+
+```python
+@dataclass
+class TelegramConfig(BaseIMConfig):
+ bot_token: str = ""
+ require_mention: bool = True
+ use_webhook: bool = False
+ webhook_url: Optional[str] = None
+ webhook_secret_token: Optional[str] = None
+ allowed_chat_ids: Optional[list[str]] = None
+ allowed_user_ids: Optional[list[str]] = None
+
+ def validate(self) -> None:
+ # Allow empty during setup wizard, validate when enabled in runtime.
+ pass
+```
+
+Notes:
+
+- `require_mention` should default to `True` for Telegram.
+- webhook fields should exist early in the schema, but webhook runtime should remain disabled in phase 1.
+- allowlists are optional but worth baking in now because Telegram group surfaces can be noisy.
+
+### 2. New IM adapter
+
+Add:
+
+- `modules/im/telegram.py`
+- `modules/im/telegram_api.py`
+- `modules/im/formatters/telegram_formatter.py`
+
+Recommended design:
+
+- use direct Bot API calls over `aiohttp`
+- do not introduce `python-telegram-bot` in phase 1
+
+Reasoning:
+
+- the repo already has a clean IM abstraction, so a second bot framework is unnecessary
+- the Bot API surface Vibe Remote needs is plain HTTP + JSON + multipart upload
+- avoiding `python-telegram-bot` sidesteps its single-threaded/non-thread-safe caveats and avoids adding a new framework-level lifecycle inside our own runtime
+- staying on `aiohttp` keeps the adapter consistent with existing code patterns
+
+### 3. IM factory and controller wiring
+
+Update:
+
+- `modules/im/factory.py`
+- `core/controller.py`
+- `modules/im/formatters/__init__.py`
+
+Needed behavior:
+
+- create a `TelegramBot` when Telegram is enabled
+- refresh `require_mention` on config hot reload
+- create a Telegram formatter in `_create_formatter`
+- ensure `get_im_client_for_context()` works unchanged with Telegram contexts
+
+### 4. Telegram message model mapping
+
+Map Telegram updates into `MessageContext` like this:
+
+- `platform`: `"telegram"`
+- `user_id`: sender user id
+- `channel_id`: chat id
+- `thread_id`: `message_thread_id` when present
+- `message_id`: Telegram message id
+- `platform_specific`:
+ - `is_dm`
+ - raw update/message handles when needed
+ - mention/reply metadata
+ - callback query id when relevant
+
+Session rules:
+
+- DM: stable session per `chat_id`
+- Plain group/supergroup without forum topics: stable session per `chat_id`; only explicit `New Session` creates a new backend session
+- Forum topic: stable session per `message_thread_id`
+- Forum supergroup `General` topic: a new top-level user message should auto-create a new forum topic and route the session into that topic
+
+That fits the existing `SessionHandler` model without needing a Telegram-specific session rewrite.
+
+### 5. Shared discovered-chat registry
+
+This is the most important design choice.
+
+Telegram cannot rely on the existing "load all channels from platform API" pattern. The right fix is not to hardcode a Telegram exception deep in the UI. The right fix is to add a shared discovered-chat registry for platforms that learn available conversations from inbound events.
+
+Proposed shared concept:
+
+- new state-backed registry under `~/.vibe_remote/state/`
+- stores discovered chat metadata per platform
+- written by IM adapters when they receive inbound events or membership updates
+- readable by `vibe/api.py` and the Channel UI
+
+Suggested metadata:
+
+- `platform`
+- `chat_id`
+- `chat_type`
+- `title`
+- `username`
+- `is_dm`
+- `is_forum`
+- `last_seen_at`
+- `last_message_thread_id` if useful
+
+This abstraction is reusable for future platforms that also lack a listing API.
+
+### 6. Interaction model
+
+Support these primitives in `TelegramBot`:
+
+- `send_message`
+- `send_message_with_buttons`
+- `edit_message`
+- `answer_callback`
+- `send_dm`
+- `download_file`
+- `download_file_to_path`
+- `upload_image_from_path`
+- `upload_file_from_path`
+- `send_typing_indicator`
+- `clear_typing_indicator`
+
+Recommended Telegram-specific UI behavior:
+
+- use inline keyboard for quick actions
+- use callback query handlers for buttons
+- use conversational prompts or `ForceReply` for text input flows such as `set_cwd`
+- keep commands as fallback, not as the primary menu model
+- avoid trying to fake Slack-style modal parity
+
+Recommended session UX behavior:
+
+- DM: one chat defaults to one session until the user explicitly clicks `New Session`
+- Plain group/supergroup: one chat defaults to one session until the user explicitly clicks `New Session`
+- Forum supergroup `General`: a new top-level user message should automatically create a new topic that becomes the new session container
+- Inside an existing topic: keep reusing that topic's session
+
+### 7. Group mention and privacy behavior
+
+Telegram requires a cleaner policy than Slack:
+
+- DMs always work
+- in groups, default to mention/reply-triggered behavior
+- expose `require_mention` as an explicit Telegram platform setting
+- document that reading all group messages depends on Telegram privacy mode configuration
+
+This should be reflected in onboarding copy and not buried in logs.
+
+### 8. Buttons and commands
+
+Telegram should behave like Discord, not like a command-first bot.
+
+Primary interaction model:
+
+- use buttons for menu entry and common actions
+- expose `New Session`, `Settings`, `Resume`, and other high-frequency actions as buttons
+- keep the conversation UI centered on reply buttons and follow-up actions
+
+Fallback command set:
+
+- `/start`
+- `/new`
+- `/cwd`
+- `/set_cwd`
+- `/settings`
+- `/stop`
+- `/bind`
+
+Implementation note:
+
+- inbound slash commands should still flow through the existing shared command handlers
+- optionally call `setMyCommands` during startup or setup save to improve UX
+- command help copy should explicitly point users back to button-first usage
+
+## UI And Setup Plan
+
+### 1. Setup wizard
+
+Update:
+
+- `ui/src/lib/platforms.ts`
+- `ui/src/components/steps/PlatformSelection.tsx`
+- `ui/src/components/Wizard.tsx`
+- add `ui/src/components/steps/TelegramConfig.tsx`
+
+Telegram setup step should include:
+
+- bot token input
+- token validation via `getMe`
+- clear explanation of DM/group/topic support
+- privacy mode guidance
+- forum topic guidance for supergroups
+- note that chats appear after the bot receives messages or is added to groups
+
+### 2. Dashboard and settings
+
+Update:
+
+- dashboard platform cards
+- platform labels and descriptions
+- channel settings routing to Telegram-specific channel management
+
+Telegram settings should show:
+
+- token presence / validation state
+- require-mention toggle
+- discovered chats count
+- whether forum auto-topic mode is available for a discovered supergroup
+- webhook fields hidden or marked future-facing in phase 1
+
+### 3. Channel management
+
+Do not copy Slack/Discord discovery UX.
+
+Recommended Telegram channel page:
+
+- list discovered chats from the shared registry
+- allow enabling/disabling each discovered chat
+- allow manual add by `chat_id` as an escape hatch
+- clearly label DM / group / supergroup / forum-topic-capable chats
+- for forum-capable supergroups, show that new top-level messages in `General` auto-create a new topic/session
+
+This is the highest-leverage product adjustment needed for Telegram.
+
+## Backend API Plan
+
+Update `vibe/api.py` and `vibe/ui_server.py` with Telegram-specific endpoints:
+
+- `telegram_auth_test(bot_token)` via `getMe`
+- `telegram_get_me(bot_token)` if separate payload is useful
+- `telegram_list_discovered_chats()` backed by the shared registry
+- optional `telegram_add_chat(chat_id)` for manual entry
+
+Important:
+
+- do not claim we can enumerate all Telegram chats from the Bot API
+- if chat enrichment is needed, use `getChat(chat_id)` only after the chat is already known
+
+## Formatter Plan
+
+Add `TelegramFormatter`.
+
+Prefer a conservative formatting policy:
+
+- start with plain text plus fenced code blocks where safe
+- add Telegram MarkdownV2 or HTML formatting only with correct escaping
+- avoid aggressive markdown conversion until tests cover escaping well
+
+Reasoning:
+
+- Telegram formatting rules are strict enough that partial escaping causes user-visible failures
+- a reliable plain-text-first formatter is better than a flaky rich formatter
+
+## Testing Plan
+
+### Unit tests
+
+Add or extend:
+
+- `tests/test_telegram_bot.py`
+- `tests/test_multi_platform_runtime.py`
+- `tests/test_session_handler_base_id.py`
+- `tests/test_v2_compat_platforms.py`
+- `tests/test_ui_api.py`
+
+Minimum cases:
+
+- config load/save with Telegram enabled
+- IM factory creates Telegram client
+- inbound DM, group, and topic message mapping
+- callback query routing
+- session id behavior for DM vs plain group vs topic
+- forum `General` top-level message triggers auto-topic creation flow
+- file download/upload plumbing
+- discovered chat registry updates on inbound events
+- API/auth test behavior
+
+### Manual validation
+
+1. DM the bot and verify button-first entry works; `/start` remains only as fallback.
+2. Add the bot to a plain group and verify the chat stays on one session until `New Session`.
+3. Use a forum-enabled supergroup and verify a new top-level message in `General` auto-creates a topic for a new session.
+4. Inside an existing topic, verify follow-up messages stay on the same session.
+5. Trigger buttons for settings/resume/routing.
+6. Send an attachment and verify download path handling.
+7. Ask the agent to send a file/image and verify outbound upload.
+
+### Regression environment
+
+Do not try to fold Telegram into the existing Docker three-regression flow immediately.
+
+Recommended rollout:
+
+1. ship adapter + unit coverage first
+2. add manual Telegram smoke validation
+3. then design whether the unified regression container should evolve into a four-platform container
+
+## Implementation Phases
+
+### Phase 0: skeleton
+
+- add config schema and platform enum support
+- add Telegram formatter stub
+- add Telegram adapter skeleton
+- wire factory/controller/UI labels
+
+Exit condition:
+
+- app boots with Telegram enabled
+- token can be saved and validated
+
+### Phase 1: core messaging
+
+- implement long-poll update loop
+- map inbound messages to `MessageContext`
+- support `send_message`, typing, inline buttons, callback queries, and fallback slash commands
+- support DM and group basics
+
+Exit condition:
+
+- DM and plain-group conversations work end-to-end with button-first interaction
+
+### Phase 2: session and topic correctness
+
+- handle `message_thread_id`
+- implement forum `General` to auto-topic session creation flow
+- verify topic session behavior
+- refine mention/reply behavior in groups
+- support message editing for long-running updates where appropriate
+
+Exit condition:
+
+- forum topic conversations behave predictably
+
+### Phase 3: file and richer actions
+
+- implement file download via `getFile`
+- implement outbound document/image upload
+- polish reply enhancements and resume/settings flows
+
+Exit condition:
+
+- Telegram reaches practical parity with existing core flows
+
+### Phase 4: UI and operator experience
+
+- finish Telegram setup step
+- build discovered chat management UI
+- document privacy mode and group behavior
+- add setup docs in English and Chinese
+
+Exit condition:
+
+- new users can self-serve setup without reading code
+
+## Risks
+
+1. Channel discovery mismatch
+ - Biggest product risk.
+ - Mitigation: build a shared discovered-chat registry instead of forcing Telegram into Slack-like channel listing.
+
+2. Formatting fragility
+ - Telegram rich text escaping is easy to break.
+ - Mitigation: start conservative; add rich formatting only when tests prove it.
+
+3. Group privacy confusion
+ - Users may expect the bot to read all group traffic.
+ - Mitigation: default `require_mention=true` and explain privacy mode clearly in UI/docs.
+
+4. Auto-topic creation permissions and noise
+ - Forum auto-topic mode requires the bot to be able to create topics, and can create noise in active groups.
+ - Mitigation: only enable it for forum-capable supergroups, document the behavior clearly, and gate it behind detected capability.
+
+5. Scope creep toward "Telegram everything"
+ - The Bot API surface is large.
+ - Mitigation: stay focused on conversational Vibe Remote workflows, not the full Telegram platform.
+
+## Open Questions
+
+1. Should phase 1 allow manual `chat_id` entry in the UI, or is discovered-chat-only enough?
+2. Do we want `/settings` and `/set_cwd` free-form input flows to use `ForceReply`, or just button-triggered conversational prompts first?
+3. Should forum auto-topic creation be configurable per supergroup, or always on when the chat supports it?
+4. Should broadcast channels be explicit non-goals in the first PR, or included as limited send-only surfaces?
+5. Should we introduce a generic discovered-chat registry now, or a Telegram-only version that we generalize later?
+
+My recommendation is to introduce the shared registry now. It is the highest-layer fix and matches the repository's architecture principles.
+
+## References
+
+- Vision: `VISION.md`
+- Existing plans:
+ - `docs/plans/multi-platform-im.md`
+ - `docs/plans/discord-im.md`
+ - `docs/plans/wechat-ilink-integration.md`
+- Official Telegram Bot API: https://core.telegram.org/bots/api
+- python-telegram-bot docs: https://docs.python-telegram-bot.org/en/stable/
diff --git a/modules/im/base.py b/modules/im/base.py
index 0beb44047..87ce41e51 100644
--- a/modules/im/base.py
+++ b/modules/im/base.py
@@ -146,6 +146,10 @@ class BaseIMClient(ABC):
"""
return False
+ def should_use_message_id_for_channel_session(self, context: Optional[MessageContext] = None) -> bool:
+ """Whether non-thread channel messages should default to per-message sessions."""
+ return True
+
@staticmethod
def extract_command_action(text: str, allow_plain_bind: bool = False) -> str:
"""Extract command action name from slash command text.
diff --git a/modules/im/factory.py b/modules/im/factory.py
index 05d377877..3b8b3d0de 100644
--- a/modules/im/factory.py
+++ b/modules/im/factory.py
@@ -40,6 +40,7 @@ class IMFactory:
# Dynamic imports to avoid circular dependency
from .slack import SlackBot
from .discord import DiscordBot
+ from .telegram import TelegramBot
enabled_platforms = list(getattr(config, "enabled_platforms", lambda: [getattr(config, "platform", "slack")])())
clients: dict[str, BaseIMClient] = {}
@@ -56,6 +57,12 @@ class IMFactory:
logger.info("Creating Discord client")
clients[platform] = DiscordBot(config.discord)
continue
+ if platform == "telegram":
+ if not getattr(config, "telegram", None):
+ raise ValueError("Telegram configuration not found")
+ logger.info("Creating Telegram client")
+ clients[platform] = TelegramBot(config.telegram)
+ continue
if platform == "lark":
from .feishu import FeishuBot
@@ -82,7 +89,7 @@ class IMFactory:
Returns:
List of supported platform names
"""
- return ["slack", "discord", "lark", "wechat"]
+ return ["slack", "discord", "telegram", "lark", "wechat"]
@staticmethod
def validate_platform_config(config) -> None:
@@ -105,6 +112,11 @@ class IMFactory:
raise ValueError("Missing configuration for platform: discord")
config.discord.validate()
continue
+ if platform == "telegram":
+ if getattr(config, "telegram", None) is None:
+ raise ValueError("Missing configuration for platform: telegram")
+ config.telegram.validate()
+ continue
if platform == "lark":
if config.lark is None:
raise ValueError("Missing configuration for platform: lark")
diff --git a/modules/im/formatters/__init__.py b/modules/im/formatters/__init__.py
index bef36092c..d0d976222 100644
--- a/modules/im/formatters/__init__.py
+++ b/modules/im/formatters/__init__.py
@@ -1,7 +1,15 @@
from .base_formatter import BaseMarkdownFormatter
from .slack_formatter import SlackFormatter
from .discord_formatter import DiscordFormatter
+from .telegram_formatter import TelegramFormatter
from .feishu_formatter import FeishuFormatter
from .wechat_formatter import WeChatFormatter
-__all__ = ["BaseMarkdownFormatter", "SlackFormatter", "DiscordFormatter", "FeishuFormatter", "WeChatFormatter"]
+__all__ = [
+ "BaseMarkdownFormatter",
+ "SlackFormatter",
+ "DiscordFormatter",
+ "TelegramFormatter",
+ "FeishuFormatter",
+ "WeChatFormatter",
+]
diff --git a/modules/im/formatters/telegram_formatter.py b/modules/im/formatters/telegram_formatter.py
new file mode 100644
index 000000000..6f754a173
--- /dev/null
+++ b/modules/im/formatters/telegram_formatter.py
@@ -0,0 +1,25 @@
+"""Telegram formatter.
+
+Telegram formatting is strict and easy to break when escaping is incomplete.
+Use a conservative plain-text formatter for now; richer formatting can be
+added later once the adapter has stronger test coverage.
+"""
+
+from .base_formatter import BaseMarkdownFormatter
+
+
+class TelegramFormatter(BaseMarkdownFormatter):
+ def format_bold(self, text: str) -> str:
+ return text
+
+ def format_italic(self, text: str) -> str:
+ return text
+
+ def format_strikethrough(self, text: str) -> str:
+ return text
+
+ def format_link(self, text: str, url: str) -> str:
+ return f"{text} ({url})"
+
+ def escape_special_chars(self, text: str) -> str:
+ return text
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
new file mode 100644
index 000000000..8f50a34c4
--- /dev/null
+++ b/modules/im/telegram.py
@@ -0,0 +1,537 @@
+from __future__ import annotations
+
+import asyncio
+import logging
+import threading
+from datetime import datetime
+from typing import Any, Callable, Dict, Optional
+
+from config.discovered_chats import DiscoveredChatsStore
+from config.v2_config import TelegramConfig
+from vibe.i18n import t as i18n_t
+
+from .base import BaseIMClient, FileAttachment, MessageContext, InlineButton, InlineKeyboard
+from .formatters import TelegramFormatter
+from . import telegram_api
+
+logger = logging.getLogger(__name__)
+
+
+class TelegramBot(BaseIMClient):
+ """Telegram adapter using Bot API long polling."""
+
+ def __init__(self, config: TelegramConfig):
+ super().__init__(config)
+ self.config = config
+ self.formatter = TelegramFormatter()
+ self.settings_manager = None
+ self.sessions = None
+ self._controller = None
+ self._stop_event = threading.Event()
+ self._offset: Optional[int] = None
+ self._bot_user: Optional[dict[str, Any]] = None
+ self._on_ready: Optional[Callable] = None
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
+
+ def set_settings_manager(self, settings_manager):
+ self.settings_manager = settings_manager
+ self.sessions = getattr(settings_manager, "sessions", None)
+
+ def set_controller(self, controller):
+ self._controller = controller
+
+ def register_callbacks(
+ self,
+ on_message: Optional[Callable] = None,
+ on_command: Optional[Dict[str, Callable]] = None,
+ on_callback_query: Optional[Callable] = None,
+ **kwargs,
+ ):
+ super().register_callbacks(on_message, on_command, on_callback_query, **kwargs)
+ if "on_ready" in kwargs:
+ self._on_ready = kwargs["on_ready"]
+
+ def _t(self, key: str, **kwargs) -> str:
+ lang = "en"
+ if self._controller and hasattr(self._controller, "_get_lang"):
+ lang = self._controller._get_lang()
+ return i18n_t(key, lang, **kwargs)
+
+ def get_default_parse_mode(self) -> Optional[str]:
+ return None
+
+ def should_use_thread_for_reply(self) -> bool:
+ return True
+
+ def should_use_message_id_for_channel_session(self, context: Optional[MessageContext] = None) -> bool:
+ return False
+
+ def format_markdown(self, text: str) -> str:
+ return text
+
+ def register_handlers(self):
+ return None
+
+ def run(self):
+ if not self.config.bot_token:
+ raise ValueError("Telegram bot token is required")
+ self._stop_event.clear()
+ asyncio.run(self._run())
+
+ def stop(self):
+ self._stop_event.set()
+
+ async def shutdown(self) -> None:
+ self._stop_event.set()
+
+ async def _run(self) -> None:
+ self._loop = asyncio.get_running_loop()
+ self._bot_user = (await telegram_api.get_me(self.config.bot_token)).get("result")
+ logger.info("Telegram bot connected as @%s", self._bot_user.get("username") if self._bot_user else "unknown")
+ if self._on_ready:
+ await self._on_ready()
+
+ while not self._stop_event.is_set():
+ try:
+ updates = await telegram_api.get_updates(self.config.bot_token, self._offset)
+ for update in updates.get("result", []):
+ self._offset = int(update["update_id"]) + 1
+ await self._handle_update(update)
+ except Exception as err:
+ logger.warning("Telegram poll loop error: %s", err, exc_info=True)
+ await asyncio.sleep(2)
+
+ async def _handle_update(self, update: dict[str, Any]) -> None:
+ if update.get("callback_query"):
+ await self._handle_callback_query(update["callback_query"])
+ return
+ message = update.get("message")
+ if message:
+ await self._handle_message(message)
+
+ async def _handle_message(self, message: dict[str, Any]) -> None:
+ context = self._build_message_context(message)
+ if context is None:
+ return
+
+ text = message.get("text") or message.get("caption") or ""
+ text = self._normalize_command_text(text)
+
+ if self.config.require_mention and not context.platform_specific.get("is_dm", False):
+ if not self._is_explicitly_addressed(message, text):
+ return
+
+ denial = self.check_authorization(
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ is_dm=bool(context.platform_specific.get("is_dm")),
+ text=text,
+ settings_manager=self.settings_manager,
+ )
+ if not denial.allowed:
+ denial_text = self.build_auth_denial_text(denial.denial, context.channel_id)
+ if denial_text:
+ await self.send_message(context, denial_text)
+ return
+
+ allow_plain_bind = self.should_allow_plain_bind(
+ user_id=context.user_id,
+ is_dm=bool(context.platform_specific.get("is_dm")),
+ settings_manager=self.settings_manager,
+ )
+ if await self.dispatch_text_command(context, text, allow_plain_bind=allow_plain_bind):
+ return
+
+ context = await self._maybe_route_to_forum_topic(context, message, text)
+
+ if self.on_message_callback:
+ await self.on_message_callback(context, text)
+
+ async def _maybe_route_to_forum_topic(
+ self,
+ context: MessageContext,
+ message: dict[str, Any],
+ text: str,
+ ) -> MessageContext:
+ if not self._should_auto_create_topic(context, message, text):
+ return context
+
+ try:
+ new_context = await self.start_new_topic_session(context, seed_text=text, message=message)
+ if new_context is not None:
+ return new_context
+ except Exception as err:
+ logger.warning("Telegram forum auto-topic failed, falling back to current topic: %s", err, exc_info=True)
+ return context
+
+ def _should_auto_create_topic(self, context: MessageContext, message: dict[str, Any], text: str) -> bool:
+ if not self.config.forum_auto_topic:
+ return False
+ if (context.platform_specific or {}).get("chat_type") != "supergroup":
+ return False
+ if not bool(message.get("is_topic_message")):
+ return False
+ if str(context.thread_id or "") != "1":
+ return False
+ if message.get("reply_to_message"):
+ return False
+ if text.startswith("/"):
+ return False
+ return True
+
+ def _derive_topic_title(self, text: str, message: dict[str, Any]) -> str:
+ first_line = ""
+ if text:
+ first_line = text.strip().splitlines()[0].strip()
+ if first_line.startswith("/"):
+ first_line = ""
+ if first_line:
+ if len(first_line) > 60:
+ return first_line[:57].rstrip() + "..."
+ return first_line
+ sender = (message.get("from") or {}).get("first_name") or "Session"
+ return f"{sender} {datetime.now().strftime('%m-%d %H:%M')}"
+
+ async def start_new_topic_session(
+ self,
+ context: MessageContext,
+ *,
+ seed_text: str = "",
+ message: Optional[dict[str, Any]] = None,
+ ) -> Optional[MessageContext]:
+ payload = context.platform_specific or {}
+ if payload.get("chat_type") != "supergroup":
+ return None
+ if not context.thread_id and not payload.get("is_topic_message"):
+ return None
+
+ topic_name = self._derive_topic_title(seed_text, message or {})
+ created = await telegram_api.create_forum_topic(self.config.bot_token, context.channel_id, topic_name)
+ topic = created.get("result") or {}
+ topic_id = topic.get("message_thread_id")
+ if topic_id is None:
+ raise RuntimeError("Telegram createForumTopic returned no message_thread_id")
+
+ topic_context = MessageContext(
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ thread_id=str(topic_id),
+ message_id=context.message_id,
+ platform="telegram",
+ files=context.files,
+ platform_specific={
+ **payload,
+ "is_topic_message": True,
+ "auto_topic_created": True,
+ "topic_name": topic_name,
+ },
+ )
+
+ if str(context.thread_id or "") == "1":
+ try:
+ await self.send_message(
+ context,
+ self._t("telegram.autoTopicGeneralNotice", topic=topic_name),
+ reply_to=context.message_id,
+ )
+ except Exception:
+ logger.debug("Failed to send Telegram General handoff notice", exc_info=True)
+
+ try:
+ intro = self._t("telegram.autoTopicIntro", topic=topic_name)
+ if seed_text:
+ intro = f"{intro}\n\n> {seed_text}"
+ await self.send_message(topic_context, intro)
+ except Exception:
+ logger.debug("Failed to send Telegram topic intro", exc_info=True)
+
+ return topic_context
+
+ async def _handle_callback_query(self, payload: dict[str, Any]) -> None:
+ message = payload.get("message") or {}
+ chat = message.get("chat") or {}
+ from_user = payload.get("from") or {}
+ if not chat or not from_user:
+ return
+ self._remember_discovered_chat(chat, message)
+ thread_id = message.get("message_thread_id")
+ context = MessageContext(
+ user_id=str(from_user.get("id")),
+ channel_id=str(chat.get("id")),
+ thread_id=str(thread_id) if thread_id is not None else None,
+ message_id=str(message.get("message_id")),
+ platform="telegram",
+ platform_specific={
+ "is_dm": chat.get("type") == "private",
+ "chat_type": chat.get("type"),
+ "chat_title": chat.get("title") or chat.get("username"),
+ "is_topic_message": bool(message.get("is_topic_message")),
+ "raw_message": message,
+ },
+ )
+ callback_id = str(payload.get("id"))
+ context.platform_specific = {
+ **(context.platform_specific or {}),
+ "callback_id": callback_id,
+ "callback_query": payload,
+ }
+ if self.on_callback_query_callback:
+ await self.on_callback_query_callback(context, payload.get("data", ""))
+ await self.answer_callback(callback_id)
+
+ def _build_message_context(self, message: dict[str, Any]) -> Optional[MessageContext]:
+ chat = message.get("chat") or {}
+ from_user = message.get("from") or {}
+ if not chat or not from_user:
+ return None
+ self._remember_discovered_chat(chat, message)
+
+ chat_id = str(chat.get("id"))
+ user_id = str(from_user.get("id"))
+ thread_id = message.get("message_thread_id")
+ files = self._extract_files(message)
+
+ return MessageContext(
+ user_id=user_id,
+ channel_id=chat_id,
+ thread_id=str(thread_id) if thread_id is not None else None,
+ message_id=str(message.get("message_id")),
+ files=files,
+ platform="telegram",
+ platform_specific={
+ "is_dm": chat.get("type") == "private",
+ "chat_type": chat.get("type"),
+ "chat_title": chat.get("title") or chat.get("username"),
+ "raw_message": message,
+ },
+ )
+
+ def _remember_discovered_chat(self, chat: dict[str, Any], message: Optional[dict[str, Any]] = None) -> None:
+ try:
+ parts = [str(chat.get("first_name") or "").strip(), str(chat.get("last_name") or "").strip()]
+ display_name = " ".join(part for part in parts if part).strip()
+ name = chat.get("title") or chat.get("username") or display_name or str(chat.get("id") or "")
+ chat_type = str(chat.get("type") or "")
+ is_topic_message = bool((message or {}).get("is_topic_message"))
+ is_forum = bool(chat.get("is_forum")) or is_topic_message
+ DiscoveredChatsStore.get_instance().remember_chat(
+ platform="telegram",
+ chat_id=str(chat.get("id")),
+ name=name,
+ username=str(chat.get("username") or ""),
+ chat_type=chat_type,
+ is_private=chat_type == "private",
+ is_forum=is_forum,
+ supports_topics=chat_type == "supergroup" and is_forum,
+ )
+ except Exception:
+ logger.debug("Failed to remember Telegram discovered chat", exc_info=True)
+
+ def _extract_files(self, message: dict[str, Any]) -> list[FileAttachment]:
+ files: list[FileAttachment] = []
+ document = message.get("document")
+ if document:
+ files.append(
+ FileAttachment(
+ name=document.get("file_name") or "telegram-document",
+ mimetype=document.get("mime_type") or "application/octet-stream",
+ url=document.get("file_id"),
+ size=document.get("file_size"),
+ )
+ )
+ photo = message.get("photo") or []
+ if photo:
+ best = photo[-1]
+ files.append(
+ FileAttachment(
+ name="telegram-photo.jpg",
+ mimetype="image/jpeg",
+ url=best.get("file_id"),
+ size=best.get("file_size"),
+ )
+ )
+ return files
+
+ def _normalize_command_text(self, text: str) -> str:
+ stripped = (text or "").strip()
+ if not stripped.startswith("/"):
+ return stripped
+ head, *tail = stripped.split(maxsplit=1)
+ if "@" in head and self._bot_user and self._bot_user.get("username"):
+ command, _, username = head.partition("@")
+ if username.lower() == str(self._bot_user.get("username")).lower():
+ head = command
+ return " ".join([head, *tail]).strip()
+
+ def _is_explicitly_addressed(self, message: dict[str, Any], text: str) -> bool:
+ if text.startswith("/"):
+ return True
+ reply_to = message.get("reply_to_message") or {}
+ reply_from = reply_to.get("from") or {}
+ if self._bot_user and str(reply_from.get("id")) == str(self._bot_user.get("id")):
+ return True
+ username = str((self._bot_user or {}).get("username") or "")
+ if not username:
+ return False
+ entities = message.get("entities") or []
+ for entity in entities:
+ if entity.get("type") != "mention":
+ continue
+ offset = int(entity.get("offset", 0))
+ length = int(entity.get("length", 0))
+ if text[offset : offset + length].lower() == f"@{username.lower()}":
+ return True
+ return False
+
+ def _build_payload(
+ self,
+ context: MessageContext,
+ text: Optional[str] = None,
+ keyboard: Optional[InlineKeyboard] = None,
+ *,
+ reply_to: Optional[str] = None,
+ ) -> dict[str, Any]:
+ payload: dict[str, Any] = {"chat_id": context.channel_id}
+ if context.thread_id:
+ payload["message_thread_id"] = int(context.thread_id)
+ if text is not None:
+ payload["text"] = text
+ if reply_to:
+ payload["reply_parameters"] = {"message_id": int(reply_to)}
+ if keyboard is not None:
+ payload["reply_markup"] = {
+ "inline_keyboard": [
+ [{"text": button.text, "callback_data": button.callback_data} for button in row]
+ for row in keyboard.buttons
+ ]
+ }
+ return payload
+
+ async def send_message(
+ self, context: MessageContext, text: str, parse_mode: Optional[str] = None, reply_to: Optional[str] = None
+ ) -> str:
+ payload = self._build_payload(context, self.format_markdown(text), reply_to=reply_to)
+ result = await telegram_api.call_api(self.config.bot_token, "sendMessage", payload)
+ return str(result["result"]["message_id"])
+
+ async def send_message_with_buttons(
+ self, context: MessageContext, text: str, keyboard: InlineKeyboard, parse_mode: Optional[str] = None
+ ) -> str:
+ payload = self._build_payload(context, self.format_markdown(text), keyboard=keyboard)
+ result = await telegram_api.call_api(self.config.bot_token, "sendMessage", payload)
+ return str(result["result"]["message_id"])
+
+ async def edit_message(
+ self,
+ context: MessageContext,
+ message_id: str,
+ text: Optional[str] = None,
+ keyboard: Optional[InlineKeyboard] = None,
+ parse_mode: Optional[str] = None,
+ ) -> bool:
+ payload = {
+ "chat_id": context.channel_id,
+ "message_id": int(message_id),
+ }
+ if keyboard is not None:
+ payload["reply_markup"] = {
+ "inline_keyboard": [
+ [{"text": button.text, "callback_data": button.callback_data} for button in row]
+ for row in keyboard.buttons
+ ]
+ }
+ if text is not None:
+ payload["text"] = self.format_markdown(text)
+ await telegram_api.call_api(self.config.bot_token, "editMessageText", payload)
+ return True
+ await telegram_api.call_api(self.config.bot_token, "editMessageReplyMarkup", payload)
+ return True
+
+ async def answer_callback(self, callback_id: str, text: Optional[str] = None, show_alert: bool = False) -> bool:
+ payload = {"callback_query_id": callback_id, "show_alert": show_alert}
+ if text:
+ payload["text"] = text
+ await telegram_api.call_api(self.config.bot_token, "answerCallbackQuery", payload)
+ return True
+
+ async def get_user_info(self, user_id: str) -> Dict[str, Any]:
+ result = await telegram_api.call_api(self.config.bot_token, "getChat", {"chat_id": user_id})
+ chat = result["result"]
+ display_name = chat.get("first_name") or chat.get("username") or "Telegram User"
+ return {"id": user_id, "name": display_name, "display_name": display_name, "real_name": display_name}
+
+ async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:
+ result = await telegram_api.call_api(self.config.bot_token, "getChat", {"chat_id": channel_id})
+ chat = result["result"]
+ name = chat.get("title") or chat.get("username") or channel_id
+ return {"id": channel_id, "name": name, "type": chat.get("type")}
+
+ async def send_dm(self, user_id: str, text: str, **kwargs) -> Optional[str]:
+ context = MessageContext(user_id=user_id, channel_id=user_id, platform="telegram", platform_specific={"is_dm": True})
+ return await self.send_message(context, text)
+
+ async def send_typing_indicator(self, context: MessageContext) -> bool:
+ payload = {"chat_id": context.channel_id, "action": "typing"}
+ if context.thread_id:
+ payload["message_thread_id"] = int(context.thread_id)
+ await telegram_api.call_api(self.config.bot_token, "sendChatAction", payload)
+ return True
+
+ async def clear_typing_indicator(self, context: MessageContext) -> bool:
+ return True
+
+ async def upload_file_from_path(
+ self,
+ context: MessageContext,
+ file_path: str,
+ title: Optional[str] = None,
+ ) -> str:
+ payload = self._build_payload(context)
+ if title:
+ payload["caption"] = title
+ result = await telegram_api.send_multipart_file(
+ self.config.bot_token,
+ "sendDocument",
+ payload,
+ file_path,
+ "document",
+ )
+ return str(result["result"]["message_id"])
+
+ async def upload_image_from_path(
+ self,
+ context: MessageContext,
+ file_path: str,
+ title: Optional[str] = None,
+ ) -> str:
+ payload = self._build_payload(context)
+ if title:
+ payload["caption"] = title
+ result = await telegram_api.send_multipart_file(
+ self.config.bot_token,
+ "sendPhoto",
+ payload,
+ file_path,
+ "photo",
+ )
+ return str(result["result"]["message_id"])
+
+ async def download_file(
+ self,
+ file_info: Dict[str, Any],
+ max_bytes: Optional[int] = None,
+ timeout_seconds: int = 30,
+ ) -> Optional[bytes]:
+ file_id = (
+ file_info.get("telegram_file_id")
+ or file_info.get("url")
+ or file_info.get("file_id")
+ )
+ if not file_id:
+ raise ValueError("Telegram file_id is required")
+ file_result = await telegram_api.get_file(self.config.bot_token, str(file_id))
+ file_path = file_result["result"]["file_path"]
+ content = await telegram_api.download_file(self.config.bot_token, file_path, timeout_seconds=timeout_seconds)
+ if max_bytes is not None and len(content) > max_bytes:
+ raise ValueError("Downloaded file exceeds max_bytes")
+ return content
diff --git a/modules/im/telegram_api.py b/modules/im/telegram_api.py
new file mode 100644
index 000000000..bff75aa6a
--- /dev/null
+++ b/modules/im/telegram_api.py
@@ -0,0 +1,88 @@
+"""Minimal Telegram Bot API helpers."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any, Optional
+
+import aiohttp
+
+
+def _api_url(bot_token: str, method: str) -> str:
+ return f"https://api.telegram.org/bot{bot_token}/{method}"
+
+
+def _file_url(bot_token: str, file_path: str) -> str:
+ return f"https://api.telegram.org/file/bot{bot_token}/{file_path.lstrip('/')}"
+
+
+async def call_api(
+ bot_token: str,
+ method: str,
+ payload: Optional[dict[str, Any]] = None,
+ *,
+ timeout_seconds: int = 60,
+ form: Optional[aiohttp.FormData] = None,
+) -> dict[str, Any]:
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ if form is not None:
+ async with session.post(_api_url(bot_token, method), data=form) as resp:
+ data = await resp.json()
+ else:
+ async with session.post(_api_url(bot_token, method), json=payload or {}) as resp:
+ data = await resp.json()
+ if not data.get("ok"):
+ raise RuntimeError(data.get("description") or f"Telegram API call failed: {method}")
+ return data
+
+
+async def get_me(bot_token: str) -> dict[str, Any]:
+ return await call_api(bot_token, "getMe")
+
+
+async def create_forum_topic(bot_token: str, chat_id: str, name: str) -> dict[str, Any]:
+ return await call_api(bot_token, "createForumTopic", {"chat_id": chat_id, "name": name})
+
+
+async def get_updates(bot_token: str, offset: Optional[int], timeout_seconds: int = 30) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "timeout": timeout_seconds,
+ "allowed_updates": ["message", "callback_query", "my_chat_member", "chat_member"],
+ }
+ if offset is not None:
+ payload["offset"] = offset
+ return await call_api(bot_token, "getUpdates", payload, timeout_seconds=timeout_seconds + 10)
+
+
+async def download_file(bot_token: str, file_path: str, *, timeout_seconds: int = 60) -> bytes:
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ async with session.get(_file_url(bot_token, file_path)) as resp:
+ resp.raise_for_status()
+ return await resp.read()
+
+
+async def get_file(bot_token: str, file_id: str) -> dict[str, Any]:
+ return await call_api(bot_token, "getFile", {"file_id": file_id})
+
+
+async def send_multipart_file(
+ bot_token: str,
+ method: str,
+ payload: dict[str, Any],
+ file_path: str,
+ field_name: str,
+) -> dict[str, Any]:
+ form = aiohttp.FormData()
+ for key, value in payload.items():
+ if value is None:
+ continue
+ if isinstance(value, (dict, list)):
+ form.add_field(key, json.dumps(value))
+ else:
+ form.add_field(key, str(value))
+ path = Path(file_path)
+ form.add_field(field_name, path.read_bytes(), filename=path.name)
+ return await call_api(bot_token, method, form=form)
diff --git a/tests/test_command_handler_user_names.py b/tests/test_command_handler_user_names.py
index 9010c9301..5e959723a 100644
--- a/tests/test_command_handler_user_names.py
+++ b/tests/test_command_handler_user_names.py
@@ -48,15 +48,21 @@ class _StubIMClient:
def __init__(self, user_info):
self.user_info = user_info
self.sent_messages = []
+ self.sent_contexts = []
self.formatter = None
+ self.started_topic_context = None
async def get_user_info(self, user_id):
return self.user_info
async def send_message(self, context, text, parse_mode=None):
+ self.sent_contexts.append(context)
self.sent_messages.append((context.channel_id, text))
return "T1"
+ async def start_new_topic_session(self, context):
+ return self.started_topic_context
+
class _StubSettingsManager:
def __init__(self):
@@ -147,6 +153,33 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):
[("wx-chat", "🆕 已开启新的会话。你下一条消息会从全新对话开始。")],
)
+ async def test_telegram_new_command_creates_topic_session_when_supported(self):
+ controller = _StubController({"display_name": "Alex"})
+ setattr(controller.config, "platform", "telegram")
+ controller.agent_service.clear_sessions = _clear_sessions # type: ignore[attr-defined]
+ handler = CommandHandlers(controller)
+ controller.im_client.started_topic_context = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ thread_id="99",
+ platform="telegram",
+ )
+ context = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ thread_id="1",
+ platform="telegram",
+ platform_specific={"platform": "telegram"},
+ )
+
+ await handler.handle_new(context)
+
+ self.assertEqual(
+ controller.im_client.sent_messages,
+ [("-100123", "🆕 已开启新的会话。你下一条消息会从全新对话开始。")],
+ )
+ self.assertEqual(controller.im_client.sent_contexts[0].thread_id, "99")
+
async def _clear_sessions(_settings_key):
return {}
diff --git a/tests/test_discovered_chats.py b/tests/test_discovered_chats.py
new file mode 100644
index 000000000..0bb30fab3
--- /dev/null
+++ b/tests/test_discovered_chats.py
@@ -0,0 +1,39 @@
+from config import paths
+from config.discovered_chats import DiscoveredChatsStore
+
+
+def test_discovered_chats_store_roundtrip(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ DiscoveredChatsStore.reset_instance()
+ store = DiscoveredChatsStore.get_instance()
+ store.remember_chat(
+ platform="telegram",
+ chat_id="-1001",
+ name="Core Forum",
+ chat_type="supergroup",
+ is_forum=True,
+ supports_topics=True,
+ )
+
+ DiscoveredChatsStore.reset_instance()
+ reloaded = DiscoveredChatsStore.get_instance()
+ chats = reloaded.list_chats("telegram", include_private=False)
+
+ assert len(chats) == 1
+ assert chats[0].name == "Core Forum"
+ assert chats[0].supports_topics is True
+ DiscoveredChatsStore.reset_instance()
+
+
+def test_discovered_chats_store_merges_forum_capability(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ DiscoveredChatsStore.reset_instance()
+ store = DiscoveredChatsStore.get_instance()
+ store.remember_chat(platform="telegram", chat_id="-1001", name="Core Group", chat_type="supergroup")
+ store.remember_chat(platform="telegram", chat_id="-1001", name="Core Group", chat_type="supergroup", is_forum=True)
+
+ chats = store.list_chats("telegram", include_private=False)
+
+ assert len(chats) == 1
+ assert chats[0].is_forum is True
+ DiscoveredChatsStore.reset_instance()
diff --git a/tests/test_session_handler_base_id.py b/tests/test_session_handler_base_id.py
index 5ce628771..335227582 100644
--- a/tests/test_session_handler_base_id.py
+++ b/tests/test_session_handler_base_id.py
@@ -16,13 +16,23 @@ class _Config:
class _Controller:
- def __init__(self, *, platform: str = "discord", dm_threads: bool = False) -> None:
+ def __init__(
+ self,
+ *,
+ platform: str = "discord",
+ dm_threads: bool = False,
+ channel_message_sessions: bool = True,
+ ) -> None:
self.config = _Config()
self.config.platform = platform
self.im_client = type(
"IM",
(),
- {"formatter": None, "should_use_thread_for_dm_session": lambda self: dm_threads},
+ {
+ "formatter": None,
+ "should_use_thread_for_dm_session": lambda self: dm_threads,
+ "should_use_message_id_for_channel_session": lambda self, context=None: channel_message_sessions,
+ },
)()
self.settings_manager = type("Settings", (), {"sessions": None})()
self.session_manager = object()
@@ -105,3 +115,16 @@ def test_channel_session_base_id_keeps_thread_or_message_behavior() -> None:
)
assert handler.get_base_session_id(context) == "discord_msg-999"
+
+
+def test_telegram_plain_group_session_base_id_uses_stable_channel_id() -> None:
+ handler = SessionHandler(_Controller(platform="telegram", channel_message_sessions=False))
+ context = MessageContext(
+ user_id="u-1",
+ channel_id="-100123",
+ message_id="42",
+ platform="telegram",
+ platform_specific={"is_dm": False, "chat_type": "supergroup"},
+ )
+
+ assert handler.get_base_session_id(context) == "telegram_-100123"
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
new file mode 100644
index 000000000..ae7072a4e
--- /dev/null
+++ b/tests/test_telegram_bot.py
@@ -0,0 +1,93 @@
+from __future__ import annotations
+
+import asyncio
+import sys
+from pathlib import Path
+from unittest.mock import AsyncMock, patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from config import paths
+from config.discovered_chats import DiscoveredChatsStore
+from modules.im import MessageContext
+from modules.im.telegram import TelegramBot
+from config.v2_config import TelegramConfig
+
+
+def test_normalize_command_text_strips_bot_mention() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ bot._bot_user = {"id": 1, "username": "vibe_remote_bot"}
+
+ assert bot._normalize_command_text("/start@vibe_remote_bot hello") == "/start hello"
+
+
+def test_plain_group_sessions_are_channel_scoped() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+
+ assert bot.should_use_message_id_for_channel_session() is False
+
+
+def test_forum_general_message_auto_creates_topic() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token", forum_auto_topic=True))
+ context = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ thread_id="1",
+ message_id="77",
+ platform="telegram",
+ platform_specific={"chat_type": "supergroup", "is_topic_message": True},
+ )
+ message = {
+ "from": {"first_name": "Alex"},
+ "is_topic_message": True,
+ "message_thread_id": 1,
+ }
+
+ with patch(
+ "modules.im.telegram.telegram_api.create_forum_topic",
+ new=AsyncMock(return_value={"result": {"message_thread_id": 88}}),
+ ):
+ with patch.object(bot, "send_message", new=AsyncMock(return_value="1")):
+ topic_context = asyncio.run(bot.start_new_topic_session(context, seed_text="Investigate this bug", message=message))
+
+ assert topic_context is not None
+ assert topic_context.thread_id == "88"
+
+
+def test_should_auto_create_topic_only_for_general_topic_messages() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token", forum_auto_topic=True))
+ context = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ thread_id="1",
+ message_id="77",
+ platform="telegram",
+ platform_specific={"chat_type": "supergroup"},
+ )
+
+ assert bot._should_auto_create_topic(context, {"is_topic_message": True}, "hello") is True
+ assert bot._should_auto_create_topic(context, {"is_topic_message": True, "reply_to_message": {"message_id": 1}}, "hello") is False
+ assert bot._should_auto_create_topic(context, {"is_topic_message": True}, "/start") is False
+
+
+def test_build_message_context_records_discovered_chat(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ DiscoveredChatsStore.reset_instance()
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+
+ context = bot._build_message_context(
+ {
+ "message_id": 77,
+ "chat": {"id": -100123, "type": "supergroup", "title": "Core Forum"},
+ "from": {"id": 42},
+ "is_topic_message": True,
+ "message_thread_id": 1,
+ }
+ )
+
+ assert context is not None
+ chats = DiscoveredChatsStore.get_instance().list_chats("telegram", include_private=False)
+ assert len(chats) == 1
+ assert chats[0].chat_id == "-100123"
+ assert chats[0].is_forum is True
+ DiscoveredChatsStore.reset_instance()
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 5ad30464b..147cef078 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -2,6 +2,8 @@ import json
import pytest
+from config import paths
+from config.discovered_chats import DiscoveredChatsStore
from vibe import api
from vibe.opencode_config import parse_jsonc_object
@@ -178,7 +180,6 @@ def test_install_codex_detects_binary_via_npm_prefix(monkeypatch, tmp_path):
assert calls[0][0] == [str(npm_path), "install", "-g", "@openai/codex"]
assert calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(npm_path.parent)
-
def test_setup_opencode_permission_preserves_existing_json_fields(monkeypatch, tmp_path):
config_path = tmp_path / ".config" / "opencode" / "opencode.json"
config_path.parent.mkdir(parents=True, exist_ok=True)
@@ -490,3 +491,32 @@ def test_parse_jsonc_object_rejects_invalid_jsonc():
}
}"""
)
+
+
+def test_telegram_auth_test_returns_response(monkeypatch):
+ async def fake_get_me(bot_token: str):
+ assert bot_token == "123456:test-token"
+ return {"id": 1, "username": "vibe_remote_bot"}
+
+ monkeypatch.setattr(api, "_telegram_get_me", fake_get_me)
+
+ result = api.telegram_auth_test("123456:test-token")
+
+ assert result["ok"] is True
+ assert result["response"]["username"] == "vibe_remote_bot"
+
+
+def test_telegram_list_chats_returns_discovered_groups(tmp_path, monkeypatch):
+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
+ DiscoveredChatsStore.reset_instance()
+ store = DiscoveredChatsStore.get_instance()
+ store.remember_chat(platform="telegram", chat_id="-1001", name="Core Group", chat_type="supergroup")
+ store.remember_chat(platform="telegram", chat_id="42", name="Alex", chat_type="private", is_private=True)
+
+ result = api.telegram_list_chats()
+
+ assert result["ok"] is True
+ assert [chat["id"] for chat in result["channels"]] == ["-1001"]
+ assert result["summary"]["visible_count"] == 1
+ assert result["summary"]["hidden_private_count"] == 1
+ DiscoveredChatsStore.reset_instance()
diff --git a/tests/test_v2_compat_platforms.py b/tests/test_v2_compat_platforms.py
index a1b59810f..fc7754d0e 100644
--- a/tests/test_v2_compat_platforms.py
+++ b/tests/test_v2_compat_platforms.py
@@ -15,6 +15,7 @@ from config.v2_config import (
PlatformsConfig,
RuntimeConfig,
SlackConfig,
+ TelegramConfig,
UiConfig,
UpdateConfig,
V2Config,
@@ -45,3 +46,29 @@ def test_to_app_config_preserves_enabled_platforms():
assert compat.platform == "discord"
assert compat.platforms == {"enabled": ["slack", "discord"], "primary": "discord"}
assert compat.enabled_platforms() == ["slack", "discord"]
+
+
+def test_to_app_config_preserves_telegram_config():
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ platform="telegram",
+ platforms=PlatformsConfig(enabled=["telegram"], primary="telegram"),
+ slack=SlackConfig(bot_token="", app_token=None, signing_secret=None, team_id=None, team_name=None, app_id=None),
+ runtime=RuntimeConfig(default_cwd=".", log_level="INFO"),
+ agents=AgentsConfig(
+ default_backend="opencode",
+ opencode=OpenCodeConfig(enabled=True, cli_path="opencode"),
+ claude=ClaudeConfig(enabled=True, cli_path="claude"),
+ codex=CodexConfig(enabled=False, cli_path="codex"),
+ ),
+ telegram=TelegramConfig(bot_token="123456:test-token", require_mention=True, forum_auto_topic=True),
+ ui=UiConfig(),
+ update=UpdateConfig(),
+ )
+
+ compat = to_app_config(config)
+
+ assert compat.platform == "telegram"
+ assert compat.telegram is not None
+ assert compat.telegram.bot_token == "123456:test-token"
diff --git a/tests/test_v2_paths.py b/tests/test_v2_paths.py
index b702f5896..766d87cac 100644
--- a/tests/test_v2_paths.py
+++ b/tests/test_v2_paths.py
@@ -7,6 +7,7 @@ def test_paths_are_under_home():
assert paths.get_config_path().parent == paths.get_config_dir()
assert paths.get_settings_path().parent == paths.get_state_dir()
assert paths.get_sessions_path().parent == paths.get_state_dir()
+ assert paths.get_discovered_chats_path().parent == paths.get_state_dir()
def test_ensure_data_dirs(tmp_path, monkeypatch):
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 1f105d612..9a139d580 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -8,7 +8,7 @@ import { LanguageSwitcher } from './LanguageSwitcher';
import { VersionBadge } from './VersionBadge';
import clsx from 'clsx';
import logoImg from '../assets/logo.png';
-import { getEnabledPlatforms } from '../lib/platforms';
+import { getEnabledPlatforms, platformSupportsChannels } from '../lib/platforms';
const NavItem = ({ to, icon: Icon, children }: { to: string; icon: any; children: React.ReactNode }) => (
<NavLink
@@ -37,7 +37,7 @@ export const AppShell: React.FC = () => {
}, []);
const isRunning = status.state === 'running';
- const hasChannelPlatforms = enabledPlatforms.some((platform) => platform !== 'wechat');
+ const hasChannelPlatforms = enabledPlatforms.some(platformSupportsChannels);
if (location.pathname === '/setup') {
return <Outlet />;
diff --git a/ui/src/components/Dashboard.tsx b/ui/src/components/Dashboard.tsx
index e314c1252..6f238bdb9 100644
--- a/ui/src/components/Dashboard.tsx
+++ b/ui/src/components/Dashboard.tsx
@@ -38,6 +38,7 @@ export const Dashboard: React.FC = () => {
reply_enhancements: newConfig.reply_enhancements,
slack: newConfig.slack,
discord: newConfig.discord,
+ telegram: newConfig.telegram,
lark: newConfig.lark,
wechat: newConfig.wechat,
agents: newConfig.agents,
diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsx
index e88d9d0d3..04ed779d2 100644
--- a/ui/src/components/Wizard.tsx
+++ b/ui/src/components/Wizard.tsx
@@ -7,6 +7,7 @@ import { PlatformSelection } from './steps/PlatformSelection';
import { AgentDetection } from './steps/AgentDetection';
import { SlackConfig } from './steps/SlackConfig';
import { DiscordConfig } from './steps/DiscordConfig';
+import { TelegramConfig } from './steps/TelegramConfig';
import { LarkConfig } from './steps/LarkConfig';
import { WeChatConfig } from './steps/WeChatConfig';
import { ChannelList } from './steps/ChannelList';
@@ -43,6 +44,13 @@ const buildConfigPayload = (data: any) => {
guild_denylist: data.discord?.guild_denylist || [],
require_mention: data.discord?.require_mention || false,
},
+ telegram: {
+ ...data.telegram,
+ bot_token: data.telegram?.bot_token || '',
+ require_mention: data.telegram?.require_mention ?? true,
+ forum_auto_topic: data.telegram?.forum_auto_topic ?? true,
+ use_webhook: data.telegram?.use_webhook ?? false,
+ },
lark: {
...data.lark,
app_id: data.lark?.app_id || '',
@@ -118,6 +126,8 @@ export const Wizard: React.FC = () => {
const platformSteps = enabledPlatforms.map((platform) => {
const component = platform === 'discord'
? DiscordConfig
+ : platform === 'telegram'
+ ? TelegramConfig
: platform === 'lark'
? LarkConfig
: platform === 'wechat'
@@ -208,6 +218,7 @@ export const Wizard: React.FC = () => {
mergedData.agents ||
mergedData.slack ||
mergedData.discord ||
+ mergedData.telegram ||
mergedData.lark ||
mergedData.wechat ||
mergedData.mode ||
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index 6988d66dc..f32e0dfbe 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -55,6 +55,13 @@ interface ChannelConfig {
require_mention?: boolean | null; // null=use global default, true=require, false=don't require
}
+interface TelegramDiscoverySummary {
+ discovered_count: number;
+ visible_count: number;
+ hidden_private_count: number;
+ forum_count: number;
+}
+
export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBack, isPage, forcedPlatform, wizardPlatforms }) => {
const { t } = useTranslation();
const api = useApi();
@@ -81,6 +88,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const [selectedModels, setSelectedModels] = useState<Record<string, string>>({});
const [guilds, setGuilds] = useState<any[]>([]);
const [selectedGuild, setSelectedGuild] = useState<string>(data.discord?.guild_allowlist?.[0] || '');
+ const [telegramSummary, setTelegramSummary] = useState<TelegramDiscoverySummary | null>(null);
// Directory browser state — tracks which channel's cwd picker is open
const [browsingCwdFor, setBrowsingCwdFor] = useState<string | null>(null);
@@ -150,6 +158,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
setWizardActivePlatform(newPlatform);
setChannels([]);
setBrowseAll(false);
+ setTelegramSummary(null);
};
useEffect(() => {
@@ -161,6 +170,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}, [api, isPage, platform]);
const botToken = platform === 'discord'
? (config.discord?.bot_token || data.discord?.bot_token || '')
+ : platform === 'telegram'
+ ? (config.telegram?.bot_token || data.telegram?.bot_token || '')
: platform === 'lark'
? '' // Lark uses app_id + app_secret, not bot_token
: (config.slack?.bot_token || config.slackBotToken || '');
@@ -207,6 +218,12 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
if (result.ok) {
setChannels(result.channels || []);
}
+ } else if (platform === 'telegram') {
+ const result = await api.telegramChats(false);
+ if (result.ok) {
+ setChannels(result.channels || []);
+ setTelegramSummary(result.summary || null);
+ }
} else if (platform === 'discord') {
if (!selectedGuild) {
setLoading(false);
@@ -452,10 +469,37 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
// Sort channels: enabled channels first
const sortedChannels = React.useMemo(() => {
- return [...channels].sort((a, b) =>
- Number(isChannelEnabled(b.id)) - Number(isChannelEnabled(a.id))
- );
- }, [channels, configs]);
+ return [...channels].sort((a, b) => {
+ const enabledDelta = Number(isChannelEnabled(b.id)) - Number(isChannelEnabled(a.id));
+ if (enabledDelta !== 0) return enabledDelta;
+
+ if (platform === 'telegram') {
+ const topicDelta = Number(Boolean(b.supports_topics)) - Number(Boolean(a.supports_topics));
+ if (topicDelta !== 0) return topicDelta;
+
+ const rank = (channel: any) => {
+ if (channel.supports_topics) return 3;
+ if (channel.type === 'supergroup') return 2;
+ if (channel.type === 'group') return 1;
+ return 0;
+ };
+ const rankDelta = rank(b) - rank(a);
+ if (rankDelta !== 0) return rankDelta;
+
+ const timeDelta = (Date.parse(b.last_seen_at || '') || 0) - (Date.parse(a.last_seen_at || '') || 0);
+ if (timeDelta !== 0) return timeDelta;
+ }
+
+ return String(a.name || a.id).localeCompare(String(b.name || b.id));
+ });
+ }, [channels, configs, platform]);
+
+ const formatTelegramLastSeen = (value?: string) => {
+ if (!value) return '';
+ const parsed = new Date(value);
+ if (Number.isNaN(parsed.getTime())) return '';
+ return parsed.toLocaleString();
+ };
const navigate = useNavigate();
@@ -548,7 +592,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
</div>
<button
onClick={async () => {
- const key = platform as 'slack' | 'discord' | 'lark' | 'wechat';
+ const key = platform as 'slack' | 'discord' | 'telegram' | 'lark' | 'wechat';
const current = !!(config as any)[key]?.require_mention;
const updated = {
...config,
@@ -584,7 +628,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
>
<RefreshCw size={14} className={loading ? 'animate-spin' : ''} /> {t('channelList.refreshList')}
</button>
- {!browseAll && platform !== 'lark' && (
+ {!browseAll && !['lark', 'telegram'].includes(platform) && (
<button
onClick={() => loadChannels(true)}
disabled={loadingAll}
@@ -603,7 +647,13 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{t('channelList.cantFindChannel')}
</span>
<span className="absolute bottom-full left-0 mb-2 px-3 py-2 bg-text text-bg text-xs rounded shadow-lg opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 w-64 whitespace-normal">
- {platform === 'discord' ? t('channelList.discordInviteBotHint') : platform === 'lark' ? t('channelList.larkInviteBotHint') : t('channelList.inviteBotHint')}
+ {platform === 'discord'
+ ? t('channelList.discordInviteBotHint')
+ : platform === 'lark'
+ ? t('channelList.larkInviteBotHint')
+ : platform === 'telegram'
+ ? t('channelList.telegramInviteBotHint')
+ : t('channelList.inviteBotHint')}
</span>
</span>
{channels.length === 0 && !loading && (
@@ -633,6 +683,19 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
<span className="text-xs text-muted">{t('channelList.accessPolicyHint')}</span>
</div>
)}
+ {platform === 'telegram' && (
+ <div className="rounded-lg border border-accent/20 bg-accent/5 p-3">
+ <div className="text-sm font-medium text-text">{t('channelList.telegramDiscoveryTitle')}</div>
+ <div className="mt-1 text-sm text-muted">{t('channelList.telegramDiscoveryInfo')}</div>
+ <div className="mt-2 text-xs text-muted">
+ {t('channelList.telegramDiscoveryStats', {
+ visible: telegramSummary?.visible_count || 0,
+ forum: telegramSummary?.forum_count || 0,
+ hidden: telegramSummary?.hidden_private_count || 0,
+ })}
+ </div>
+ </div>
+ )}
</div>
<div className="flex-1 overflow-y-auto border border-border rounded-xl divide-y divide-border bg-panel shadow-sm">
@@ -641,6 +704,12 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{t('channelList.addTokenFirst')}
</div>
)}
+ {!loading && channels.length === 0 && platform === 'telegram' && !!botToken && (
+ <div className="p-8 text-center">
+ <div className="text-sm font-medium text-text">{t('channelList.telegramDiscoveryEmptyTitle')}</div>
+ <div className="mt-2 text-sm text-muted">{t('channelList.telegramDiscoveryEmptyDesc')}</div>
+ </div>
+ )}
{sortedChannels.map((channel) => {
const rawConfig = configs[channel.id] || {};
const def = defaultConfig();
@@ -678,6 +747,14 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
<Hash size={14} className="text-muted" /> {channel.name}
</div>
<div className="text-xs text-muted font-mono">ID: {channel.id}</div>
+ {platform === 'telegram' && (channel.username || channel.last_seen_at) && (
+ <div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted">
+ {channel.username && <span>@{channel.username}</span>}
+ {channel.last_seen_at && (
+ <span>{t('channelList.telegramLastSeen', { time: formatTelegramLastSeen(channel.last_seen_at) })}</span>
+ )}
+ </div>
+ )}
</div>
</div>
<span
@@ -685,6 +762,14 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
'text-xs px-2 py-0.5 rounded-full border',
platform === 'discord'
? 'bg-neutral-100 text-text border-border'
+ : platform === 'telegram'
+ ? channel.supports_topics
+ ? 'bg-accent/10 text-accent border-accent/20'
+ : channel.type === 'supergroup'
+ ? 'bg-success/10 text-success border-success/20'
+ : channel.is_private
+ ? 'bg-warning/10 text-warning border-warning/20'
+ : 'bg-neutral-100 text-text border-border'
: channel.is_private
? 'bg-warning/10 text-warning border-warning/20'
: 'bg-success/10 text-success border-success/20'
@@ -692,6 +777,16 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
>
{platform === 'discord'
? (channel.type === 5 ? t('channelList.discordNews') : t('channelList.discordText'))
+ : platform === 'telegram'
+ ? channel.supports_topics
+ ? t('channelList.telegramForum')
+ : channel.type === 'supergroup'
+ ? t('channelList.telegramSupergroup')
+ : channel.type === 'group'
+ ? t('channelList.telegramGroup')
+ : channel.is_private
+ ? t('common.private')
+ : t('channelList.telegramChat')
: channel.is_private ? t('common.private') : t('common.public')}
</span>
</div>
@@ -751,6 +846,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
<option value="">
{t('common.default')} ({platform === 'discord'
? (config.discord?.require_mention ? t('channelList.mentionStatusOn') : t('channelList.mentionStatusOff'))
+ : platform === 'telegram'
+ ? (config.telegram?.require_mention ? t('channelList.mentionStatusOn') : t('channelList.mentionStatusOff'))
: platform === 'lark'
? (config.lark?.require_mention ? t('channelList.mentionStatusOn') : t('channelList.mentionStatusOff'))
: (config.slack?.require_mention ? t('channelList.mentionStatusOn') : t('channelList.mentionStatusOff'))})
diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsx
index 9b2f7c77b..9d2b221f6 100644
--- a/ui/src/components/steps/Summary.tsx
+++ b/ui/src/components/steps/Summary.tsx
@@ -33,6 +33,8 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {
platform,
platform === 'discord'
? (data.discord?.require_mention || false)
+ : platform === 'telegram'
+ ? (data.telegram?.require_mention ?? true)
: platform === 'lark'
? (data.lark?.require_mention || false)
: platform === 'wechat'
@@ -75,6 +77,10 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {
...data.discord,
require_mention: requireMentionByPlatform.discord ?? data.discord?.require_mention,
},
+ telegram: {
+ ...data.telegram,
+ require_mention: requireMentionByPlatform.telegram ?? data.telegram?.require_mention,
+ },
lark: {
...data.lark,
require_mention: requireMentionByPlatform.lark ?? data.lark?.require_mention,
@@ -205,6 +211,9 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {
<Section title={t('summary.discordGuild')} value={(data.discord?.guild_allowlist || [])[0] || t('summary.notSet')} />
</>
)}
+ {enabledPlatforms.includes('telegram') && (
+ <Section title={t('summary.telegramBotToken')} value={mask(data.telegram?.bot_token || '')} />
+ )}
{enabledPlatforms.includes('lark') && (
<Section title={t('summary.larkAppId')} value={mask(data.lark?.app_id || '')} />
)}
@@ -367,6 +376,13 @@ const buildConfigPayload = (data: any) => {
guild_denylist: data.discord?.guild_denylist || [],
require_mention: data.discord?.require_mention || false,
},
+ telegram: {
+ ...data.telegram,
+ bot_token: data.telegram?.bot_token || '',
+ require_mention: data.telegram?.require_mention ?? true,
+ forum_auto_topic: data.telegram?.forum_auto_topic ?? true,
+ use_webhook: data.telegram?.use_webhook ?? false,
+ },
lark: {
...data.lark,
app_id: data.lark?.app_id || '',
diff --git a/ui/src/components/steps/TelegramConfig.tsx b/ui/src/components/steps/TelegramConfig.tsx
new file mode 100644
index 000000000..726258d35
--- /dev/null
+++ b/ui/src/components/steps/TelegramConfig.tsx
@@ -0,0 +1,172 @@
+import React, { useMemo, useState } from 'react';
+import { Check, KeyRound, MessageSquare, RefreshCw, Shield, SplitSquareVertical } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+import { useApi } from '../../context/ApiContext';
+
+interface TelegramConfigProps {
+ data: any;
+ onNext: (data: any) => void;
+ onBack: () => void;
+}
+
+export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, onBack }) => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const [botToken, setBotToken] = useState(data.telegram?.bot_token || '');
+ const [requireMention, setRequireMention] = useState(data.telegram?.require_mention ?? true);
+ const [forumAutoTopic, setForumAutoTopic] = useState(data.telegram?.forum_auto_topic ?? true);
+ const [checking, setChecking] = useState(false);
+ const [authResult, setAuthResult] = useState<any>(null);
+
+ const isValid = useMemo(() => {
+ if (!botToken) return false;
+ if (authResult?.ok) return true;
+ return Boolean(data.telegram?.bot_token && botToken === data.telegram?.bot_token);
+ }, [authResult, botToken, data.telegram?.bot_token]);
+
+ const runAuthTest = async () => {
+ setChecking(true);
+ try {
+ const result = await api.telegramAuthTest(botToken);
+ setAuthResult(result);
+ } catch (err: any) {
+ setAuthResult({ ok: false, error: err?.message || 'Request failed' });
+ } finally {
+ setChecking(false);
+ }
+ };
+
+ return (
+ <div className="flex flex-col h-full max-w-2xl mx-auto">
+ <div className="mb-6">
+ <h2 className="text-3xl font-display font-bold text-text">{t('telegramConfig.title')}</h2>
+ <p className="text-muted mt-1">{t('telegramConfig.subtitle')}</p>
+ </div>
+
+ <div className="space-y-4 overflow-y-auto flex-1 pr-1">
+ <div className="bg-panel border border-border rounded-xl p-5 space-y-4">
+ <div>
+ <div className="text-sm font-medium text-text flex items-center gap-2">
+ <MessageSquare size={16} className="text-accent" />
+ {t('telegramConfig.buttonFirstTitle')}
+ </div>
+ <p className="text-sm text-muted mt-2">{t('telegramConfig.buttonFirstDesc')}</p>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ <div className="rounded-lg border border-border bg-bg p-4">
+ <div className="text-sm font-medium text-text">{t('telegramConfig.sessionPlainTitle')}</div>
+ <p className="text-xs text-muted mt-2">{t('telegramConfig.sessionPlainDesc')}</p>
+ </div>
+ <div className="rounded-lg border border-border bg-bg p-4">
+ <div className="text-sm font-medium text-text">{t('telegramConfig.sessionForumTitle')}</div>
+ <p className="text-xs text-muted mt-2">{t('telegramConfig.sessionForumDesc')}</p>
+ </div>
+ </div>
+ </div>
+
+ <div className="bg-panel border border-border rounded-xl p-5 space-y-4">
+ <label className="text-sm font-medium text-text flex items-center gap-2">
+ <KeyRound size={16} className="text-accent" />
+ {t('telegramConfig.botToken')}
+ </label>
+ <input
+ type="password"
+ value={botToken}
+ onChange={(e) => {
+ setBotToken(e.target.value);
+ setAuthResult(null);
+ }}
+ placeholder={t('telegramConfig.botTokenPlaceholder')}
+ className="w-full bg-bg border border-border rounded-lg p-3 text-text focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent font-mono transition-colors"
+ />
+ <p className="text-xs text-muted">{t('telegramConfig.botTokenHint')}</p>
+
+ <div className="flex items-center gap-3">
+ <button
+ onClick={runAuthTest}
+ disabled={!botToken || checking}
+ className="px-4 py-2 bg-accent text-white rounded-lg flex items-center gap-2 transition-colors font-medium shadow-sm hover:bg-accent/90 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {checking ? <RefreshCw size={16} className="animate-spin" /> : <Shield size={16} />}
+ {t('telegramConfig.validateToken')}
+ </button>
+ {authResult && (
+ <span
+ className={clsx(
+ 'flex items-center gap-2 text-sm font-medium px-3 py-1.5 rounded-lg border',
+ authResult.ok ? 'text-success bg-success/10 border-success/20' : 'text-danger bg-danger/10 border-danger/20'
+ )}
+ >
+ {authResult.ok ? (
+ <>
+ <Check size={14} />
+ <span>{t('telegramConfig.tokenValidated')}</span>
+ </>
+ ) : (
+ <span>{t('telegramConfig.authFailed')}: {authResult.error}</span>
+ )}
+ </span>
+ )}
+ </div>
+ </div>
+
+ <div className="bg-panel border border-border rounded-xl p-5 space-y-4">
+ <label className="flex items-start justify-between gap-4">
+ <div>
+ <div className="text-sm font-medium text-text">{t('telegramConfig.requireMention')}</div>
+ <p className="text-xs text-muted mt-1">{t('telegramConfig.requireMentionHint')}</p>
+ </div>
+ <input
+ type="checkbox"
+ checked={requireMention}
+ onChange={(e) => setRequireMention(e.target.checked)}
+ className="mt-1 h-4 w-4"
+ />
+ </label>
+ <label className="flex items-start justify-between gap-4">
+ <div className="pr-4">
+ <div className="text-sm font-medium text-text flex items-center gap-2">
+ <SplitSquareVertical size={16} className="text-accent" />
+ {t('telegramConfig.forumAutoTopic')}
+ </div>
+ <p className="text-xs text-muted mt-1">{t('telegramConfig.forumAutoTopicHint')}</p>
+ </div>
+ <input
+ type="checkbox"
+ checked={forumAutoTopic}
+ onChange={(e) => setForumAutoTopic(e.target.checked)}
+ className="mt-1 h-4 w-4"
+ />
+ </label>
+ </div>
+ </div>
+
+ <div className="mt-auto flex justify-between pt-6 border-t border-border">
+ <button onClick={onBack} className="px-6 py-2 text-muted hover:text-text font-medium transition-colors">
+ {t('common.back')}
+ </button>
+ <button
+ onClick={() =>
+ onNext({
+ platform: 'telegram',
+ telegram: {
+ ...(data.telegram || {}),
+ bot_token: botToken,
+ require_mention: requireMention,
+ forum_auto_topic: forumAutoTopic,
+ },
+ })
+ }
+ disabled={!isValid}
+ className={clsx(
+ 'px-8 py-3 rounded-lg font-medium transition-colors shadow-sm',
+ isValid ? 'bg-accent hover:bg-accent/90 text-white' : 'bg-neutral-200 text-muted cursor-not-allowed'
+ )}
+ >
+ {t('common.continue')}
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index a672cedea..50da1203e 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -22,6 +22,8 @@ export type ApiContextType = {
discordAuthTest: (botToken: string) => Promise<any>;
discordGuilds: (botToken: string) => Promise<any>;
discordChannels: (botToken: string, guildId: string) => Promise<any>;
+ telegramAuthTest: (botToken: string) => Promise<any>;
+ telegramChats: (includePrivate?: boolean) => Promise<any>;
larkAuthTest: (appId: string, appSecret: string, domain?: string) => Promise<any>;
larkChats: (appId: string, appSecret: string, domain?: string) => Promise<any>;
larkTempWsStart: (appId: string, appSecret: string, domain?: string) => Promise<any>;
@@ -148,6 +150,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
discordAuthTest: (botToken) => postJson('/discord/auth_test', { bot_token: botToken }),
discordGuilds: (botToken) => postJson('/discord/guilds', { bot_token: botToken }),
discordChannels: (botToken, guildId) => postJson('/discord/channels', { bot_token: botToken, guild_id: guildId }),
+ telegramAuthTest: (botToken) => postJson('/telegram/auth_test', { bot_token: botToken }),
+ telegramChats: (includePrivate) => postJson('/telegram/chats', { include_private: includePrivate || false }),
larkAuthTest: (appId, appSecret, domain) => postJson('/lark/auth_test', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu' }),
larkChats: (appId, appSecret, domain) => postJson('/lark/chats', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu' }),
larkTempWsStart: (appId, appSecret, domain) => postJson('/lark/temp_ws/start', { app_id: appId, app_secret: appSecret, domain: domain || 'feishu' }),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 6829d2bd2..b2b85ce6b 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -79,6 +79,10 @@
"title": "Discord",
"desc": "Connect a Discord bot and choose a guild."
},
+ "telegram": {
+ "title": "Telegram",
+ "desc": "Connect a Telegram bot for DMs, groups, and forum topics."
+ },
"lark": {
"title": "Lark",
"desc": "Connect to Feishu/Lark workspace for team collaboration"
@@ -136,6 +140,26 @@
"dmTroubleshoot2": "In server Privacy Settings, enable \"Allow direct messages from server members\".",
"dmTroubleshoot3": "Ensure you didn't block the bot account."
},
+ "telegramConfig": {
+ "title": "Telegram Configuration",
+ "subtitle": "Connect a Telegram bot with button-first interaction and topic-aware sessions.",
+ "buttonFirstTitle": "Button-first interaction",
+ "buttonFirstDesc": "Telegram should behave more like Discord than a command-first bot. Commands remain available as fallback entrypoints.",
+ "sessionPlainTitle": "Plain chat session",
+ "sessionPlainDesc": "Direct messages and plain groups keep one session by default. Users explicitly start a new one with the New Session button.",
+ "sessionForumTitle": "Forum topic session",
+ "sessionForumDesc": "In forum-enabled supergroups, new top-level messages can branch into dedicated topics that each hold one session.",
+ "botToken": "Bot Token",
+ "botTokenPlaceholder": "Paste your Telegram bot token",
+ "botTokenHint": "Create a bot with @BotFather, then paste the token here.",
+ "validateToken": "Validate Token",
+ "tokenValidated": "Token validated",
+ "authFailed": "Validation failed",
+ "requireMention": "Require explicit bot targeting in groups",
+ "requireMentionHint": "When enabled, the bot responds in groups only when explicitly addressed by command, mention, or reply.",
+ "forumAutoTopic": "Forum auto-topic mode",
+ "forumAutoTopicHint": "For forum-enabled supergroups, new top-level messages can automatically create a new topic that becomes the session container."
+ },
"larkConfig": {
"title": "Configure Lark",
"subtitle": "Set up your Lark/Feishu bot in a few steps",
@@ -307,11 +331,22 @@
"inviteBotHint": "Invite the bot to your channel first:\n1. Open the channel, click ⚙️ Settings → Integrations → Add apps\n2. Or type /invite @YourBotName in the channel",
"discordInviteBotHint": "Add the bot to your guild and grant access to the channel.",
"larkInviteBotHint": "Add the bot to a group chat: Open the group → Settings → Bots → Add Bot.",
+ "telegramInviteBotHint": "Send a message from the Telegram group or forum to the bot first, then refresh this list.",
"wechatInviteBotHint": "Send a message to your WeChat bot account to start a conversation.",
"guild": "Guild",
"guildPlaceholder": "Select a guild",
"discordText": "Text",
"discordNews": "News",
+ "telegramForum": "Forum",
+ "telegramSupergroup": "Supergroup",
+ "telegramGroup": "Group",
+ "telegramChat": "Chat",
+ "telegramDiscoveryTitle": "Telegram uses discovered chats",
+ "telegramDiscoveryInfo": "This page shows Telegram groups and forums that the bot has already seen from incoming messages. Direct messages stay hidden here.",
+ "telegramDiscoveryStats": "{{visible}} visible chats · {{forum}} forums · {{hidden}} hidden DMs",
+ "telegramDiscoveryEmptyTitle": "No Telegram chats discovered yet",
+ "telegramDiscoveryEmptyDesc": "Send a message in any Telegram group or forum where the bot is present, then refresh this page.",
+ "telegramLastSeen": "Last seen {{time}}",
"enabledCount": "{{count}} enabled",
"accessPolicy": "Access Policy",
"accessPolicyHint": "Groups are enabled only when checked below.",
@@ -353,6 +388,7 @@
"slackBotToken": "Slack Bot Token",
"slackAppToken": "Slack App Token",
"discordBotToken": "Discord Bot Token",
+ "telegramBotToken": "Telegram Bot Token",
"larkAppId": "Lark App ID",
"wechatBotToken": "WeChat Bot Token",
"discordGuild": "Discord Guild",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index bd0d38286..3172c2df1 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -79,6 +79,10 @@
"title": "Discord",
"desc": "连接 Discord 机器人并选择服务器。"
},
+ "telegram": {
+ "title": "Telegram",
+ "desc": "连接 Telegram 机器人,支持私聊、群组和 forum topic。"
+ },
"lark": {
"title": "飞书",
"desc": "连接飞书工作区,实现团队协作"
@@ -136,6 +140,26 @@
"dmTroubleshoot2": "在服务器隐私设置中开启「允许来自服务器成员的私信」。",
"dmTroubleshoot3": "确认你没有屏蔽该机器人账号。"
},
+ "telegramConfig": {
+ "title": "Telegram 配置",
+ "subtitle": "连接 Telegram 机器人,采用按钮优先交互,并为 topic 会话做好准备。",
+ "buttonFirstTitle": "按钮优先交互",
+ "buttonFirstDesc": "Telegram 的体验应更接近 Discord,而不是 command-first 机器人。命令只作为兜底入口保留。",
+ "sessionPlainTitle": "普通会话模式",
+ "sessionPlainDesc": "私聊和普通群默认保持单一 session,只有用户点击 New Session 才会切换到新 session。",
+ "sessionForumTitle": "Forum topic 会话模式",
+ "sessionForumDesc": "在启用 forum 的 supergroup 中,新的顶层消息可以自动分叉到独立 topic,每个 topic 承载一个 session。",
+ "botToken": "机器人令牌",
+ "botTokenPlaceholder": "粘贴 Telegram 机器人令牌",
+ "botTokenHint": "先通过 @BotFather 创建机器人,再把令牌粘贴到这里。",
+ "validateToken": "验证令牌",
+ "tokenValidated": "令牌验证成功",
+ "authFailed": "验证失败",
+ "requireMention": "群组中需要显式触发",
+ "requireMentionHint": "开启后,机器人只会在群组中响应显式 command、@提及或回复。",
+ "forumAutoTopic": "Forum 自动建 Topic",
+ "forumAutoTopicHint": "对启用了 forum 的 supergroup,新顶层消息可以自动创建新的 topic,并把它作为 session 容器。"
+ },
"larkConfig": {
"title": "配置飞书",
"subtitle": "几步完成飞书/Lark 机器人的配置",
@@ -307,11 +331,22 @@
"inviteBotHint": "请先将 Bot 邀请到频道:\n1. 打开频道,点击 ⚙️ 设置 → 集成 → 添加应用\n2. 或在频道中输入 /invite @你的Bot名称",
"discordInviteBotHint": "请确保机器人已加入服务器并具备访问频道的权限。",
"larkInviteBotHint": "将机器人添加到群聊:打开群 → 设置 → 群机器人 → 添加机器人。",
+ "telegramInviteBotHint": "先让 Telegram 群组或 forum 给机器人发过一条消息,再回来刷新列表。",
"wechatInviteBotHint": "向微信机器人账号发送消息即可开始对话。",
"guild": "服务器",
"guildPlaceholder": "选择服务器",
"discordText": "文本",
"discordNews": "公告",
+ "telegramForum": "Forum",
+ "telegramSupergroup": "Supergroup",
+ "telegramGroup": "群组",
+ "telegramChat": "会话",
+ "telegramDiscoveryTitle": "Telegram 这里只展示已发现会话",
+ "telegramDiscoveryInfo": "这里只有 bot 已经从入站消息里见过的 Telegram 群组和 forum。私聊不会在这里展示。",
+ "telegramDiscoveryStats": "{{visible}} 个可见会话 · {{forum}} 个 forum · {{hidden}} 个隐藏私聊",
+ "telegramDiscoveryEmptyTitle": "还没有发现任何 Telegram 会话",
+ "telegramDiscoveryEmptyDesc": "先在 bot 已加入的 Telegram 群组或 forum 里发一条消息,再回来刷新这个页面。",
+ "telegramLastSeen": "最近出现于 {{time}}",
"enabledCount": "已启用 {{count}} 个",
"accessPolicy": "访问策略",
"accessPolicyHint": "只有勾选的群组才会启用",
@@ -353,6 +388,7 @@
"slackBotToken": "Slack Bot 令牌",
"slackAppToken": "Slack App 令牌",
"discordBotToken": "Discord 机器人令牌",
+ "telegramBotToken": "Telegram 机器人令牌",
"larkAppId": "飞书 App ID",
"wechatBotToken": "微信 Bot Token",
"discordGuild": "Discord 服务器",
diff --git a/ui/src/lib/platforms.ts b/ui/src/lib/platforms.ts
index 095880b74..0afeffe53 100644
--- a/ui/src/lib/platforms.ts
+++ b/ui/src/lib/platforms.ts
@@ -1,4 +1,4 @@
-export const ALL_PLATFORMS = ['slack', 'discord', 'lark', 'wechat'] as const;
+export const ALL_PLATFORMS = ['slack', 'discord', 'telegram', 'lark', 'wechat'] as const;
export type PlatformName = (typeof ALL_PLATFORMS)[number];
@@ -25,4 +25,4 @@ export const getPrimaryPlatform = (data: any): PlatformName => {
return enabled[0] || 'slack';
};
-export const platformSupportsChannels = (platform: string): boolean => platform !== 'wechat';
+export const platformSupportsChannels = (platform: string): boolean => !['wechat'].includes(platform);
diff --git a/vibe/api.py b/vibe/api.py
index 9b6cc7fc7..b7ce09499 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -20,6 +20,7 @@ from config.v2_settings import (
_parse_routing,
_routing_to_dict,
)
+from config.discovered_chats import DiscoveredChatsStore
from config.v2_sessions import SessionsStore
from vibe.opencode_config import (
get_opencode_config_paths,
@@ -254,6 +255,7 @@ def config_to_payload(config: V2Config) -> dict:
"require_mention": config.slack.require_mention,
},
"discord": config.discord.__dict__ if config.discord else None,
+ "telegram": config.telegram.__dict__ if config.telegram else None,
"lark": config.lark.__dict__ if config.lark else None,
"wechat": config.wechat.__dict__ if config.wechat else None,
"runtime": {
@@ -429,6 +431,41 @@ def discord_auth_test(bot_token: str) -> dict:
return {"ok": False, "error": str(exc)}
+def telegram_auth_test(bot_token: str) -> dict:
+ try:
+ return {"ok": True, "response": asyncio.run(_telegram_get_me(bot_token))}
+ except Exception as exc:
+ return {"ok": False, "error": str(exc)}
+
+
+def telegram_list_chats(include_private: bool = False) -> dict:
+ store = DiscoveredChatsStore.get_instance()
+ all_chats = store.list_chats("telegram", include_private=True)
+ chats = all_chats if include_private else [chat for chat in all_chats if not chat.is_private]
+ return {
+ "ok": True,
+ "channels": [
+ {
+ "id": chat.chat_id,
+ "name": chat.name or chat.username or chat.chat_id,
+ "username": chat.username,
+ "type": chat.chat_type,
+ "is_private": chat.is_private,
+ "is_forum": chat.is_forum,
+ "supports_topics": chat.supports_topics,
+ "last_seen_at": chat.last_seen_at,
+ }
+ for chat in chats
+ ],
+ "summary": {
+ "discovered_count": len(all_chats),
+ "visible_count": len(chats),
+ "hidden_private_count": sum(1 for chat in all_chats if chat.is_private) if not include_private else 0,
+ "forum_count": sum(1 for chat in chats if chat.supports_topics),
+ },
+ }
+
+
def discord_list_guilds(bot_token: str) -> dict:
try:
data = _discord_api_get(bot_token, "users/@me/guilds")
@@ -477,6 +514,13 @@ def _discord_api_get(bot_token: str, path: str) -> dict:
return json.loads(payload)
+async def _telegram_get_me(bot_token: str) -> dict:
+ from modules.im import telegram_api
+
+ result = await telegram_api.get_me(bot_token)
+ return result.get("result") or {}
+
+
async def opencode_options_async(cwd: str) -> dict:
# Expand ~ to user home directory
expanded_cwd = os.path.expanduser(cwd)
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 82dbccc22..f563c8bf8 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -273,5 +273,9 @@
"systemDefault": "(System Default)",
"en": "English",
"zh": "\u4e2d\u6587"
+ },
+ "telegram": {
+ "autoTopicGeneralNotice": "Started a new topic for this request: {topic}. Continue there.",
+ "autoTopicIntro": "New session topic created: {topic}"
}
}
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 01aae9d71..72efd2c8c 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -273,5 +273,9 @@
"systemDefault": "(系统默认)",
"en": "English",
"zh": "中文"
+ },
+ "telegram": {
+ "autoTopicGeneralNotice": "已为这次请求创建新的 Topic:{topic},请在那里继续。",
+ "autoTopicIntro": "已创建新的会话 Topic:{topic}"
}
}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 656703ea3..205f64700 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -300,6 +300,23 @@ def discord_channels():
return jsonify(api.discord_list_channels(payload.get("bot_token", ""), payload.get("guild_id", "")))
[email protected]("/telegram/auth_test", methods=["POST"])
+def telegram_auth_test():
+ from vibe import api
+
+ payload = request.json or {}
+ result = api.telegram_auth_test(payload.get("bot_token", ""))
+ return jsonify(result)
+
+
[email protected]("/telegram/chats", methods=["POST"])
+def telegram_chats():
+ from vibe import api
+
+ payload = request.json or {}
+ return jsonify(api.telegram_list_chats(include_private=payload.get("include_private", False)))
+
+
@app.route("/lark/auth_test", methods=["POST"])
def lark_auth_test():
from vibe import api