Skip to content

Your lightweight open-source personal agent.

fix(command): rename hyphenated slash commands to Telegram-safe underscores (#5711)

Nasterda749b4a8762
diff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.py
index 0a29c55ad..2ce199cfa 100644
--- a/nanobot/channels/telegram/runtime.py
+++ b/nanobot/channels/telegram/runtime.py
@@ -462,6 +462,41 @@ class TelegramConfig(Base):
return self
+_TELEGRAM_COMMAND_ALIASES = {
+ "/dream_log": "/dream-log",
+ "/dream_restore": "/dream-restore",
+ "/dream_prompt": "/dream-prompt",
+ "/evaluator_prompt": "/evaluator-prompt",
+}
+_TELEGRAM_DISPLAY_COMMAND_RE = re.compile(
+ r"(?<![\w/.-])/(?:dream-log|dream-restore|dream-prompt|evaluator-prompt)(?![\w/.-])"
+)
+
+
+def _telegram_command_text(text: str) -> str:
+ """Render command references for Telegram without changing fenced code or diffs."""
+ display_names = {value: key for key, value in _TELEGRAM_COMMAND_ALIASES.items()}
+ lines: list[str] = []
+ fence: str | None = None
+ for line in text.splitlines(keepends=True):
+ stripped = line.lstrip()
+ if fence is not None:
+ if stripped.startswith(fence):
+ fence = None
+ elif stripped.startswith(("```", "~~~")):
+ fence = stripped[:3]
+ else:
+ line = _TELEGRAM_DISPLAY_COMMAND_RE.sub(lambda match: display_names[match[0]], line)
+ # Inline code is not tappable as a Telegram command.
+ line = re.sub(
+ r"`(/(?:dream_log|dream_restore|dream_prompt|evaluator_prompt)(?: [^`\n]*)?)`",
+ r"\1",
+ line,
+ )
+ lines.append(line)
+ return "".join(lines)
+
+
class TelegramChannel(BaseChannel):
"""
Telegram channel using long polling or webhook mode.
@@ -491,15 +526,16 @@ class TelegramChannel(BaseChannel):
BotCommand("dream_log", "Show the latest Dream memory change"),
BotCommand("dream_restore", "Restore Dream memory to an earlier version"),
BotCommand("dream_prompt", "Tell Dream how to organize memory"),
+ BotCommand("evaluator_prompt", "Customize the heartbeat evaluator prompt"),
BotCommand("help", "Show available commands"),
]
# Regex for slash commands routed to AgentLoop via ``_forward_command``.
- # Hyphenated ``dream-*`` commands stay on a separate handler (below).
- # Must cover every builtin router command; ``test_telegram_bus_slash_command_regex_matches_agent_loop_commands``
- # pins the pairing.
+ # Telegram-safe aliases are normalized before reaching the core router.
+ # Canonical hyphenated commands stay on a separate handler (below).
TELEGRAM_BUS_SLASH_COMMAND_RE = re.compile(
- r"^/(?:new|compact|stop|restart|status|dream|history|goal|trigger|pairing|model|skill|evaluator-prompt)(?:@\w+)?(?:\s+.*)?$"
+ r"^/(?:new|compact|stop|restart|status|dream|history|goal|trigger|pairing|model|skill"
+ r"|dream_log|dream_restore|dream_prompt|evaluator_prompt|evaluator-prompt)(?:@\w+)?(?:\s+.*)?$"
)
@classmethod
@@ -555,12 +591,9 @@ class TelegramChannel(BaseChannel):
"""Map Telegram-safe command aliases back to canonical nanobot commands."""
if not content.startswith("/"):
return content
- if content == "/dream_log" or content.startswith("/dream_log "):
- return content.replace("/dream_log", "/dream-log", 1)
- if content == "/dream_restore" or content.startswith("/dream_restore "):
- return content.replace("/dream_restore", "/dream-restore", 1)
- if content == "/dream_prompt" or content.startswith("/dream_prompt "):
- return content.replace("/dream_prompt", "/dream-prompt", 1)
+ for alias, canonical in _TELEGRAM_COMMAND_ALIASES.items():
+ if content == alias or content.startswith(f"{alias} "):
+ return canonical + content[len(alias):]
return content
async def start(self) -> None:
@@ -658,7 +691,7 @@ class TelegramChannel(BaseChannel):
self._app.add_handler(
MessageHandler(
filters.Regex(
- r"^/(dream-log|dream_log|dream-restore|dream_restore|dream-prompt|dream_prompt)(?:@\w+)?(?:\s+.*)?$"
+ r"^/(?:dream-log|dream-restore|dream-prompt)(?:@\w+)?(?:\s+.*)?$"
),
self._forward_command,
)
@@ -1116,6 +1149,8 @@ class TelegramChannel(BaseChannel):
buttons = cast(list[list[str]], getattr(msg, "buttons", None) or [])
reply_markup = self._build_keyboard(buttons) if buttons else None
text = msg.content
+ if msg.metadata.get("render_as") == "text":
+ text = _telegram_command_text(text)
# Fallback: no native keyboard → splice labels into the message so the choices survive.
if buttons and reply_markup is None:
text = f"{text}\n\n{self._buttons_as_text(buttons)}"
@@ -1544,7 +1579,7 @@ class TelegramChannel(BaseChannel):
if not self.is_allowed(sender_id):
await self._send_pairing_code_if_private(sender_id, update.message, user)
return
- await update.message.reply_text(build_help_text())
+ await update.message.reply_text(_telegram_command_text(build_help_text()))
@staticmethod
def _sender_id(user: User) -> str:
diff --git a/nanobot/channels/telegram/tests/test_telegram_channel.py b/nanobot/channels/telegram/tests/test_telegram_channel.py
index 9684db42f..f9f3a17dc 100644
--- a/nanobot/channels/telegram/tests/test_telegram_channel.py
+++ b/nanobot/channels/telegram/tests/test_telegram_channel.py
@@ -25,6 +25,7 @@ from nanobot.channels.telegram.runtime import (
_markdown_to_telegram_html,
_split_telegram_markdown,
_StreamBuf,
+ _telegram_command_text,
)
@@ -360,6 +361,8 @@ async def test_start_creates_separate_pools_with_proxy(monkeypatch) -> None:
assert any(cmd.command == "dream_log" for cmd in app.bot.commands)
assert any(cmd.command == "dream_restore" for cmd in app.bot.commands)
assert any(cmd.command == "dream_prompt" for cmd in app.bot.commands)
+ assert any(cmd.command == "evaluator_prompt" for cmd in app.bot.commands)
+ assert any(cmd.command == "compact" for cmd in app.bot.commands)
@pytest.mark.asyncio
@@ -2491,11 +2494,15 @@ def test_telegram_bus_slash_command_regex_matches_agent_loop_commands() -> None:
assert pat.fullmatch("/new@nanobot_bot")
assert pat.fullmatch("/goal@nanobot_bot refine objective")
assert pat.fullmatch("/trigger@nanobot_bot CI summary")
- assert pat.fullmatch("/compact")
assert pat.fullmatch("/compact@nanobot_bot")
+ assert pat.fullmatch("/dream_log deadbeef")
+ assert pat.fullmatch("/dream_restore deadbeef")
+ assert pat.fullmatch("/dream_prompt init")
+ assert pat.fullmatch("/evaluator_prompt@nanobot_bot init")
+ assert pat.fullmatch("/unknown-command") is None
+ assert pat.fullmatch("/compact")
assert pat.fullmatch("/evaluator-prompt")
assert pat.fullmatch("/evaluator-prompt init")
- assert not pat.fullmatch("/unknown-command")
assert pat.fullmatch("/dream-log deadbeef") is None
assert pat.fullmatch("/dream-restore deadbeef") is None
assert pat.fullmatch("/dream-prompt init") is None
@@ -2518,13 +2525,89 @@ async def test_on_help_includes_restart_command() -> None:
assert "/status" in help_text
assert "/skill" in help_text
assert "/dream" in help_text
- assert "/dream-log" in help_text
- assert "/dream-prompt" in help_text
+ assert "/dream_log" in help_text
+ assert "/dream_prompt" in help_text
+ assert "/evaluator_prompt" in help_text
+ assert "/compact" in help_text
assert "/goal" in help_text
assert "/trigger" in help_text
assert "/pairing" in help_text
assert "/model" in help_text
- assert "/dream-restore" in help_text
+ assert "/dream_restore" in help_text
+
+
[email protected]("command", ["dream-log", "dream-restore", "dream-prompt", "evaluator-prompt"])
[email protected]("underscore", [False, True])
+async def test_telegram_command_handlers_preserve_core_names(monkeypatch, command, underscore):
+ bus = MessageBus()
+ channel = TelegramChannel(
+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"]), bus,
+ )
+ app = _FakeApp(lambda: None)
+ monkeypatch.setattr("nanobot.channels.telegram.runtime.HTTPXRequest", _FakeHTTPXRequest)
+ monkeypatch.setattr(
+ "nanobot.channels.telegram.runtime.Application",
+ SimpleNamespace(builder=lambda: _FakeBuilder(app)),
+ )
+ await channel._start_app()
+ try:
+ spelling = command.replace("-", "_") if underscore else command
+ text = f"/{spelling}@nanobot_test argument"
+ update = telegram.Update.de_json({
+ "update_id": 1,
+ "message": {
+ "message_id": 1, "date": 1,
+ "chat": {"id": 123, "type": "private"},
+ "from": {"id": 123, "is_bot": False, "first_name": "Tester"},
+ "text": text,
+ "entities": [{
+ "type": "bot_command", "offset": 0,
+ "length": len(text.split()[0]) if underscore else len(command.split("-")[0]) + 1,
+ }],
+ },
+ }, None)
+ handler = next(handler for handler in app.handlers if handler.check_update(update))
+ assert handler.callback == channel._forward_command
+ await handler.callback(update, None)
+ message = await asyncio.wait_for(bus.consume_inbound(), timeout=1)
+ assert message.content == f"/{command} argument"
+ finally:
+ await channel._teardown_app()
+
+
+def test_telegram_command_text_preserves_arguments_paths_and_diffs():
+ text = (
+ "Use `/dream-log deadbeef` or `/evaluator-prompt init`.\n"
+ "Usage: /dream-prompt [init]\n"
+ "Keep /tmp/dream-log and /dream-log.md.\n"
+ "```diff\n- /dream-log\n+ /dream-prompt\n```\n"
+ )
+ assert _telegram_command_text(text) == (
+ "Use /dream_log deadbeef or /evaluator_prompt init.\n"
+ "Usage: /dream_prompt [init]\n"
+ "Keep /tmp/dream-log and /dream-log.md.\n"
+ "```diff\n- /dream-log\n+ /dream-prompt\n```\n"
+ )
+
+
[email protected]("control_reply", [False, True])
+async def test_send_adapts_command_references_only_in_control_replies(control_reply):
+ channel = TelegramChannel(
+ TelegramConfig(enabled=True, token="123:abc", allow_from=["*"], rich_messages=False),
+ MessageBus(),
+ )
+ app = _install_ready_app(channel)
+ content = "Use `/dream-restore deadbeef`."
+ message = OutboundMessage(
+ channel="telegram", chat_id="123", content=content,
+ metadata={"render_as": "text"} if control_reply else {},
+ )
+ await channel.send(message)
+ expected = "Use /dream_restore deadbeef." if control_reply else _markdown_to_telegram_html(content)
+ assert app.bot.sent_messages[-1]["text"] == expected
+ assert message.content == content
@pytest.mark.asyncio