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): sync bot command menu (#884)

Call White00af0b181630
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
index 83e8ad3ff..dce2d894a 100644
--- a/modules/im/telegram.py
+++ b/modules/im/telegram.py
@@ -95,6 +95,16 @@ class TelegramBot(BaseIMClient):
_MAX_IN_FLIGHT_UPDATE_TASKS = 100
_MAX_IN_FLIGHT_MESSAGE_CALLBACK_TASKS = 100
+ _COMMAND_MENU = (
+ ("start", "telegram.commandMenu.start"),
+ ("new", "telegram.commandMenu.new"),
+ ("cwd", "telegram.commandMenu.cwd"),
+ ("setcwd", "telegram.commandMenu.setcwd"),
+ ("resume", "telegram.commandMenu.resume"),
+ ("setup", "telegram.commandMenu.setup"),
+ ("settings", "telegram.commandMenu.settings"),
+ ("stop", "telegram.commandMenu.stop"),
+ )
_RICH_MARKDOWN_BLOCK_RE = re.compile(
r"(?m)^(?:#{1,6}\s+\S|[-*+]\s+\S|\d+\.\s+\S|>\s?\S|---\s*$|\|.*\|\s*$|\$\$)"
r"|```|<details\b|<tg-|!\[[^\]]*\]\(\s*<?https?://",
@@ -142,6 +152,7 @@ class TelegramBot(BaseIMClient):
self._on_ready: Optional[Callable] = None
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._poll_task: Optional[asyncio.Task[Any]] = None
+ self._command_menu_task: Optional[asyncio.Task[Any]] = None
self._update_tasks: set[asyncio.Task[Any]] = set()
self._message_callback_tasks: set[asyncio.Task[Any]] = set()
self._update_scope_gates: dict[str, _TelegramUpdateScopeGate] = {}
@@ -216,6 +227,7 @@ class TelegramBot(BaseIMClient):
try:
self._bot_user = (await telegram_api.get_me(self.config.bot_token, proxy_url=self._proxy_url)).get("result")
logger.info("Telegram bot connected as @%s", self._bot_user.get("username") if self._bot_user else "unknown")
+ self._command_menu_task = asyncio.create_task(self._sync_command_menu())
if self._on_ready:
await self._on_ready()
@@ -245,8 +257,49 @@ class TelegramBot(BaseIMClient):
await asyncio.sleep(2)
finally:
self._poll_task = None
+ command_menu_task = self._command_menu_task
+ self._command_menu_task = None
+ if command_menu_task is not None:
+ if not command_menu_task.done():
+ command_menu_task.cancel()
+ await asyncio.gather(command_menu_task, return_exceptions=True)
await self._drain_background_tasks()
+ def _build_command_menu(self, language: str) -> list[dict[str, str]]:
+ return [
+ {"command": command, "description": i18n_t(key, language)}
+ for command, key in self._COMMAND_MENU
+ ]
+
+ async def _sync_command_menu(self) -> None:
+ registrations: list[tuple[Optional[str], str]] = [(None, "en")]
+ registrations.extend(
+ (language, language)
+ for language in get_supported_languages()
+ if re.fullmatch(r"[a-z]{2}", language)
+ )
+
+ for language_code, translation_language in registrations:
+ try:
+ await telegram_api.set_my_commands(
+ self.config.bot_token,
+ self._build_command_menu(translation_language),
+ language_code=language_code,
+ proxy_url=self._proxy_url,
+ )
+ except Exception as err:
+ label = language_code or "default"
+ logger.warning("Failed to sync Telegram command menu for %s: %s", label, err)
+
+ try:
+ await telegram_api.set_chat_menu_button(
+ self.config.bot_token,
+ menu_button={"type": "commands"},
+ proxy_url=self._proxy_url,
+ )
+ except Exception as err:
+ logger.warning("Failed to enable Telegram command menu button: %s", err)
+
def _spawn_update_task(self, update: dict[str, Any]) -> None:
scope_key = self._extract_update_scope_key(update)
if scope_key:
diff --git a/modules/im/telegram_api.py b/modules/im/telegram_api.py
index c7981e9e7..098f7db71 100644
--- a/modules/im/telegram_api.py
+++ b/modules/im/telegram_api.py
@@ -107,6 +107,33 @@ async def clear_message_reaction(bot_token: str, chat_id: str, message_id: str,
return await call_api(bot_token, "setMessageReaction", payload, proxy_url=proxy_url)
+async def set_my_commands(
+ bot_token: str,
+ commands: list[dict[str, str]],
+ *,
+ language_code: Optional[str] = None,
+ proxy_url: Optional[str] = None,
+) -> dict[str, Any]:
+ payload: dict[str, Any] = {"commands": commands}
+ if language_code:
+ payload["language_code"] = language_code
+ return await call_api(bot_token, "setMyCommands", payload, proxy_url=proxy_url)
+
+
+async def set_chat_menu_button(
+ bot_token: str,
+ *,
+ menu_button: dict[str, Any],
+ proxy_url: Optional[str] = None,
+) -> dict[str, Any]:
+ return await call_api(
+ bot_token,
+ "setChatMenuButton",
+ {"menu_button": menu_button},
+ proxy_url=proxy_url,
+ )
+
+
async def send_multipart_file(
bot_token: str,
method: str,
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
index 8ff26b198..8200bdb78 100644
--- a/tests/test_telegram_bot.py
+++ b/tests/test_telegram_bot.py
@@ -18,6 +18,7 @@ from modules.agents.native_sessions import NativeResumeSession
from modules.im import InlineButton, InlineKeyboard, MessageContext
from modules.im.multi import MultiIMClient
from modules.im.telegram import TelegramBot
+from modules.im import telegram_api
from config.v2_config import TelegramConfig
@@ -351,11 +352,91 @@ def test_run_dispatches_telegram_updates_concurrently() -> None:
with patch("modules.im.telegram.telegram_api.get_me", new=AsyncMock(return_value={"result": {"username": "bot"}})):
with patch("modules.im.telegram.telegram_api.get_updates", new=AsyncMock(side_effect=fake_get_updates)):
- with patch.object(bot, "_handle_update", new=fake_handle):
- asyncio.run(asyncio.wait_for(bot._run(), timeout=0.2))
+ with patch.object(bot, "_sync_command_menu", new=AsyncMock()) as sync_mock:
+ with patch.object(bot, "_handle_update", new=fake_handle):
+ asyncio.run(asyncio.wait_for(bot._run(), timeout=0.2))
assert second_started.is_set()
assert started == [1, 2]
+ sync_mock.assert_awaited_once()
+
+
+def test_sync_command_menu_registers_localized_commands_and_menu_button() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token", proxy_url="socks5://127.0.0.1:1080"))
+
+ with patch(
+ "modules.im.telegram.telegram_api.set_my_commands",
+ new=AsyncMock(return_value={"ok": True}),
+ ) as commands_mock:
+ with patch(
+ "modules.im.telegram.telegram_api.set_chat_menu_button",
+ new=AsyncMock(return_value={"ok": True}),
+ ) as menu_mock:
+ asyncio.run(bot._sync_command_menu())
+
+ assert [call.kwargs["language_code"] for call in commands_mock.await_args_list] == [None, "en", "zh"]
+ default_commands = commands_mock.await_args_list[0].args[1]
+ chinese_commands = commands_mock.await_args_list[2].args[1]
+ assert [item["command"] for item in default_commands] == [
+ "start",
+ "new",
+ "cwd",
+ "setcwd",
+ "resume",
+ "setup",
+ "settings",
+ "stop",
+ ]
+ assert default_commands[0]["description"] == "Open the main menu"
+ assert chinese_commands[0]["description"] == "打开主菜单"
+ assert all(call.kwargs["proxy_url"] == "socks5://127.0.0.1:1080" for call in commands_mock.await_args_list)
+ menu_mock.assert_awaited_once_with(
+ "123456:test-token",
+ menu_button={"type": "commands"},
+ proxy_url="socks5://127.0.0.1:1080",
+ )
+
+
+def test_sync_command_menu_keeps_going_after_registration_failure() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+
+ with patch(
+ "modules.im.telegram.telegram_api.set_my_commands",
+ new=AsyncMock(side_effect=[RuntimeError("default failed"), {"ok": True}, {"ok": True}]),
+ ) as commands_mock:
+ with patch(
+ "modules.im.telegram.telegram_api.set_chat_menu_button",
+ new=AsyncMock(return_value={"ok": True}),
+ ) as menu_mock:
+ asyncio.run(bot._sync_command_menu())
+
+ assert commands_mock.await_count == 3
+ menu_mock.assert_awaited_once()
+
+
+def test_set_my_commands_builds_language_payload_and_uses_proxy() -> None:
+ with patch(
+ "modules.im.telegram_api.call_api",
+ new=AsyncMock(return_value={"ok": True}),
+ ) as call_mock:
+ asyncio.run(
+ telegram_api.set_my_commands(
+ "123456:test-token",
+ [{"command": "start", "description": "Open the main menu"}],
+ language_code="en",
+ proxy_url="socks5://127.0.0.1:1080",
+ )
+ )
+
+ call_mock.assert_awaited_once_with(
+ "123456:test-token",
+ "setMyCommands",
+ {
+ "commands": [{"command": "start", "description": "Open the main menu"}],
+ "language_code": "en",
+ },
+ proxy_url="socks5://127.0.0.1:1080",
+ )
def test_spawn_update_task_keeps_same_scope_updates_ordered() -> None:
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index cadf90fb7..6eccde3b6 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -449,6 +449,16 @@
"zh": "\u4e2d\u6587"
},
"telegram": {
+ "commandMenu": {
+ "start": "Open the main menu",
+ "new": "Start a fresh session",
+ "cwd": "Show the working directory",
+ "setcwd": "Change the working directory",
+ "resume": "Resume a recent session",
+ "setup": "Repair backend login",
+ "settings": "Open settings",
+ "stop": "Stop the current task"
+ },
"autoTopicGeneralNotice": "Started a new topic for this request: {topic}. Continue there.",
"autoTopicIntro": "New session topic created: {topic}",
"cwdPromptTitle": "Change working directory",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index b987412e0..5f4a6a1ca 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -449,6 +449,16 @@
"zh": "中文"
},
"telegram": {
+ "commandMenu": {
+ "start": "打开主菜单",
+ "new": "开始全新会话",
+ "cwd": "查看当前工作目录",
+ "setcwd": "更改工作目录",
+ "resume": "恢复最近的会话",
+ "setup": "修复后端登录",
+ "settings": "打开设置",
+ "stop": "停止当前任务"
+ },
"autoTopicGeneralNotice": "已为这次请求创建新的 Topic:{topic},请在那里继续。",
"autoTopicIntro": "已创建新的会话 Topic:{topic}",
"cwdPromptTitle": "更改工作目录",