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.

fix(telegram): polish interaction and setup flows

cyh1c8f53e482e5
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index 64cb811a4..b553b9772 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -74,6 +74,8 @@ class SettingsHandler(BaseHandler):
await self._handle_settings_slack(context)
elif platform == "discord":
await self._handle_settings_discord(context)
+ elif platform == "telegram":
+ await self._handle_settings_telegram(context)
elif platform == "lark":
await self._handle_settings_lark(context)
else:
@@ -209,6 +211,34 @@ class SettingsHandler(BaseHandler):
return
await self._handle_settings_traditional(context)
+ async def _handle_settings_telegram(self, context: MessageContext):
+ im_client = self._get_im_client(context)
+ settings_key = self._get_settings_key(context)
+ settings_manager = self._get_settings_manager(context)
+ user_settings = settings_manager.get_user_settings(settings_key)
+ message_types = settings_manager.get_available_message_types()
+ display_names = self._message_type_display_names()
+ current_require_mention = settings_manager.get_require_mention_override(settings_key)
+ global_require_mention = self.config.telegram.require_mention if self.config.telegram else True
+ current_language = self.config.language
+
+ if hasattr(im_client, "open_settings_modal"):
+ await im_client.run_on_client_loop(
+ im_client.open_settings_modal(
+ trigger_id=context,
+ user_settings=user_settings,
+ message_types=message_types,
+ display_names=display_names,
+ channel_id=context.channel_id,
+ current_require_mention=current_require_mention,
+ global_require_mention=global_require_mention,
+ current_language=current_language,
+ owner_user_id=context.user_id,
+ )
+ )
+ return
+ await self._handle_settings_traditional(context)
+
async def _handle_settings_lark(self, context: MessageContext):
"""Handle settings for Lark/Feishu using interactive form card."""
im_client = self._get_im_client(context)
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index cd16ef9e1..cfa224660 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -404,7 +404,7 @@ class ConsolidatedMessageDispatcher:
row.append(InlineButton(text=btn.text, callback_data=callback))
platform = context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platform
- rows = [[button] for button in row] if platform == "lark" else [row]
+ rows = [[button] for button in row] if platform in {"lark", "telegram"} else [row]
keyboard = InlineKeyboard(buttons=rows)
return await im_client.send_message_with_buttons(
context,
diff --git a/modules/im/formatters/telegram_formatter.py b/modules/im/formatters/telegram_formatter.py
index 6f754a173..a3d64cf17 100644
--- a/modules/im/formatters/telegram_formatter.py
+++ b/modules/im/formatters/telegram_formatter.py
@@ -1,25 +1,74 @@
-"""Telegram formatter.
+"""Telegram formatter with HTML rendering.
-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.
+The rest of the app emits standard Markdown-ish text (`**bold**`, backticks,
+links). Telegram is stricter than Slack/Discord, so we normalize that subset
+into Bot API HTML before sending.
"""
+from __future__ import annotations
+
+import html
+import re
+
from .base_formatter import BaseMarkdownFormatter
class TelegramFormatter(BaseMarkdownFormatter):
+ _CODE_BLOCK_RE = re.compile(r"```(?:([\w.+-]+)\n)?(.*?)```", re.DOTALL)
+ _INLINE_CODE_RE = re.compile(r"`([^`\n]+)`")
+ _LINK_RE = re.compile(r"\[([^\]]+)\]\((https?://[^\s)]+)\)")
+ _BOLD_RE = re.compile(r"\*\*(.+?)\*\*", re.DOTALL)
+ _ITALIC_RE = re.compile(r"(?<!\*)\*([^*\n]+)\*(?!\*)")
+ _STRIKE_RE = re.compile(r"~~(.+?)~~", re.DOTALL)
+
def format_bold(self, text: str) -> str:
- return text
+ return f"**{text}**"
def format_italic(self, text: str) -> str:
- return text
+ return f"*{text}*"
def format_strikethrough(self, text: str) -> str:
- return text
+ return f"~~{text}~~"
def format_link(self, text: str, url: str) -> str:
- return f"{text} ({url})"
+ return f"[{text}]({url})"
def escape_special_chars(self, text: str) -> str:
return text
+
+ def render(self, text: str) -> str:
+ if not text:
+ return ""
+
+ placeholders: dict[str, str] = {}
+
+ def stash(replacement: str) -> str:
+ token = f"@@TG{len(placeholders)}@@"
+ placeholders[token] = replacement
+ return token
+
+ def render_code_block(match: re.Match[str]) -> str:
+ language = (match.group(1) or "").strip()
+ code = html.escape(match.group(2).strip("\n"))
+ if language:
+ return f'<pre><code class="language-{html.escape(language, quote=True)}">{code}</code></pre>'
+ return f"<pre><code>{code}</code></pre>"
+
+ def render_inline_code(match: re.Match[str]) -> str:
+ return f"<code>{html.escape(match.group(1))}</code>"
+
+ rendered = self._CODE_BLOCK_RE.sub(lambda m: stash(render_code_block(m)), text)
+ rendered = self._INLINE_CODE_RE.sub(lambda m: stash(render_inline_code(m)), rendered)
+ rendered = html.escape(rendered)
+
+ rendered = self._LINK_RE.sub(
+ lambda m: f'<a href="{html.escape(m.group(2), quote=True)}">{m.group(1)}</a>',
+ rendered,
+ )
+ rendered = self._BOLD_RE.sub(r"<b>\1</b>", rendered)
+ rendered = self._STRIKE_RE.sub(r"<s>\1</s>", rendered)
+ rendered = self._ITALIC_RE.sub(r"<i>\1</i>", rendered)
+
+ for token, replacement in placeholders.items():
+ rendered = rendered.replace(token, replacement)
+ return rendered
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
index b9f7c03b8..e4f031269 100644
--- a/modules/im/telegram.py
+++ b/modules/im/telegram.py
@@ -12,7 +12,7 @@ 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 vibe.i18n import get_supported_languages, t as i18n_t
from modules.agents.native_sessions import AgentNativeSessionService, NativeResumeSession
from .base import BaseIMClient, FileAttachment, MessageContext, InlineButton, InlineKeyboard
@@ -70,6 +70,16 @@ class _TelegramQuestionState:
index: int = 0
+@dataclass
+class _TelegramSettingsState:
+ message_id: str
+ show_message_types: list[str]
+ current_require_mention: Optional[bool]
+ global_require_mention: bool
+ current_language: str
+ is_dm: bool
+
+
class TelegramBot(BaseIMClient):
"""Telegram adapter using Bot API long polling."""
@@ -89,6 +99,7 @@ class TelegramBot(BaseIMClient):
self._resume_states: dict[str, _TelegramResumeSessionState] = {}
self._routing_states: dict[str, _TelegramRoutingState] = {}
self._question_states: dict[str, _TelegramQuestionState] = {}
+ self._settings_states: dict[str, _TelegramSettingsState] = {}
def set_settings_manager(self, settings_manager):
self.settings_manager = settings_manager
@@ -115,7 +126,7 @@ class TelegramBot(BaseIMClient):
return i18n_t(key, lang, **kwargs)
def get_default_parse_mode(self) -> Optional[str]:
- return None
+ return "HTML"
def should_use_thread_for_reply(self) -> bool:
return True
@@ -124,7 +135,7 @@ class TelegramBot(BaseIMClient):
return False
def format_markdown(self, text: str) -> str:
- return text
+ return self.formatter.render(text)
def register_handlers(self):
return None
@@ -171,16 +182,30 @@ class TelegramBot(BaseIMClient):
if context is None:
return
- text = message.get("text") or message.get("caption") or ""
- text = self._normalize_command_text(text)
+ raw_text = message.get("text") or message.get("caption") or ""
+ text = self._normalize_command_text(raw_text)
if self._is_command_for_other_bot(text):
return
+ explicitly_addressed = self._is_explicitly_addressed(message, text)
+
+ effective_require_mention = self.config.require_mention
+ if self.settings_manager is not None and not context.platform_specific.get("is_dm", False):
+ try:
+ effective_require_mention = self.settings_manager.get_require_mention(
+ context.channel_id,
+ global_default=self.config.require_mention,
+ )
+ except Exception:
+ logger.debug("Failed to resolve Telegram effective require_mention", exc_info=True)
+
+ text = self._strip_leading_bot_mention(message, text)
+
if await self._consume_cwd_prompt(context, text):
return
- if self.config.require_mention and not context.platform_specific.get("is_dm", False):
- if not self._is_explicitly_addressed(message, text):
+ if effective_require_mention and not context.platform_specific.get("is_dm", False):
+ if not explicitly_addressed:
return
denial = self.check_authorization(
@@ -226,14 +251,28 @@ class TelegramBot(BaseIMClient):
logger.warning("Telegram forum auto-topic failed, falling back to current topic: %s", err, exc_info=True)
return context
+ def _is_forum_chat(self, context: MessageContext, message: Optional[dict[str, Any]] = None) -> bool:
+ payload = context.platform_specific or {}
+ chat = (message or {}).get("chat") or {}
+ return (
+ bool(payload.get("is_forum"))
+ or bool(payload.get("is_topic_message"))
+ or bool((message or {}).get("is_topic_message"))
+ or bool(chat.get("is_forum"))
+ )
+
+ def _is_general_forum_context(self, context: MessageContext, message: dict[str, Any]) -> bool:
+ if not self._is_forum_chat(context, message):
+ return False
+ thread_id = str(context.thread_id or message.get("message_thread_id") or "").strip()
+ return thread_id in {"", "1"}
+
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":
+ if not self._is_general_forum_context(context, message):
return False
if message.get("reply_to_message"):
return False
@@ -264,7 +303,7 @@ class TelegramBot(BaseIMClient):
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"):
+ if not context.thread_id and not self._is_forum_chat(context, message):
return None
topic_name = self._derive_topic_title(seed_text, message or {})
@@ -284,12 +323,13 @@ class TelegramBot(BaseIMClient):
platform_specific={
**payload,
"is_topic_message": True,
+ "is_forum": True,
"auto_topic_created": True,
"topic_name": topic_name,
},
)
- if str(context.thread_id or "") == "1":
+ if self._is_general_forum_context(context, message or {}):
try:
await self.send_message(
context,
@@ -299,14 +339,6 @@ class TelegramBot(BaseIMClient):
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:
@@ -339,7 +371,7 @@ class TelegramBot(BaseIMClient):
}
callback_data = str(payload.get("data", ""))
primary_action = self._resolve_callback_action(callback_data)
- is_internal_callback = callback_data.startswith(("tg_cwd:", "tg_resume:", "tg_route:", "tg_question:"))
+ is_internal_callback = callback_data.startswith(("tg_cwd:", "tg_resume:", "tg_route:", "tg_question:", "tg_settings:"))
if is_internal_callback:
auth_result = self.check_authorization(
user_id=context.user_id,
@@ -388,6 +420,9 @@ class TelegramBot(BaseIMClient):
if callback_data.startswith("tg_route:"):
await self._handle_routing_callback(context, callback_data)
return True
+ if callback_data.startswith("tg_settings:"):
+ await self._handle_settings_callback(context, callback_data)
+ return True
if callback_data.startswith("tg_question:"):
await self._handle_question_callback(context, callback_data)
return True
@@ -416,6 +451,8 @@ class TelegramBot(BaseIMClient):
"is_dm": chat.get("type") == "private",
"chat_type": chat.get("type"),
"chat_title": chat.get("title") or chat.get("username"),
+ "is_forum": bool(chat.get("is_forum")),
+ "is_topic_message": bool(message.get("is_topic_message")),
"raw_message": message,
},
)
@@ -494,11 +531,38 @@ class TelegramBot(BaseIMClient):
bot_username = str((self._bot_user or {}).get("username") or "")
return bool(bot_username) and username.lower() != bot_username.lower()
+ def _strip_leading_bot_mention(self, message: dict[str, Any], text: str) -> str:
+ stripped = (text or "").strip()
+ if not stripped or stripped.startswith("/"):
+ return stripped
+
+ username = str((self._bot_user or {}).get("username") or "")
+ if not username:
+ return stripped
+
+ entities = message.get("entities") or []
+ candidate = stripped
+ for entity in entities:
+ if entity.get("type") != "mention":
+ continue
+ offset = int(entity.get("offset", 0))
+ length = int(entity.get("length", 0))
+ if offset != 0 or length <= 0:
+ continue
+ mention_text = candidate[offset : offset + length]
+ if mention_text.lower() != f"@{username.lower()}":
+ continue
+ remainder = candidate[offset + length :].lstrip(" \t\r\n,:-")
+ return remainder.strip()
+ return stripped
+
def _resolve_callback_action(self, callback_data: str) -> str:
if callback_data.startswith("tg_cwd:"):
return "cmd_change_cwd"
if callback_data.startswith("tg_route:"):
return "cmd_routing"
+ if callback_data.startswith("tg_settings:"):
+ return "cmd_settings"
if callback_data.startswith("toggle_msg_") or callback_data in {"open_settings_modal", "info_msg_types"}:
return "cmd_settings"
return callback_data
@@ -518,7 +582,7 @@ class TelegramBot(BaseIMClient):
return False
if stripped == "/cancel":
self._cwd_prompts.pop(self._interaction_scope_key(context), None)
- await self.send_message(context, self._t("telegram.cwdPromptCanceled"))
+ await self._delete_interaction_message(context, prompt.message_id)
return True
known_commands = {
"start",
@@ -537,6 +601,7 @@ class TelegramBot(BaseIMClient):
if parsed_command and parsed_command[0] in known_commands:
return False
self._cwd_prompts.pop(self._interaction_scope_key(context), None)
+ await self._delete_interaction_message(context, prompt.message_id)
if self._controller is None or not hasattr(self._controller, "command_handler"):
await self.send_message(context, f"❌ {self._t('error.cwdChangeFailed')}")
return True
@@ -575,12 +640,16 @@ class TelegramBot(BaseIMClient):
keyboard: Optional[InlineKeyboard] = None,
*,
reply_to: Optional[str] = None,
+ parse_mode: 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
+ resolved_parse_mode = self._resolve_parse_mode(parse_mode)
+ if text is not None and resolved_parse_mode:
+ payload["parse_mode"] = resolved_parse_mode
if reply_to:
payload["reply_parameters"] = {"message_id": int(reply_to)}
if keyboard is not None:
@@ -595,14 +664,24 @@ class TelegramBot(BaseIMClient):
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)
+ payload = self._build_payload(
+ context,
+ self.format_markdown(text),
+ reply_to=reply_to,
+ parse_mode=parse_mode,
+ )
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)
+ payload = self._build_payload(
+ context,
+ self.format_markdown(text),
+ keyboard=keyboard,
+ parse_mode=parse_mode,
+ )
result = await telegram_api.call_api(self.config.bot_token, "sendMessage", payload)
return str(result["result"]["message_id"])
@@ -648,6 +727,9 @@ class TelegramBot(BaseIMClient):
payload["reply_markup"] = {"inline_keyboard": []}
if text is not None:
payload["text"] = self.format_markdown(text)
+ resolved_parse_mode = self._resolve_parse_mode(parse_mode)
+ if resolved_parse_mode:
+ payload["parse_mode"] = resolved_parse_mode
if keyboard is None:
payload["reply_markup"] = {"inline_keyboard": []}
await telegram_api.call_api(self.config.bot_token, "editMessageText", payload)
@@ -655,6 +737,13 @@ class TelegramBot(BaseIMClient):
await telegram_api.call_api(self.config.bot_token, "editMessageReplyMarkup", payload)
return True
+ def _resolve_parse_mode(self, parse_mode: Optional[str]) -> Optional[str]:
+ if not parse_mode:
+ return self.get_default_parse_mode()
+ if parse_mode.lower() == "markdown":
+ return self.get_default_parse_mode()
+ return parse_mode
+
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:
@@ -678,6 +767,43 @@ class TelegramBot(BaseIMClient):
context = MessageContext(user_id=user_id, channel_id=user_id, platform="telegram", platform_specific={"is_dm": True})
return await self.send_message(context, text)
+ def _normalize_reaction_emoji(self, emoji: str) -> Optional[str]:
+ normalized = (emoji or "").strip()
+ if not normalized:
+ return None
+ aliases = {
+ ":eyes:": "👀",
+ "eyes": "👀",
+ "eye": "👀",
+ "👀": "👀",
+ ":robot_face:": "🤖",
+ "robot_face": "🤖",
+ "robot": "🤖",
+ "🤖": "🤖",
+ }
+ return aliases.get(normalized, normalized)
+
+ async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
+ normalized = self._normalize_reaction_emoji(emoji)
+ if not normalized or not message_id:
+ return False
+ try:
+ await telegram_api.set_message_reaction(self.config.bot_token, context.channel_id, message_id, normalized)
+ return True
+ except Exception as err:
+ logger.debug("Failed to add Telegram reaction: %s", err)
+ return False
+
+ async def remove_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
+ if not message_id or not self._normalize_reaction_emoji(emoji):
+ return False
+ try:
+ await telegram_api.clear_message_reaction(self.config.bot_token, context.channel_id, message_id)
+ return True
+ except Exception as err:
+ logger.debug("Failed to remove Telegram reaction: %s", err)
+ return False
+
async def send_typing_indicator(self, context: MessageContext) -> bool:
payload = {"chat_id": context.channel_id, "action": "typing"}
if context.thread_id:
@@ -688,6 +814,20 @@ class TelegramBot(BaseIMClient):
async def clear_typing_indicator(self, context: MessageContext) -> bool:
return True
+ async def delete_message(self, context: MessageContext, message_id: str) -> bool:
+ if not message_id:
+ return False
+ await telegram_api.delete_message(self.config.bot_token, context.channel_id, message_id)
+ return True
+
+ async def _delete_interaction_message(self, context: MessageContext, message_id: str) -> None:
+ if not message_id:
+ return
+ try:
+ await self.delete_message(context, message_id)
+ except Exception:
+ logger.debug("Failed to delete Telegram interaction message %s", message_id, exc_info=True)
+
async def upload_file_from_path(
self,
context: MessageContext,
@@ -768,14 +908,8 @@ class TelegramBot(BaseIMClient):
async def _handle_cwd_callback(self, context: MessageContext, callback_data: str) -> None:
scope_key = self._interaction_scope_key(context)
if callback_data == "tg_cwd:cancel":
- self._cwd_prompts.pop(scope_key, None)
- if context.message_id:
- await self.edit_message(
- context,
- context.message_id,
- text=f"📂 {self._t('telegram.cwdPromptCanceled')}",
- keyboard=None,
- )
+ prompt = self._cwd_prompts.pop(scope_key, None)
+ await self._delete_interaction_message(context, (prompt.message_id if prompt else context.message_id or ""))
async def open_resume_session_modal(
self,
@@ -824,12 +958,7 @@ class TelegramBot(BaseIMClient):
return
if callback_data == "tg_resume:cancel":
self._resume_states.pop(scope_key, None)
- await self.edit_message(
- context,
- state.message_id,
- text=f"⏮️ {self._t('telegram.resumeCanceled')}",
- keyboard=None,
- )
+ await self._delete_interaction_message(context, state.message_id)
return
try:
@@ -844,12 +973,7 @@ class TelegramBot(BaseIMClient):
if self._controller is None or not hasattr(self._controller, "session_handler"):
await self.send_message(context, f"❌ {self._t('error.resumeFailed')}")
return
- await self.edit_message(
- context,
- state.message_id,
- text=f"⏮️ {self._t('telegram.resumeSubmitting')}",
- keyboard=None,
- )
+ await self._delete_interaction_message(context, state.message_id)
await self._controller.session_handler.handle_resume_session_submission(
user_id=context.user_id,
channel_id=context.channel_id,
@@ -1019,12 +1143,7 @@ class TelegramBot(BaseIMClient):
del header, prompt
if action == "cancel":
self._question_states.pop(scope_key, None)
- await self.edit_message(
- context,
- state.message_id,
- text=f"❓ {self._t('common.cancel')}",
- keyboard=None,
- )
+ await self._delete_interaction_message(context, state.message_id)
return
if action in {"choose", "toggle"} and rest:
@@ -1065,12 +1184,7 @@ class TelegramBot(BaseIMClient):
) -> None:
self._question_states.pop(scope_key, None)
answers_payload = state.answers
- await self.edit_message(
- context,
- state.message_id,
- text=f"❓ {self._t('common.submitted')}",
- keyboard=None,
- )
+ await self._delete_interaction_message(context, state.message_id)
auth_result = self.check_authorization(
user_id=context.user_id,
channel_id=context.channel_id,
@@ -1228,7 +1342,12 @@ class TelegramBot(BaseIMClient):
text = "\n".join(self._routing_summary_lines(state))
backend_row = [
- InlineButton(text=self._get_backend_label(backend), callback_data="tg_route:field:backend")
+ InlineButton(
+ text=(f"☑️ {self._get_backend_label(backend)}" if backend == state.backend else self._get_backend_label(backend))[
+ :40
+ ],
+ callback_data=f"tg_route:backend:{backend}",
+ )
for backend in state.registered_backends[:3]
]
rows: list[list[InlineButton]] = []
@@ -1356,24 +1475,14 @@ class TelegramBot(BaseIMClient):
action = parts[1] if len(parts) > 1 else ""
if action == "cancel":
self._routing_states.pop(scope_key, None)
- await self.edit_message(
- context,
- state.message_id,
- text=f"🤖 {self._t('telegram.routingCanceled')}",
- keyboard=None,
- )
+ await self._delete_interaction_message(context, state.message_id)
return
if action == "save":
self._routing_states.pop(scope_key, None)
if self._controller is None or not hasattr(self._controller, "settings_handler"):
await self.send_message(context, f"❌ {self._t('error.routingModalFailed')}")
return
- await self.edit_message(
- context,
- state.message_id,
- text=f"🤖 {self._t('telegram.routingSaving')}",
- keyboard=None,
- )
+ await self._delete_interaction_message(context, state.message_id)
await self._controller.settings_handler.handle_routing_update(
user_id=state.user_id,
channel_id=state.channel_id,
@@ -1393,6 +1502,12 @@ class TelegramBot(BaseIMClient):
if action == "back":
state.picker_field = None
state.picker_page = 0
+ elif action == "backend" and len(parts) > 2:
+ backend = parts[2]
+ if backend in state.registered_backends:
+ state.backend = backend
+ state.picker_field = None
+ state.picker_page = 0
elif action == "page" and len(parts) > 2:
state.picker_page += -1 if parts[2] == "prev" else 1
elif action == "field" and len(parts) > 2:
@@ -1419,3 +1534,176 @@ class TelegramBot(BaseIMClient):
text, keyboard = self._render_routing_state(state)
await self.edit_message(context, state.message_id, text=text, keyboard=keyboard)
+
+ async def open_settings_modal(
+ self,
+ trigger_id: Any,
+ user_settings: Any,
+ message_types: list,
+ display_names: dict,
+ channel_id: str = None,
+ current_require_mention: object = None,
+ global_require_mention: bool = False,
+ current_language: str = None,
+ owner_user_id: Optional[str] = None,
+ ):
+ del display_names, owner_user_id
+ context = trigger_id if isinstance(trigger_id, MessageContext) else None
+ if context is None:
+ raise ValueError("Telegram settings flow requires a message context")
+
+ state = _TelegramSettingsState(
+ message_id="",
+ show_message_types=list(getattr(user_settings, "show_message_types", []) or []),
+ current_require_mention=current_require_mention,
+ global_require_mention=global_require_mention,
+ current_language=current_language or self._get_lang(),
+ is_dm=bool((context.platform_specific or {}).get("is_dm")),
+ )
+ text, keyboard = self._render_settings_state(state, list(message_types or []))
+ message_id = await self.send_message_with_buttons(context, text, keyboard)
+ state.message_id = message_id
+ self._settings_states[self._interaction_scope_key(context)] = state
+
+ def _settings_mention_label(self, value: Optional[bool], global_require_mention: bool) -> str:
+ if value is None:
+ default_status = (
+ self._t("modal.settings.mentionStatusOn")
+ if global_require_mention
+ else self._t("modal.settings.mentionStatusOff")
+ )
+ return f"{self._t('common.default')} ({default_status})"
+ return self._t("modal.settings.optionRequireMention") if value else self._t("modal.settings.optionDontRequireMention")
+
+ def _settings_message_type_label(self, msg_type: str) -> str:
+ display_names = {
+ "system": self._t("messageType.system"),
+ "assistant": self._t("messageType.assistant"),
+ "toolcall": self._t("messageType.toolcall"),
+ }
+ return display_names.get(msg_type, msg_type)
+
+ def _render_settings_state(
+ self,
+ state: _TelegramSettingsState,
+ message_types: list[str],
+ ) -> tuple[str, InlineKeyboard]:
+ selected = [self._settings_message_type_label(msg_type) for msg_type in state.show_message_types]
+ selected_text = ", ".join(selected) if selected else "-"
+ language_label = self._t(f"language.{state.current_language}")
+ if language_label == f"language.{state.current_language}":
+ language_label = state.current_language
+
+ lines = [
+ f"⚙️ {self._t('modal.settings.title')}",
+ "",
+ f"1. {self._t('modal.settings.showMessageTypes')}",
+ f" 当前: {selected_text}",
+ "",
+ f"2. {self._t('modal.settings.requireMention')}",
+ f" 当前: {self._settings_mention_label(state.current_require_mention, state.global_require_mention)}",
+ "",
+ f"3. {self._t('modal.settings.language')}",
+ f" 当前: {language_label}",
+ ]
+
+ rows: list[list[InlineButton]] = []
+ row: list[InlineButton] = []
+ for index, msg_type in enumerate(message_types):
+ is_shown = msg_type in state.show_message_types
+ checkbox = "☑️" if is_shown else "⬜"
+ row.append(
+ InlineButton(
+ text=f"{checkbox} {self._settings_message_type_label(msg_type)}"[:40],
+ callback_data=f"tg_settings:toggle:{msg_type}",
+ )
+ )
+ if len(row) == 2 or index == len(message_types) - 1:
+ rows.append(row)
+ row = []
+
+ mention_options = [
+ ("default", self._t("common.default"), state.current_require_mention is None),
+ ("on", self._t("modal.settings.optionRequireMention"), state.current_require_mention is True),
+ ("off", self._t("modal.settings.optionDontRequireMention"), state.current_require_mention is False),
+ ]
+ rows.append(
+ [
+ InlineButton(
+ text=(f"☑️ {label}" if selected_option else label)[:40],
+ callback_data=f"tg_settings:mention:{value}",
+ )
+ for value, label, selected_option in mention_options
+ ]
+ )
+ rows.append(
+ [
+ InlineButton(
+ text=(f"☑️ {self._t(f'language.{lang}')}" if lang == state.current_language else self._t(f"language.{lang}"))[:40],
+ callback_data=f"tg_settings:lang:{lang}",
+ )
+ for lang in get_supported_languages()
+ ]
+ )
+ rows.append([InlineButton(text=f"ℹ️ {self._t('button.aboutMessageTypes')}", callback_data="info_msg_types")])
+ rows.append(
+ [
+ InlineButton(text=f"💾 {self._t('common.save')}", callback_data="tg_settings:save"),
+ InlineButton(text=f"✖️ {self._t('common.cancel')}", callback_data="tg_settings:cancel"),
+ ]
+ )
+ return "\n".join(lines), InlineKeyboard(buttons=rows)
+
+ async def _handle_settings_callback(self, context: MessageContext, callback_data: str) -> None:
+ scope_key = self._interaction_scope_key(context)
+ state = self._settings_states.get(scope_key)
+ if state is None or state.message_id != (context.message_id or ""):
+ return
+
+ settings_manager = self.settings_manager
+ message_types = list(settings_manager.get_available_message_types()) if settings_manager else []
+ parts = callback_data.split(":")
+ action = parts[1] if len(parts) > 1 else ""
+
+ if action == "cancel":
+ self._settings_states.pop(scope_key, None)
+ await self._delete_interaction_message(context, state.message_id)
+ return
+
+ if action == "save":
+ self._settings_states.pop(scope_key, None)
+ if self._controller is None or not hasattr(self._controller, "settings_handler"):
+ await self.send_message(context, f"❌ {self._t('error.settingsFailed')}")
+ return
+ await self._delete_interaction_message(context, state.message_id)
+ await self._controller.settings_handler.handle_settings_update(
+ user_id=context.user_id,
+ show_message_types=state.show_message_types,
+ channel_id=context.channel_id,
+ require_mention=state.current_require_mention,
+ language=state.current_language,
+ notify_user=True,
+ is_dm=state.is_dm,
+ platform="telegram",
+ )
+ return
+
+ if action == "toggle" and len(parts) > 2:
+ msg_type = parts[2]
+ if msg_type in state.show_message_types:
+ state.show_message_types = [item for item in state.show_message_types if item != msg_type]
+ elif msg_type in message_types:
+ state.show_message_types.append(msg_type)
+ elif action == "mention" and len(parts) > 2:
+ value = parts[2]
+ if value == "default":
+ state.current_require_mention = None
+ elif value == "on":
+ state.current_require_mention = True
+ elif value == "off":
+ state.current_require_mention = False
+ elif action == "lang" and len(parts) > 2 and parts[2] in get_supported_languages():
+ state.current_language = parts[2]
+
+ text, keyboard = self._render_settings_state(state, message_types)
+ await self.edit_message(context, state.message_id, text=text, keyboard=keyboard)
diff --git a/modules/im/telegram_api.py b/modules/im/telegram_api.py
index bff75aa6a..45b60a38c 100644
--- a/modules/im/telegram_api.py
+++ b/modules/im/telegram_api.py
@@ -68,6 +68,36 @@ 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 delete_message(bot_token: str, chat_id: str, message_id: str) -> dict[str, Any]:
+ return await call_api(bot_token, "deleteMessage", {"chat_id": chat_id, "message_id": int(message_id)})
+
+
+async def set_message_reaction(
+ bot_token: str,
+ chat_id: str,
+ message_id: str,
+ emoji: str,
+ *,
+ is_big: bool = False,
+) -> dict[str, Any]:
+ payload = {
+ "chat_id": chat_id,
+ "message_id": int(message_id),
+ "reaction": [{"type": "emoji", "emoji": emoji}],
+ "is_big": is_big,
+ }
+ return await call_api(bot_token, "setMessageReaction", payload)
+
+
+async def clear_message_reaction(bot_token: str, chat_id: str, message_id: str) -> dict[str, Any]:
+ payload = {
+ "chat_id": chat_id,
+ "message_id": int(message_id),
+ "reaction": [],
+ }
+ return await call_api(bot_token, "setMessageReaction", payload)
+
+
async def send_multipart_file(
bot_token: str,
method: str,
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index edc39ee0c..01d6928d9 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -287,6 +287,20 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(controller.im_client.reactions, [])
self.assertGreaterEqual(len(controller.im_client.typing_calls), 1)
+ async def test_telegram_reaction_mode_matches_global_ack_strategy(self):
+ controller = _StubController(platform="telegram", ack_mode="reaction", typing_result=True)
+ handler = MessageHandler(controller)
+ handler.set_session_handler(_StubSessionHandler())
+ context = MessageContext(user_id="tg-user", channel_id="tg-chat", message_id="m1", platform="telegram")
+
+ await handler.handle_user_message(context, "hello")
+
+ _, request = controller.agent_service.requests[0]
+ self.assertFalse(request.typing_indicator_active)
+ self.assertEqual(request.ack_reaction_message_id, "m1")
+ self.assertEqual(request.ack_reaction_emoji, ":eyes:")
+ self.assertEqual(controller.im_client.reactions, [("tg-chat", "m1", ":eyes:")])
+
async def test_platform_specific_client_is_used_for_user_info(self):
controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)
handler = MessageHandler(controller)
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index c8a401f61..d6e2cfca0 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -186,6 +186,21 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
keyboard = controller.im_client.sent_button_messages[0][3]
self.assertEqual([[button.text for button in row] for row in keyboard.buttons], [["继续"], ["提交PR"]])
+ async def test_telegram_quick_reply_buttons_use_vertical_layout(self):
+ controller = _StubController("telegram")
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(user_id="U1", channel_id="C1", platform="telegram")
+
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "Done.\n---\n[继续] | [提交PR]",
+ )
+
+ self.assertEqual(len(controller.im_client.sent_button_messages), 1)
+ keyboard = controller.im_client.sent_button_messages[0][3]
+ self.assertEqual([[button.text for button in row] for row in keyboard.buttons], [["继续"], ["提交PR"]])
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
index 4be05cabb..199c882ec 100644
--- a/tests/test_telegram_bot.py
+++ b/tests/test_telegram_bot.py
@@ -23,6 +23,67 @@ def test_normalize_command_text_strips_bot_mention() -> None:
assert bot._normalize_command_text("/start@vibe_remote_bot hello") == "/start hello"
+def test_strip_leading_bot_mention_returns_empty_for_mention_only() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ bot._bot_user = {"id": 1, "username": "vibe_remote_bot"}
+ message = {
+ "text": "@vibe_remote_bot",
+ "entities": [{"type": "mention", "offset": 0, "length": 16}],
+ }
+
+ assert bot._strip_leading_bot_mention(message, "@vibe_remote_bot") == ""
+
+
+def test_strip_leading_bot_mention_keeps_message_body() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ bot._bot_user = {"id": 1, "username": "vibe_remote_bot"}
+ message = {
+ "text": "@vibe_remote_bot hello there",
+ "entities": [{"type": "mention", "offset": 0, "length": 16}],
+ }
+
+ assert bot._strip_leading_bot_mention(message, "@vibe_remote_bot hello there") == "hello there"
+
+
+def test_group_message_uses_channel_require_mention_override() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token", require_mention=True))
+ bot._bot_user = {"id": 1, "username": "vibe_remote_bot"}
+ bot.settings_manager = SimpleNamespace(get_require_mention=lambda channel_id, global_default=False: False)
+ bot.on_message_callback = AsyncMock()
+
+ asyncio.run(
+ bot._handle_message(
+ {
+ "message_id": 77,
+ "chat": {"id": -100123, "type": "group", "title": "Core Group"},
+ "from": {"id": 42},
+ "text": "hello team",
+ }
+ )
+ )
+
+ bot.on_message_callback.assert_awaited_once()
+ assert bot.on_message_callback.await_args.args[1] == "hello team"
+
+
+def test_group_mention_only_falls_through_as_empty_message() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token", require_mention=True))
+ bot._bot_user = {"id": 1, "username": "vibe_remote_bot"}
+ bot.on_message_callback = AsyncMock()
+ message = {
+ "message_id": 77,
+ "chat": {"id": -100123, "type": "group", "title": "Core Group"},
+ "from": {"id": 42},
+ "text": "@vibe_remote_bot",
+ "entities": [{"type": "mention", "offset": 0, "length": 16}],
+ }
+
+ asyncio.run(bot._handle_message(message))
+
+ bot.on_message_callback.assert_awaited_once()
+ assert bot.on_message_callback.await_args.args[1] == ""
+
+
def test_plain_group_sessions_are_channel_scoped() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
@@ -49,11 +110,13 @@ def test_forum_general_message_auto_creates_topic() -> None:
"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")):
+ with patch.object(bot, "send_message", new=AsyncMock(return_value="1")) as send_mock:
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"
+ send_mock.assert_awaited_once()
+ assert send_mock.await_args.args[0] == context
def test_should_auto_create_topic_only_for_general_topic_messages() -> None:
@@ -72,6 +135,54 @@ def test_should_auto_create_topic_only_for_general_topic_messages() -> None:
assert bot._should_auto_create_topic(context, {"is_topic_message": True}, "/start") is False
+def test_should_auto_create_topic_for_forum_general_without_thread_id() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token", forum_auto_topic=True))
+ context = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ thread_id=None,
+ message_id="77",
+ platform="telegram",
+ platform_specific={"chat_type": "supergroup", "is_forum": True, "is_topic_message": False},
+ )
+
+ message = {
+ "chat": {"id": -100123, "type": "supergroup", "title": "Core Forum", "is_forum": True},
+ "message_id": 77,
+ }
+
+ assert bot._should_auto_create_topic(context, message, "hello from general") is True
+
+
+def test_start_new_topic_session_allows_forum_context_without_thread_id() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token", forum_auto_topic=True))
+ context = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ thread_id=None,
+ message_id="77",
+ platform="telegram",
+ platform_specific={"chat_type": "supergroup", "is_forum": True, "is_topic_message": False},
+ )
+ message = {
+ "chat": {"id": -100123, "type": "supergroup", "title": "Core Forum", "is_forum": True},
+ "from": {"first_name": "Alex"},
+ "message_id": 77,
+ }
+
+ 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")) as send_mock:
+ 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"
+ send_mock.assert_awaited_once()
+ assert send_mock.await_args.args[0] == context
+
+
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()
@@ -130,10 +241,12 @@ def test_pending_cwd_prompt_consumes_next_plain_message() -> None:
command_handler=SimpleNamespace(handle_set_cwd=AsyncMock()),
)
- handled = asyncio.run(bot._consume_cwd_prompt(context, "/repo/new"))
+ with patch.object(bot, "_delete_interaction_message", new=AsyncMock()) as delete_mock:
+ handled = asyncio.run(bot._consume_cwd_prompt(context, "/repo/new"))
assert handled is True
bot._controller.command_handler.handle_set_cwd.assert_awaited_once()
+ delete_mock.assert_awaited_once_with(context, "10")
assert bot._interaction_scope_key(context) not in bot._cwd_prompts
@@ -154,6 +267,49 @@ def test_pending_cwd_prompt_bypasses_slash_command_with_args() -> None:
assert bot._interaction_scope_key(context) in bot._cwd_prompts
+def test_send_message_uses_html_parse_mode() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ context = MessageContext(user_id="42", channel_id="-100123", platform="telegram")
+
+ with patch(
+ "modules.im.telegram.telegram_api.call_api",
+ new=AsyncMock(return_value={"result": {"message_id": 77}}),
+ ) as call_mock:
+ asyncio.run(bot.send_message(context, "Hello **world**"))
+
+ payload = call_mock.await_args.args[2]
+ assert payload["parse_mode"] == "HTML"
+ assert payload["text"] == "Hello <b>world</b>"
+
+
+def test_add_reaction_uses_telegram_message_reactions() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ context = MessageContext(user_id="42", channel_id="-100123", platform="telegram")
+
+ with patch(
+ "modules.im.telegram.telegram_api.set_message_reaction",
+ new=AsyncMock(return_value={"ok": True}),
+ ) as reaction_mock:
+ result = asyncio.run(bot.add_reaction(context, "77", ":eyes:"))
+
+ assert result is True
+ reaction_mock.assert_awaited_once_with("123456:test-token", "-100123", "77", "👀")
+
+
+def test_remove_reaction_clears_telegram_message_reactions() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ context = MessageContext(user_id="42", channel_id="-100123", platform="telegram")
+
+ with patch(
+ "modules.im.telegram.telegram_api.clear_message_reaction",
+ new=AsyncMock(return_value={"ok": True}),
+ ) as reaction_mock:
+ result = asyncio.run(bot.remove_reaction(context, "77", ":eyes:"))
+
+ assert result is True
+ reaction_mock.assert_awaited_once_with("123456:test-token", "-100123", "77")
+
+
def test_resume_menu_uses_short_callback_ids() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
context = MessageContext(
@@ -251,12 +407,145 @@ def test_routing_callback_save_persists_selected_backend() -> None:
settings_handler=SimpleNamespace(handle_routing_update=AsyncMock()),
)
- with patch.object(bot, "edit_message", new=AsyncMock(return_value=True)):
+ with patch.object(bot, "_delete_interaction_message", new=AsyncMock()) as delete_mock:
asyncio.run(bot._handle_routing_callback(context, "tg_route:save"))
+ delete_mock.assert_awaited_once_with(context, "88")
bot._controller.settings_handler.handle_routing_update.assert_awaited_once()
+def test_routing_state_marks_current_backend_in_first_row() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ state = SimpleNamespace(
+ registered_backends=["opencode", "claude", "codex"],
+ backend="claude",
+ opencode_agent=None,
+ opencode_model=None,
+ opencode_reasoning_effort=None,
+ claude_agent="reviewer",
+ claude_model="claude-sonnet-4-6",
+ claude_reasoning_effort="high",
+ codex_model=None,
+ codex_reasoning_effort=None,
+ picker_field=None,
+ picker_page=0,
+ )
+
+ _, keyboard = bot._render_routing_state(state)
+
+ assert [button.callback_data for button in keyboard.buttons[0]] == [
+ "tg_route:backend:opencode",
+ "tg_route:backend:claude",
+ "tg_route:backend:codex",
+ ]
+ assert keyboard.buttons[0][1].text.startswith("☑️ ")
+
+
+def test_routing_callback_backend_switches_without_nested_picker() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ context = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ message_id="88",
+ platform="telegram",
+ platform_specific={"is_dm": False},
+ )
+ bot._routing_states[bot._interaction_scope_key(context)] = SimpleNamespace(
+ message_id="88",
+ channel_id=context.channel_id,
+ user_id=context.user_id,
+ is_dm=False,
+ registered_backends=["opencode", "claude", "codex"],
+ backend="opencode",
+ opencode_agent=None,
+ opencode_model=None,
+ opencode_reasoning_effort=None,
+ claude_agent=None,
+ claude_model=None,
+ claude_reasoning_effort=None,
+ codex_model=None,
+ codex_reasoning_effort=None,
+ picker_field=None,
+ picker_page=0,
+ )
+
+ with patch.object(bot, "edit_message", new=AsyncMock(return_value=True)) as edit_mock:
+ asyncio.run(bot._handle_routing_callback(context, "tg_route:backend:claude"))
+
+ state = bot._routing_states[bot._interaction_scope_key(context)]
+ assert state.backend == "claude"
+ assert state.picker_field is None
+ edit_mock.assert_awaited_once()
+
+
+def test_open_settings_modal_includes_language_buttons() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ context = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ message_id="88",
+ platform="telegram",
+ platform_specific={"is_dm": False},
+ )
+ user_settings = SimpleNamespace(show_message_types=["assistant", "toolcall"])
+
+ with patch.object(bot, "send_message_with_buttons", new=AsyncMock(return_value="66")) as send_mock:
+ asyncio.run(
+ bot.open_settings_modal(
+ context,
+ user_settings=user_settings,
+ message_types=["assistant", "toolcall", "system"],
+ display_names={},
+ channel_id=context.channel_id,
+ current_require_mention=None,
+ global_require_mention=True,
+ current_language="en",
+ )
+ )
+
+ keyboard = send_mock.await_args.args[2]
+ language_row = keyboard.buttons[-3]
+ assert [button.callback_data for button in language_row] == ["tg_settings:lang:en", "tg_settings:lang:zh"]
+
+
+def test_settings_callback_save_updates_language_and_deletes_menu() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ context = MessageContext(
+ user_id="42",
+ channel_id="-100123",
+ message_id="66",
+ platform="telegram",
+ platform_specific={"is_dm": False},
+ )
+ bot.settings_manager = SimpleNamespace(get_available_message_types=lambda: ["assistant", "toolcall", "system"])
+ bot._settings_states[bot._interaction_scope_key(context)] = SimpleNamespace(
+ message_id="66",
+ show_message_types=["assistant"],
+ current_require_mention=None,
+ global_require_mention=True,
+ current_language="zh",
+ is_dm=False,
+ )
+ bot._controller = SimpleNamespace(
+ settings_handler=SimpleNamespace(handle_settings_update=AsyncMock()),
+ )
+
+ with patch.object(bot, "_delete_interaction_message", new=AsyncMock()) as delete_mock:
+ asyncio.run(bot._handle_settings_callback(context, "tg_settings:save"))
+
+ delete_mock.assert_awaited_once_with(context, "66")
+ bot._controller.settings_handler.handle_settings_update.assert_awaited_once_with(
+ user_id="42",
+ show_message_types=["assistant"],
+ channel_id="-100123",
+ require_mention=None,
+ language="zh",
+ notify_user=True,
+ is_dm=False,
+ platform="telegram",
+ )
+
+
def test_open_question_modal_edits_message_with_telegram_buttons() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
context = MessageContext(
diff --git a/ui/src/components/steps/TelegramConfig.tsx b/ui/src/components/steps/TelegramConfig.tsx
index 726258d35..673439d7b 100644
--- a/ui/src/components/steps/TelegramConfig.tsx
+++ b/ui/src/components/steps/TelegramConfig.tsx
@@ -1,8 +1,22 @@
-import React, { useMemo, useState } from 'react';
-import { Check, KeyRound, MessageSquare, RefreshCw, Shield, SplitSquareVertical } from 'lucide-react';
+import React, { useEffect, useMemo, useState } from 'react';
+import {
+ Check,
+ ChevronDown,
+ ChevronUp,
+ Copy,
+ ExternalLink,
+ KeyRound,
+ MessageSquare,
+ RefreshCw,
+ Settings2,
+ Shield,
+ SplitSquareVertical,
+} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
+import { useToast } from '../../context/ToastContext';
+import { copyTextToClipboard } from '../../lib/utils';
interface TelegramConfigProps {
data: any;
@@ -13,17 +27,32 @@ interface TelegramConfigProps {
export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, onBack }) => {
const { t } = useTranslation();
const api = useApi();
+ const { showToast } = useToast();
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 [expandedSteps, setExpandedSteps] = useState<Record<number, boolean>>({ 1: true, 2: true, 3: false, 4: false, 5: false });
+ const [copiedCommand, setCopiedCommand] = useState<string | null>(null);
+
+ const hasSavedToken = Boolean(data.telegram?.bot_token && botToken === data.telegram?.bot_token);
+
+ useEffect(() => {
+ setAuthResult(null);
+ }, [botToken]);
+
+ useEffect(() => {
+ if ((authResult?.ok || hasSavedToken) && !expandedSteps[3]) {
+ setExpandedSteps((prev) => ({ ...prev, 2: false, 3: true, 4: true, 5: true }));
+ }
+ }, [authResult?.ok, hasSavedToken, expandedSteps]);
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]);
+ return hasSavedToken;
+ }, [authResult, botToken, hasSavedToken]);
const runAuthTest = async () => {
setChecking(true);
@@ -37,108 +66,286 @@ export const TelegramConfig: React.FC<TelegramConfigProps> = ({ data, onNext, on
}
};
+ const openBotFather = () => {
+ window.open('https://t.me/BotFather', '_blank');
+ };
+
+ const copyCommand = async (command: string) => {
+ const copied = await copyTextToClipboard(command);
+ if (!copied) {
+ showToast(t('common.copyFailed'), 'error');
+ return;
+ }
+ setCopiedCommand(command);
+ setTimeout(() => setCopiedCommand((current) => (current === command ? null : current)), 2000);
+ };
+
+ const toggleStep = (step: number) => {
+ setExpandedSteps((prev) => ({ ...prev, [step]: !prev[step] }));
+ };
+
+ const StepHeader: React.FC<{ step: number; title: string; icon: React.ReactNode; completed?: boolean }> = ({
+ step,
+ title,
+ icon,
+ completed,
+ }) => (
+ <button
+ onClick={() => toggleStep(step)}
+ className="w-full px-4 py-3 flex items-center justify-between bg-neutral-50 hover:bg-neutral-100 transition-colors"
+ >
+ <div className="flex items-center gap-3">
+ <span
+ className={clsx(
+ 'w-7 h-7 rounded-full text-sm font-bold flex items-center justify-center transition-colors',
+ completed ? 'bg-success text-white' : 'bg-accent text-white'
+ )}
+ >
+ {completed ? <Check size={14} /> : step}
+ </span>
+ <span className="flex items-center gap-2 font-semibold text-text">
+ {icon}
+ {title}
+ </span>
+ </div>
+ {expandedSteps[step] ? <ChevronUp size={18} className="text-muted" /> : <ChevronDown size={18} className="text-muted" />}
+ </button>
+ );
+
return (
<div className="flex flex-col h-full max-w-2xl mx-auto">
- <div className="mb-6">
+ <div className="mb-4">
<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 className="space-y-3 overflow-y-auto flex-1 pr-1">
+ <div className="bg-panel border border-border rounded-xl overflow-hidden">
+ <StepHeader
+ step={1}
+ title={t('telegramConfig.step1Title')}
+ icon={<MessageSquare size={16} className="text-accent" />}
+ />
+ {expandedSteps[1] && (
+ <div className="p-4 space-y-4 border-t border-border">
+ <p className="text-sm text-muted">{t('telegramConfig.step1Description')}</p>
+ <ol className="list-decimal list-inside space-y-1.5 text-sm text-muted pl-1">
+ <li>{t('telegramConfig.step1Item1')}</li>
+ <li>{t('telegramConfig.step1Item2')}</li>
+ <li>{t('telegramConfig.step1Item3')}</li>
+ <li>{t('telegramConfig.step1Item4')}</li>
+ </ol>
+ <div className="flex flex-wrap gap-2">
+ <button
+ onClick={openBotFather}
+ className="flex items-center gap-2 px-4 py-2 bg-accent text-white rounded-lg hover:bg-accent/90 transition-colors font-medium shadow-sm"
+ >
+ <ExternalLink size={16} />
+ {t('telegramConfig.openBotFather')}
+ </button>
+ <button
+ onClick={() => copyCommand('/newbot')}
+ className="flex items-center gap-2 px-4 py-2 border border-border rounded-lg text-text hover:bg-neutral-50 transition-colors font-medium"
+ >
+ {copiedCommand === '/newbot' ? <Check size={16} className="text-success" /> : <Copy size={16} className="text-accent" />}
+ {copiedCommand === '/newbot' ? t('telegramConfig.copiedCommand') : t('telegramConfig.copyNewBotCommand')}
+ </button>
+ </div>
+ <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-800">
+ <strong>{t('slackConfig.tip')}:</strong> {t('telegramConfig.step1Tip')}
+ </div>
</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"
+ <div className="bg-panel border border-border rounded-xl overflow-hidden">
+ <StepHeader
+ step={2}
+ title={t('telegramConfig.step2Title')}
+ icon={<KeyRound size={16} className="text-accent" />}
+ completed={isValid}
/>
- <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>
+ {expandedSteps[2] && (
+ <div className="p-4 space-y-4 border-t border-border">
+ <p className="text-sm text-muted">{t('telegramConfig.step2Description')}</p>
+ <ol className="list-decimal list-inside space-y-1.5 text-sm text-muted pl-1">
+ <li>{t('telegramConfig.step2Item1')}</li>
+ <li>{t('telegramConfig.step2Item2')}</li>
+ <li>{t('telegramConfig.step2Item3')}</li>
+ </ol>
+
+ <div className="space-y-2 pt-2">
+ <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)}
+ 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>
+
+ <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>
)}
- </span>
- )}
- </div>
+ </div>
+ </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 className="bg-panel border border-border rounded-xl overflow-hidden">
+ <StepHeader
+ step={3}
+ title={t('telegramConfig.step3Title')}
+ icon={<Shield size={16} className="text-accent" />}
+ />
+ {expandedSteps[3] && (
+ <div className="p-4 space-y-4 border-t border-border">
+ <p className="text-sm text-muted">{t('telegramConfig.step3Description')}</p>
+ <ol className="list-decimal list-inside space-y-1.5 text-sm text-muted pl-1">
+ <li>{t('telegramConfig.step3Item1')}</li>
+ <li>{t('telegramConfig.step3Item2')}</li>
+ <li>{t('telegramConfig.step3Item3')}</li>
+ <li>{t('telegramConfig.step3Item4')}</li>
+ </ol>
+ <div className="grid gap-3">
+ {[
+ {
+ command: '/setprivacy',
+ title: t('telegramConfig.step3Command1Title'),
+ description: t('telegramConfig.step3Command1Description'),
+ },
+ {
+ command: '/setjoingroups',
+ title: t('telegramConfig.step3Command2Title'),
+ description: t('telegramConfig.step3Command2Description'),
+ },
+ {
+ command: '/setcommands',
+ title: t('telegramConfig.step3Command3Title'),
+ description: t('telegramConfig.step3Command3Description'),
+ },
+ ].map((item) => (
+ <div key={item.command} className="rounded-lg border border-border bg-neutral-50 p-3">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div>
+ <div className="text-sm font-semibold text-text">{item.title}</div>
+ <p className="mt-1 text-xs text-muted">{item.description}</p>
+ </div>
+ <button
+ onClick={() => copyCommand(item.command)}
+ className="inline-flex items-center gap-2 rounded-lg border border-border bg-white px-3 py-1.5 text-sm font-medium text-text hover:bg-neutral-100 transition-colors"
+ >
+ {copiedCommand === item.command ? (
+ <Check size={14} className="text-success" />
+ ) : (
+ <Copy size={14} className="text-accent" />
+ )}
+ <code>{copiedCommand === item.command ? t('telegramConfig.copiedCommand') : item.command}</code>
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm text-amber-900">
+ <strong>{t('telegramConfig.step3TipTitle')}:</strong> {t('telegramConfig.step3Tip')}
+ </div>
+ <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-800">
+ <strong>{t('slackConfig.tip')}:</strong> {t('telegramConfig.step3ExtraTip')}
+ </div>
</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>
+
+ <div className="bg-panel border border-border rounded-xl overflow-hidden">
+ <StepHeader
+ step={4}
+ title={t('telegramConfig.step4Title')}
+ icon={<ExternalLink size={16} className="text-accent" />}
+ />
+ {expandedSteps[4] && (
+ <div className="p-4 space-y-4 border-t border-border">
+ <p className="text-sm text-muted">{t('telegramConfig.step4Description')}</p>
+ <ol className="list-decimal list-inside space-y-1.5 text-sm text-muted pl-1">
+ <li>{t('telegramConfig.step4Item1')}</li>
+ <li>{t('telegramConfig.step4Item2')}</li>
+ <li>{t('telegramConfig.step4Item3')}</li>
+ <li>{t('telegramConfig.step4Item4')}</li>
+ </ol>
+ <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-800">
+ <strong>{t('slackConfig.tip')}:</strong> {t('telegramConfig.step4Tip')}
</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 className="bg-panel border border-border rounded-xl overflow-hidden">
+ <StepHeader
+ step={5}
+ title={t('telegramConfig.step5Title')}
+ icon={<Settings2 size={16} className="text-accent" />}
+ />
+ {expandedSteps[5] && (
+ <div className="p-4 space-y-4 border-t border-border">
+ <p className="text-sm text-muted">{t('telegramConfig.step5Description')}</p>
+
+ <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>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 4ab85f9cc..bb4e5f744 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -142,13 +142,46 @@
},
"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.",
+ "subtitle": "Create a Telegram bot, validate the token, then finish the group setup in a few guided steps.",
+ "step1Title": "Create Bot with BotFather",
+ "step1Description": "Use @BotFather to create a new bot and prepare the API token.",
+ "step1Item1": "Open @BotFather in Telegram",
+ "step1Item2": "Send /newbot and follow the prompts",
+ "step1Item3": "Choose a display name for the bot",
+ "step1Item4": "Choose a username ending in \"bot\" and keep the generated token page open",
+ "step1Tip": "If you already created the bot, you can skip straight to copying the token in Step 2.",
+ "openBotFather": "Open BotFather",
+ "copyNewBotCommand": "Copy /newbot",
+ "copiedCommand": "Copied",
+ "step2Title": "Paste Token & Validate",
+ "step2Description": "Copy the bot token from BotFather and verify that Vibe Remote can talk to the bot.",
+ "step2Item1": "In BotFather, open your bot and choose the API token option",
+ "step2Item2": "Copy the token and paste it below",
+ "step2Item3": "Validate the token before continuing",
+ "step3Title": "Finish BotFather Initialization",
+ "step3Description": "Set the BotFather switches that directly control whether the bot can join groups and receive the messages you expect.",
+ "step3Item1": "Run the commands below in BotFather and select your bot each time",
+ "step3Item2": "If you want normal group messages without @mentions, set privacy mode to Disable",
+ "step3Item3": "If the bot should be used in groups or forums, make sure group joining is enabled",
+ "step3Item4": "Publish the common slash commands so new users can discover them from the Telegram command picker",
+ "step3Command1Title": "Disable group privacy mode",
+ "step3Command1Description": "Send /setprivacy, choose your bot, then select Disable. Otherwise Telegram forwards only commands, @mentions, and replies to the bot.",
+ "step3Command2Title": "Allow the bot to join groups",
+ "step3Command2Description": "Send /setjoingroups, choose your bot, and make sure it is set to Enable so the bot can be added to groups and forums normally.",
+ "step3Command3Title": "Publish the bot command menu",
+ "step3Command3Description": "Send /setcommands and add common commands like /start, /settings, /new, and /resume so users immediately see what the bot can do.",
+ "step3TipTitle": "Most commonly missed",
+ "step3Tip": "If you expect the bot to respond to normal group messages without explicit @mentions, /setprivacy must be set to Disable. This is the most common Telegram setup miss.",
+ "step3ExtraTip": "If you only need the bot in DMs for now, /setjoingroups can wait. But before using groups or forum topics, finish it first.",
+ "step4Title": "Add the Bot and Send the First Message",
+ "step4Description": "Complete the Telegram-side onboarding so Vibe Remote can actually discover your DM, group, or forum topic.",
+ "step4Item1": "Start a DM with the bot and send /start to confirm the direct-message path works",
+ "step4Item2": "If you want group or forum usage, add the bot there and grant permission to send messages; for auto-created topics, also grant admin or topic-management rights",
+ "step4Item3": "Send one message in each target conversation so the bot can discover that chat",
+ "step4Item4": "Return to the next channel-selection step and refresh the Telegram chat list",
+ "step4Tip": "If the bot still reacts only to commands or @mentions in groups, go back to Step 3 and verify that /setprivacy is really set to Disable.",
+ "step5Title": "Choose Conversation Defaults",
+ "step5Description": "Set the default group reply behavior and forum topic behavior for this bot.",
"botToken": "Bot Token",
"botTokenPlaceholder": "Paste your Telegram bot token",
"botTokenHint": "Create a bot with @BotFather, then paste the token here.",
@@ -158,7 +191,7 @@
"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."
+ "forumAutoTopicHint": "For forum-enabled supergroups, new top-level messages can automatically create a new topic that becomes the session container. This requires the bot to have admin or topic-management rights in that chat."
},
"larkConfig": {
"title": "Configure Lark",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 99ea6c42d..29600c102 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -142,13 +142,46 @@
},
"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。",
+ "subtitle": "按步骤创建 Telegram 机器人、验证令牌,并完成群组侧配置。",
+ "step1Title": "用 BotFather 创建机器人",
+ "step1Description": "先在 Telegram 里通过 @BotFather 创建一个新机器人,并准备好 API 令牌。",
+ "step1Item1": "在 Telegram 中打开 @BotFather",
+ "step1Item2": "发送 /newbot 并按提示操作",
+ "step1Item3": "给机器人设置一个显示名称",
+ "step1Item4": "设置一个以 bot 结尾的用户名,并保留生成令牌的页面",
+ "step1Tip": "如果你已经创建过机器人,可以直接跳到第 2 步复制令牌。",
+ "openBotFather": "打开 BotFather",
+ "copyNewBotCommand": "复制 /newbot",
+ "copiedCommand": "已复制",
+ "step2Title": "粘贴令牌并验证",
+ "step2Description": "从 BotFather 复制机器人令牌,并验证 Vibe Remote 是否能访问这个机器人。",
+ "step2Item1": "在 BotFather 中打开你的机器人,进入 API Token 相关选项",
+ "step2Item2": "复制令牌并粘贴到下方",
+ "step2Item3": "继续之前先完成令牌验证",
+ "step3Title": "在 BotFather 完成初始化设置",
+ "step3Description": "把 BotFather 里几个会直接影响群聊可用性的开关先设置好,后面就不会出现“加群了但不响应”的常见问题。",
+ "step3Item1": "在 BotFather 中发送下列命令,并选择刚创建的机器人",
+ "step3Item2": "如果希望群里无需 @ 也能响应普通消息,把隐私模式设为 Disable",
+ "step3Item3": "如果要把机器人拉进群组或 forum,确认允许加入群组",
+ "step3Item4": "把常用命令写进 BotFather,用户输入 / 时就能看到命令列表",
+ "step3Command1Title": "关闭群聊隐私模式",
+ "step3Command1Description": "发送 /setprivacy,选中你的 bot,然后选择 Disable。否则 Telegram 只会把命令、@提及和回复转发给机器人。",
+ "step3Command2Title": "允许机器人加入群组",
+ "step3Command2Description": "发送 /setjoingroups,选中你的 bot,并确保设置为 Enable。否则很容易出现机器人无法正常加入目标群聊。",
+ "step3Command3Title": "设置机器人命令菜单",
+ "step3Command3Description": "发送 /setcommands,给 bot 配置 /start、/settings、/new、/resume 等常用命令,让新用户更容易发现可用操作。",
+ "step3TipTitle": "最容易漏掉的点",
+ "step3Tip": "如果你希望机器人在群里无需 @ 也能响应普通消息,/setprivacy 必须选 Disable。这是 Telegram 群聊里最常见的初始化遗漏。",
+ "step3ExtraTip": "如果你只是先在私聊里使用 bot,/setjoingroups 可以稍后再配;但一旦要进群或 forum,建议这一步先完成。",
+ "step4Title": "把机器人加进去并发第一条消息",
+ "step4Description": "完成 Telegram 侧接入,让 Vibe Remote 能真正发现你的私聊、群组或 forum topic。",
+ "step4Item1": "先和机器人私聊并发送 /start,确认私聊链路正常",
+ "step4Item2": "如果要在群组或 forum 里用,把机器人加进去并授予发消息权限;若要自动新建 topic,请给它管理员或管理 topic 的权限",
+ "step4Item3": "在每个目标会话里先发送一条消息,让机器人发现这个会话",
+ "step4Item4": "回到下一步的频道列表页,刷新 Telegram 会话列表并选中目标会话",
+ "step4Tip": "如果群里仍然只对命令或 @ 有响应,先回头检查第 3 步的 /setprivacy 是否真的已经设成 Disable。",
+ "step5Title": "选择默认会话行为",
+ "step5Description": "为这个 Telegram 机器人设置默认的群聊响应方式和 forum topic 行为。",
"botToken": "机器人令牌",
"botTokenPlaceholder": "粘贴 Telegram 机器人令牌",
"botTokenHint": "先通过 @BotFather 创建机器人,再把令牌粘贴到这里。",
@@ -158,7 +191,7 @@
"requireMention": "群组中需要显式触发",
"requireMentionHint": "开启后,机器人只会在群组中响应显式 command、@提及或回复。",
"forumAutoTopic": "Forum 自动建 Topic",
- "forumAutoTopicHint": "对启用了 forum 的 supergroup,新顶层消息可以自动创建新的 topic,并把它作为 session 容器。"
+ "forumAutoTopicHint": "对启用了 forum 的 supergroup,新顶层消息可以自动创建新的 topic,并把它作为 session 容器。这个功能要求 bot 在该群里有管理员或管理 topic 的权限。"
},
"larkConfig": {
"title": "配置飞书",