Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(platform): connect Telegram by messaging the bot first; adding it to a group is optional (#15159)

Bently61bba1aa1e87
diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/registry.py b/autogpt_platform/backend/backend/api/features/platform_linking/registry.py
index d38d648b62..0281272c89 100644
--- a/autogpt_platform/backend/backend/api/features/platform_linking/registry.py
+++ b/autogpt_platform/backend/backend/api/features/platform_linking/registry.py
@@ -31,6 +31,11 @@ _SERVER_NOUNS = {
}
_DEFAULT_SERVER_NOUN = "server"
+# Payload on the Telegram DM deep link. Telegram sends it as "/start <payload>";
+# the bot only needs the /start, but a payload makes Telegram send it again for
+# users who already have a chat with the bot.
+TELEGRAM_DM_START_PAYLOAD = "connect"
+
class PlatformMeta(BaseModel):
"""Static + runtime metadata for one chat-bot platform."""
@@ -43,6 +48,9 @@ class PlatformMeta(BaseModel):
server_noun: str # see _SERVER_NOUNS
enabled: bool
add_bot_url: str | None # null when the platform has no invite URL we can build
+ # Deep link that opens a DM with the bot, for platforms where that is the
+ # easiest way in. Null when the platform can't open a DM from a URL.
+ dm_url: str | None = None
def enabled_platforms() -> list[PlatformMeta]:
@@ -103,22 +111,27 @@ def _slack_meta() -> PlatformMeta:
def _telegram_meta() -> PlatformMeta:
- # Enabled on the same gate the webhook adapter mounts on. The t.me
- # startgroup deep link opens Telegram's own "add to group" picker, so the
- # button only renders when the bot's public username is configured.
+ # Enabled on the same gate the webhook adapter mounts on. Both deep links
+ # need the bot's public username, so the buttons only render when it's set.
+ # The DM link comes first: ?start= opens the bot chat and sends /start,
+ # which replies with the Link Account button. ?startgroup= opens
+ # Telegram's "add to group" picker, which is a dead end for anyone who has
+ # no group yet.
enabled = bool(
telegram_config.get_bot_token() and telegram_config.get_webhook_secret()
)
username = telegram_config.get_bot_username().lstrip("@")
+ has_links = enabled and bool(username)
return PlatformMeta(
platform="TELEGRAM",
display_name="Telegram",
icon="telegram.png",
server_noun=_SERVER_NOUNS["TELEGRAM"],
enabled=enabled,
- add_bot_url=(
- f"https://t.me/{username}?startgroup=true"
- if (enabled and username)
+ add_bot_url=f"https://t.me/{username}?startgroup=true" if has_links else None,
+ dm_url=(
+ f"https://t.me/{username}?start={TELEGRAM_DM_START_PAYLOAD}"
+ if has_links
else None
),
)
diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.py b/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.py
index 92146757ce..9ee4a4e557 100644
--- a/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.py
+++ b/autogpt_platform/backend/backend/api/features/platform_linking/registry_test.py
@@ -168,6 +168,9 @@ def test_telegram_appears_with_tme_link_when_username_set():
assert telegram.display_name == "Telegram"
assert telegram.icon == "telegram.png"
assert telegram.add_bot_url == "https://t.me/AutoGPTBot?startgroup=true"
+ # The DM is the first step; ?start= makes Telegram send /start, which
+ # the bot answers with the Link Account button.
+ assert telegram.dm_url == "https://t.me/AutoGPTBot?start=connect"
def test_telegram_without_username_has_no_add_bot_url():
@@ -182,6 +185,7 @@ def test_telegram_without_username_has_no_add_bot_url():
assert [p.platform for p in platforms] == ["TELEGRAM"]
assert platforms[0].add_bot_url is None
+ assert platforms[0].dm_url is None
def test_telegram_hidden_without_webhook_secret():
diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/routes.py b/autogpt_platform/backend/backend/api/features/platform_linking/routes.py
index 82223e3da6..db3a0a29ed 100644
--- a/autogpt_platform/backend/backend/api/features/platform_linking/routes.py
+++ b/autogpt_platform/backend/backend/api/features/platform_linking/routes.py
@@ -214,6 +214,7 @@ async def list_bot_platforms(
add_bot_url=_user_bound_install_url(
meta.platform, meta.add_bot_url, user_id
),
+ dm_url=meta.dm_url,
dm_link=dm_by_platform.get(meta.platform),
server_links=servers_by_platform.get(meta.platform, []),
pending_install=await _pending_install(
diff --git a/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.py b/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.py
index b43611021e..7b20c43d67 100644
--- a/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/platform_linking/routes_test.py
@@ -293,6 +293,39 @@ class TestAdversarialDeleteLinkId:
class TestListBotPlatforms:
+ @pytest.mark.asyncio
+ async def test_passes_the_dm_url_through(self):
+ from backend.api.features.platform_linking.routes import list_bot_platforms
+
+ db = _db_mock(
+ list_user_links=AsyncMock(return_value=[]),
+ list_server_links=AsyncMock(return_value=[]),
+ )
+ telegram = PlatformMeta(
+ platform="TELEGRAM",
+ display_name="Telegram",
+ icon="telegram.png",
+ server_noun="group",
+ enabled=True,
+ add_bot_url="https://t.me/AutoGPTBot?startgroup=true",
+ dm_url="https://t.me/AutoGPTBot?start=connect",
+ )
+ with (
+ patch(
+ "backend.api.features.platform_linking.routes.platform_linking_db",
+ return_value=db,
+ ),
+ patch(
+ "backend.api.features.platform_linking.routes.registry.enabled_platforms",
+ return_value=[telegram, _discord_meta()],
+ ),
+ ):
+ result = await list_bot_platforms(user_id="u1")
+
+ assert result[0].dm_url == "https://t.me/AutoGPTBot?start=connect"
+ assert result[0].add_bot_url == "https://t.me/AutoGPTBot?startgroup=true"
+ assert result[1].dm_url is None
+
@pytest.mark.asyncio
async def test_returns_enabled_platforms_with_no_links(self):
from backend.api.features.platform_linking.routes import list_bot_platforms
diff --git a/autogpt_platform/backend/backend/copilot/bot/README.md b/autogpt_platform/backend/backend/copilot/bot/README.md
index c4381b4933..6d009ebc6b 100644
--- a/autogpt_platform/backend/backend/copilot/bot/README.md
+++ b/autogpt_platform/backend/backend/copilot/bot/README.md
@@ -55,7 +55,7 @@ bot/
├── turn_stream.py # Streaming one batched turn: chunked sends, artifacts, renames
├── prompt.py # Prompt + thread-name assembly
├── attachments.py # Attachment upload + failure notes
-├── command_core.py # Shared /setup + /unlink policy (adapters render it)
+├── command_core.py # Shared /setup + /unlink + DM-link policy (adapters render it)
├── bot_backend.py # Thin facade over PlatformLinkingManagerClient + stream_registry
├── text.py # Text splitting + batch formatting
├── threads.py # Redis-backed thread subscription tracking
@@ -80,7 +80,7 @@ bot/
├── telegram/ # WebhookAdapter — Telegram Bot API
│ ├── adapter.py # Inbound updates route, sends, chat-model mapping
│ ├── api_client.py # Thin httpx Bot API client (JSON + multipart + getFile)
- │ ├── commands.py # Bot commands (/setup, /help, /unlink)
+ │ ├── commands.py # Bot commands (/start + /setup link a DM or group, /help, /unlink)
│ ├── config.py # BotFather token + webhook secret + platform limits
│ └── text.py # CommonMark → Telegram HTML
└── teams/ # WebhookAdapter — Bot Framework Connector
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py
index aadba54848..5ba488b2df 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py
@@ -165,7 +165,9 @@ class TelegramAdapter(WebhookAdapter):
# This runs as a fire-and-forget task — an unhandled error would
# only surface as asyncio's deferred "exception never retrieved".
try:
- await commands.handle(self._api, self._client, message, command)
+ await commands.handle(
+ self._api, self._client, message, command, self.send_link
+ )
except Exception:
logger.exception("Telegram command handler failed")
return
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter_test.py
index 937f759423..57145b700d 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter_test.py
@@ -160,6 +160,35 @@ class TestDispatch:
handle.assert_awaited_once()
assert seen == []
+ @pytest.mark.asyncio
+ async def test_private_start_sends_the_link_account_button(self):
+ # The full path a user takes from the Bots page: t.me/<bot>?start=connect
+ # makes Telegram post "/start connect" from the private chat.
+ a = _adapter()
+ seen = []
+ a.on_message(lambda ctx, adapter: seen.append(ctx) or _noop())
+ a._api.resolve_user = AsyncMock(return_value=MagicMock(linked=False))
+ a._api.create_user_link_token = AsyncMock(
+ return_value=MagicMock(link_url="https://platform.example/link/tok")
+ )
+ update = _dm(
+ "/start connect",
+ entities=[{"type": "bot_command", "offset": 0, "length": 6}],
+ )
+ await a._dispatch_update(update)
+
+ assert seen == [] # never reaches the chat pipeline
+ a._api.create_user_link_token.assert_awaited_once_with(
+ platform="telegram", platform_user_id="42", platform_username="bently"
+ )
+ assert a._client.call.call_args.args == ("sendMessage",)
+ sent = a._client.call.call_args.kwargs
+ assert sent["chat_id"] == "42"
+ button = sent["reply_markup"]["inline_keyboard"][0][0]
+ assert button["text"] == "Link Account"
+ # login_url, so the /link page can verify who tapped it.
+ assert button["login_url"] == {"url": "https://platform.example/link/tok"}
+
@pytest.mark.asyncio
async def test_command_handler_error_is_contained(self):
# _dispatch_update runs as a fire-and-forget task — a raising command
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands.py
index dc0eaed13a..864cdd3515 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands.py
@@ -8,11 +8,16 @@ URL button.
import html
import logging
-from typing import Any, Optional
+from typing import Any, Awaitable, Callable, Optional
from backend.copilot.bot import sessions
from backend.copilot.bot.bot_backend import BotBackend
-from backend.copilot.bot.command_core import CommandReply, setup_reply, unlink_reply
+from backend.copilot.bot.command_core import (
+ CommandReply,
+ dm_link_reply,
+ setup_reply,
+ unlink_reply,
+)
from .api_client import TelegramClient
from .targets import encode_target
@@ -20,6 +25,10 @@ from .text import to_html
logger = logging.getLogger(__name__)
+# The adapter's send_link(channel_id, text, link_label, link_url): it renders a
+# login_url button, so the /link page can verify who tapped it.
+SendLink = Callable[[str, str, str, str], Awaitable[None]]
+
# Published to Telegram's command menu via setMyCommands on startup.
COMMAND_MENU = [
{"command": "setup", "description": "Link this group to an AutoGPT account"},
@@ -30,9 +39,9 @@ COMMAND_MENU = [
_HELP_TEXT = (
"**AutoGPT for Telegram**\n"
+ "• Message me directly to chat with your personal AutoGPT account.\n"
"• Add me to a group and run /setup to link it to an AutoGPT account.\n"
"• Mention me (or reply to my messages) in a group to chat.\n"
- "• Message me directly to chat with your personal AutoGPT account.\n"
"• Run /new to start a fresh conversation.\n"
"• Run /unlink to manage your linked groups and DM."
)
@@ -58,7 +67,11 @@ def parse_command(message: dict[str, Any], bot_username: str) -> Optional[str]:
async def handle(
- api: BotBackend, client: TelegramClient, message: dict[str, Any], command: str
+ api: BotBackend,
+ client: TelegramClient,
+ message: dict[str, Any],
+ command: str,
+ send_link: SendLink,
) -> None:
chat = message.get("chat") or {}
sender = message.get("from") or {}
@@ -106,17 +119,26 @@ async def handle(
return
if command in ("setup", "start"):
if is_private:
- await _send(
- client,
- chat_id,
- CommandReply(
- text=(
- "/setup links a group. To link your own DMs, just send "
- "me a message and I'll walk you through it."
- )
- ),
- message,
+ # A private chat has no group to link, so both commands link the
+ # DM. /start is what the Bots page's "Message bot" link sends.
+ reply = await dm_link_reply(
+ api,
+ platform="telegram",
+ platform_display="Telegram",
+ platform_user_id=str(sender.get("id", "")),
+ platform_username=sender.get("username")
+ or sender.get("first_name")
+ or "unknown",
)
+ if reply.button_label and reply.button_url:
+ await send_link(
+ encode_target(chat_id, message.get("message_thread_id")),
+ reply.text,
+ reply.button_label,
+ reply.button_url,
+ )
+ else:
+ await _send(client, chat_id, reply, message)
return
reply = await setup_reply(
api,
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands_test.py
index a3bbd3cbed..2b81949ade 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/commands_test.py
@@ -46,7 +46,9 @@ async def test_setup_in_group_mints_link_and_sends_button():
button_url="https://x/l",
)
with patch(f"{_CMD}.setup_reply", new=AsyncMock(return_value=reply)) as sr:
- await commands.handle(MagicMock(), client, _message("/setup"), "setup")
+ await commands.handle(
+ MagicMock(), client, _message("/setup"), "setup", AsyncMock()
+ )
kwargs = sr.call_args.kwargs
assert kwargs["platform"] == "telegram"
assert kwargs["server_noun"] == "group"
@@ -58,22 +60,122 @@ async def test_setup_in_group_mints_link_and_sends_button():
@pytest.mark.asyncio
-async def test_setup_in_private_chat_redirects_to_dm_linking():
[email protected]("text", ["/start", "/start connect", "/setup"])
+async def test_start_in_private_chat_sends_the_dm_link_button(text):
+ # The Bots page's "Message bot" link opens t.me/<bot>?start=connect, which
+ # Telegram delivers as "/start connect" in the private chat.
+ client = MagicMock()
+ client.call = AsyncMock()
+ send_link = AsyncMock()
+ message = _message(text, chat_type="private")
+ message["chat"] = {"id": 42, "type": "private"}
+ reply = CommandReply(
+ text="**Welcome to AutoGPT**",
+ button_label="Link Account",
+ button_url="https://x/link/dm",
+ )
+ command = commands.parse_command(message, "OurBot")
+ with (
+ patch(f"{_CMD}.setup_reply", new=AsyncMock()) as sr,
+ patch(f"{_CMD}.dm_link_reply", new=AsyncMock(return_value=reply)) as dr,
+ ):
+ await commands.handle(MagicMock(), client, message, command, send_link)
+ sr.assert_not_called()
+ assert dr.call_args.kwargs["platform"] == "telegram"
+ assert dr.call_args.kwargs["platform_user_id"] == "42"
+ assert dr.call_args.kwargs["platform_username"] == "bently"
+ send_link.assert_awaited_once_with(
+ "42", "**Welcome to AutoGPT**", "Link Account", "https://x/link/dm"
+ )
+ client.call.assert_not_called()
+
+
+async def test_start_in_private_chat_when_already_linked_sends_plain_text():
client = MagicMock()
client.call = AsyncMock()
- with patch(f"{_CMD}.setup_reply", new=AsyncMock()) as sr:
+ send_link = AsyncMock()
+ reply = CommandReply(text="Your Telegram DMs are linked to AutoGPT.")
+ with patch(f"{_CMD}.dm_link_reply", new=AsyncMock(return_value=reply)):
await commands.handle(
- MagicMock(), client, _message("/setup", chat_type="private"), "setup"
+ MagicMock(),
+ client,
+ _message("/start", chat_type="private"),
+ "start",
+ send_link,
)
- sr.assert_not_called()
- assert "send me a message" in client.call.call_args.kwargs["text"]
+ send_link.assert_not_called()
+ assert "DMs are linked" in client.call.call_args.kwargs["text"]
+
+
+async def test_start_when_already_linked_names_the_account_in_the_sent_text():
+ # Runs the real dm_link_reply + HTML conversion, so the masked email
+ # reaches Telegram literally (its *** must not turn into emphasis).
+ client = MagicMock()
+ client.call = AsyncMock()
+ api = MagicMock()
+ api.resolve_user = AsyncMock(
+ return_value=MagicMock(linked=True, account_hint="b***@agpt.co")
+ )
+ message = _message("/start", chat_type="private")
+ message["chat"] = {"id": 42, "type": "private"}
+ await commands.handle(api, client, message, "start", AsyncMock())
+ api.resolve_user.assert_awaited_once_with("telegram", "42", include_account=True)
+ sent = client.call.call_args.kwargs
+ assert "reply_markup" not in sent
+ assert "linked to the AutoGPT account b***@agpt.co." in sent["text"]
+ assert "Send /unlink, sign in as b***@agpt.co" in sent["text"]
+
+
+async def test_unlink_in_private_chat_points_at_bots_settings():
+ client = MagicMock()
+ client.call = AsyncMock()
+ message = _message("/unlink", chat_type="private")
+ message["chat"] = {"id": 42, "type": "private"}
+ with patch(
+ f"{_CMD}.unlink_reply",
+ return_value=CommandReply(
+ text="Unlinking requires authentication",
+ button_label="Open Settings",
+ button_url="https://x/settings/bots",
+ ),
+ ):
+ await commands.handle(MagicMock(), client, message, "unlink", AsyncMock())
+ sent = client.call.call_args.kwargs
+ assert sent["chat_id"] == "42"
+ button = sent["reply_markup"]["inline_keyboard"][0][0]
+ assert button["url"] == "https://x/settings/bots"
+
+
+async def test_start_in_group_still_links_the_group():
+ client = MagicMock()
+ client.call = AsyncMock()
+ reply = CommandReply(
+ text="**Set up AutoGPT for Builders**",
+ button_label="Link Group",
+ button_url="https://x/l",
+ )
+ with (
+ patch(f"{_CMD}.setup_reply", new=AsyncMock(return_value=reply)) as sr,
+ patch(f"{_CMD}.dm_link_reply", new=AsyncMock()) as dr,
+ ):
+ await commands.handle(
+ MagicMock(), client, _message("/start"), "start", AsyncMock()
+ )
+ dr.assert_not_called()
+ assert sr.call_args.kwargs["platform_server_id"] == "-100123456"
+ sent = client.call.call_args.kwargs
+ assert sent["reply_markup"]["inline_keyboard"][0][0]["url"] == "https://x/l"
@pytest.mark.asyncio
async def test_help_sends_usage_text():
client = MagicMock()
client.call = AsyncMock()
- await commands.handle(MagicMock(), client, _message("/help"), "help")
+ await commands.handle(MagicMock(), client, _message("/help"), "help", AsyncMock())
text = client.call.call_args.kwargs["text"]
# Rendered as real HTML — an escaped-entity regression would show the
# user literal &lt;b&gt; junk.
@@ -88,7 +190,7 @@ async def test_new_clears_the_target_session():
msg = _message("/new")
msg["message_thread_id"] = 7
with patch(f"{_CMD}.sessions.clear_session", new=AsyncMock()) as clear:
- await commands.handle(MagicMock(), client, msg, "new")
+ await commands.handle(MagicMock(), client, msg, "new", AsyncMock())
clear.assert_awaited_once_with("telegram", "-100123456|7")
assert "fresh conversation" in client.call.call_args.kwargs["text"]
@@ -98,7 +200,7 @@ async def test_commands_track_command_used_with_group_scope():
client = MagicMock()
client.call = AsyncMock()
api = MagicMock()
- await commands.handle(api, client, _message("/help"), "help")
+ await commands.handle(api, client, _message("/help"), "help", AsyncMock())
api.track_event.assert_called_once_with(
platform="telegram",
event_type="command_used",
@@ -112,5 +214,7 @@ async def test_dm_commands_track_without_server_id():
client = MagicMock()
client.call = AsyncMock()
api = MagicMock()
- await commands.handle(api, client, _message("/help", chat_type="private"), "help")
+ await commands.handle(
+ api, client, _message("/help", chat_type="private"), "help", AsyncMock()
+ )
assert api.track_event.call_args.kwargs["server_id"] is None
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
index 9eea3c74ed..ae81e70da1 100644
--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
@@ -109,6 +109,7 @@ __all__ = [
@dataclass
class ResolveResult:
linked: bool
+ account_hint: str | None = None
@dataclass
@@ -264,12 +265,18 @@ class BotBackend:
)
return ResolveResult(linked=resp.linked)
- async def resolve_user(self, platform: str, platform_user_id: str) -> ResolveResult:
+ async def resolve_user(
+ self, platform: str, platform_user_id: str, include_account: bool = False
+ ) -> ResolveResult:
+ """Check a DM link; ``include_account`` also fetches the masked email
+ of the linked account (an extra lookup, so only for user-facing copy).
+ """
resp = await self._client.resolve_user_link(
platform=Platform(platform.upper()),
platform_user_id=platform_user_id,
+ include_account=include_account,
)
- return ResolveResult(linked=resp.linked)
+ return ResolveResult(linked=resp.linked, account_hint=resp.account_hint)
async def list_linked_server_ids(self, platform: str, user_id: str) -> list[str]:
"""Return the platform server (guild) IDs ``user_id`` has linked.
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
index 28e3319d54..fa534c7064 100644
--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
@@ -68,6 +68,17 @@ class TestResolve:
)
result = await api.resolve_user("discord", "u1")
assert result.linked is False
+ assert result.account_hint is None
+
+ @pytest.mark.asyncio
+ async def test_resolve_user_forwards_include_account(self, api: BotBackend):
+ api._client.resolve_user_link = AsyncMock(
+ return_value=ResolveResponse(linked=True, account_hint="b***@agpt.co")
+ )
+ result = await api.resolve_user("telegram", "u1", include_account=True)
+ assert result.linked is True
+ assert result.account_hint == "b***@agpt.co"
+ assert api._client.resolve_user_link.await_args.kwargs["include_account"]
class TestListLinkedServerIds:
diff --git a/autogpt_platform/backend/backend/copilot/bot/command_core.py b/autogpt_platform/backend/backend/copilot/bot/command_core.py
index 3e2e39aecd..aef3ee552d 100644
--- a/autogpt_platform/backend/backend/copilot/bot/command_core.py
+++ b/autogpt_platform/backend/backend/copilot/bot/command_core.py
@@ -1,4 +1,4 @@
-"""Shared slash-command policy — /setup and /unlink, platform-neutral.
+"""Shared slash-command policy — /setup, /unlink and DM linking, platform-neutral.
Each adapter owns its transport (Discord interactions, Slack form POSTs) and
its rendering (View buttons vs block kit), but the *policy* — how a link token
@@ -84,6 +84,73 @@ async def setup_reply(
)
+async def dm_link_reply(
+ api: BotBackend,
+ *,
+ platform: str,
+ platform_display: str,
+ platform_user_id: str,
+ platform_username: str,
+) -> CommandReply:
+ """Greet a user who opened a DM with the bot and link it if needed.
+
+ Answers a "start" in a DM (Telegram's /start), so a user who arrives from
+ the Bots settings page gets the Link Account button straight away instead
+ of having to send a first message.
+ """
+ try:
+ resolved = await api.resolve_user(
+ platform, platform_user_id, include_account=True
+ )
+ if resolved.linked:
+ return _dm_linked_reply(platform_display, resolved.account_hint)
+ result = await api.create_user_link_token(
+ platform=platform,
+ platform_user_id=platform_user_id,
+ platform_username=platform_username,
+ )
+ except LinkAlreadyExistsError:
+ # Linked between the check and the mint.
+ return _dm_linked_reply(platform_display, None)
+ except Exception:
+ logger.exception("%s DM link token creation failed", platform)
+ return CommandReply(
+ text="Something went wrong setting up the link. Try again later."
+ )
+ return CommandReply(
+ text=(
+ "**Welcome to AutoGPT**\n\n"
+ "Tap the button below to connect this chat to your AutoGPT "
+ "account. Once linked, just message me here to chat.\n\n"
+ "This link expires in 30 minutes."
+ ),
+ button_label="Link Account",
+ button_url=result.link_url,
+ )
+
+
+def _dm_linked_reply(platform_display: str, account_hint: str | None) -> CommandReply:
+ """Say which account the DMs run as, and how to switch if it's the wrong one.
+
+ The web Bots page lists only the signed-in account's links, so someone
+ signed in elsewhere has to manage the link as the account named here.
+ """
+ if account_hint:
+ account = f"the AutoGPT account {account_hint}"
+ switch = f"sign in as {account_hint} and unlink these DMs"
+ else:
+ account = "an AutoGPT account"
+ switch = "sign in as that account and unlink these DMs"
+ return CommandReply(
+ text=(
+ f"Your {platform_display} DMs are linked to {account}. Send me a "
+ "message to start chatting.\n\n"
+ "Using a different AutoGPT account? Send /unlink, "
+ f"{switch}, then message me again to link the right one."
+ )
+ )
+
+
def unlink_reply() -> CommandReply:
"""Point the user at the Bots settings page — unlinking needs web auth."""
message = (
diff --git a/autogpt_platform/backend/backend/copilot/bot/command_core_test.py b/autogpt_platform/backend/backend/copilot/bot/command_core_test.py
index a8c29743c6..6a57bc359d 100644
--- a/autogpt_platform/backend/backend/copilot/bot/command_core_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/command_core_test.py
@@ -6,7 +6,7 @@ import pytest
from backend.util.exceptions import LinkAlreadyExistsError
-from .command_core import setup_reply, unlink_reply
+from .command_core import dm_link_reply, setup_reply, unlink_reply
_CORE = "backend.copilot.bot.command_core"
@@ -78,3 +78,86 @@ def test_unlink_without_base_url_falls_back_to_text():
reply = unlink_reply()
assert reply.button_url is None
assert "Settings → Bots" in reply.text
+
+
+def _dm_api(*, linked: bool = False, account_hint: str | None = None) -> MagicMock:
+ api = MagicMock()
+ api.resolve_user = AsyncMock(
+ return_value=MagicMock(linked=linked, account_hint=account_hint)
+ )
+ api.create_user_link_token = AsyncMock(
+ return_value=MagicMock(link_url="https://x/link/dm-tok")
+ )
+ return api
+
+
+async def _dm_link(api) -> object:
+ return await dm_link_reply(
+ api,
+ platform="telegram",
+ platform_display="Telegram",
+ platform_user_id="42",
+ platform_username="bently",
+ )
+
+
+async def test_dm_link_unlinked_user_gets_link_button():
+ api = _dm_api()
+ reply = await _dm_link(api)
+ assert reply.button_label == "Link Account"
+ assert reply.button_url == "https://x/link/dm-tok"
+ assert "expires in 30 minutes" in reply.text
+ api.resolve_user.assert_awaited_once_with("telegram", "42", include_account=True)
+ api.create_user_link_token.assert_awaited_once_with(
+ platform="telegram", platform_user_id="42", platform_username="bently"
+ )
+
+
+async def test_dm_link_linked_user_is_told_to_just_chat():
+ api = _dm_api(linked=True, account_hint="b***@agpt.co")
+ reply = await _dm_link(api)
+ assert reply.button_url is None
+ assert "Telegram DMs are linked" in reply.text
+ api.create_user_link_token.assert_not_called()
+
+
+async def test_dm_link_linked_reply_names_the_account_and_the_way_out():
+ api = _dm_api(linked=True, account_hint="b***@agpt.co")
+ reply = await _dm_link(api)
+ assert reply.text == (
+ "Your Telegram DMs are linked to the AutoGPT account b***@agpt.co. "
+ "Send me a message to start chatting.\n\n"
+ "Using a different AutoGPT account? Send /unlink, sign in as "
+ "b***@agpt.co and unlink these DMs, then message me again to link "
+ "the right one."
+ )
+
+
+async def test_dm_link_linked_reply_without_a_hint_still_offers_unlink():
+ api = _dm_api(linked=True, account_hint=None)
+ reply = await _dm_link(api)
+ assert "linked to an AutoGPT account." in reply.text
+ assert "Send /unlink, sign in as that account" in reply.text
+
+
+async def test_dm_link_race_with_existing_link_reads_as_linked():
+ api = _dm_api()
+ api.create_user_link_token = AsyncMock(side_effect=LinkAlreadyExistsError("dup"))
+ reply = await _dm_link(api)
+ assert reply.button_url is None
+ assert "linked" in reply.text
+ assert "/unlink" in reply.text
+
+
+async def test_dm_link_failure_returns_generic_message():
+ api = _dm_api()
+ api.resolve_user = AsyncMock(side_effect=RuntimeError("boom"))
+ reply = await _dm_link(api)
+ assert reply.button_url is None
+ assert "went wrong" in reply.text.lower()
diff --git a/autogpt_platform/backend/backend/platform_linking/db.py b/autogpt_platform/backend/backend/platform_linking/db.py
index f376e38834..a1ba884608 100644
--- a/autogpt_platform/backend/backend/platform_linking/db.py
+++ b/autogpt_platform/backend/backend/platform_linking/db.py
@@ -88,9 +88,35 @@ async def resolve_server_link(
return ResolveResponse(linked=owner is not None)
-async def resolve_user_link(platform: str, platform_user_id: str) -> ResolveResponse:
- owner = await find_user_link_owner(platform, platform_user_id)
- return ResolveResponse(linked=owner is not None)
+async def resolve_user_link(
+ platform: str, platform_user_id: str, include_account: bool = False
+) -> ResolveResponse:
+ if not include_account:
+ owner = await find_user_link_owner(platform, platform_user_id)
+ return ResolveResponse(linked=owner is not None)
+ link = await PlatformUserLink.prisma().find_unique(
+ where={
+ "platform_platformUserId": {
+ "platform": platform,
+ "platformUserId": platform_user_id,
+ }
+ },
+ include={"User": True},
+ )
+ if not link:
+ return ResolveResponse(linked=False)
+ email = link.User.email if link.User else None
+ return ResolveResponse(linked=True, account_hint=mask_email(email))
+
+
+def mask_email(email: str | None) -> str | None:
+ """Mask an email for showing to its owner: '[email protected]' -> 'b***@agpt.co'."""
+ if not email or "@" not in email:
+ return None
+ local, domain = email.rsplit("@", 1)
+ if not local or not domain:
+ return None
+ return f"{local[0]}***@{domain}"
# ── Token creation ────────────────────────────────────────────────────
diff --git a/autogpt_platform/backend/backend/platform_linking/db_test.py b/autogpt_platform/backend/backend/platform_linking/db_test.py
index 2b7e7bcc1a..fcaa8ebc0c 100644
--- a/autogpt_platform/backend/backend/platform_linking/db_test.py
+++ b/autogpt_platform/backend/backend/platform_linking/db_test.py
@@ -28,6 +28,7 @@ from .db import (
fetch_workspace_artifact,
get_link_token_info,
get_link_token_status,
+ mask_email,
refresh_server_link_name,
resolve_server_link,
resolve_user_link,
@@ -75,6 +76,39 @@ class TestResolve:
result = await resolve_user_link("DISCORD", "pu1")
assert result.linked is True
+ @pytest.mark.asyncio
+ async def test_user_linked_with_account_hint_masks_the_email(self):
+ with patch("backend.platform_linking.db.PlatformUserLink") as mock_user_link:
+ find = AsyncMock(
+ return_value=MagicMock(
+ userId="u-xyz", User=MagicMock(email="[email protected]")
+ )
+ )
+ mock_user_link.prisma.return_value.find_unique = find
+ result = await resolve_user_link("TELEGRAM", "pu1", include_account=True)
+ assert result.linked is True
+ assert result.account_hint == "b***@agpt.co"
+ assert find.await_args.kwargs["include"] == {"User": True}
+
+ @pytest.mark.asyncio
+ async def test_user_linked_without_include_skips_the_account(self):
+ with patch("backend.platform_linking.db.PlatformUserLink") as mock_user_link:
+ mock_user_link.prisma.return_value.find_unique = AsyncMock(
+ return_value=MagicMock(userId="u-xyz")
+ )
+ result = await resolve_user_link("TELEGRAM", "pu1")
+ assert result.account_hint is None
+
+ @pytest.mark.asyncio
+ async def test_user_unlinked_with_account_hint(self):
+ with patch("backend.platform_linking.db.PlatformUserLink") as mock_user_link:
+ mock_user_link.prisma.return_value.find_unique = AsyncMock(
+ return_value=None
+ )
+ result = await resolve_user_link("TELEGRAM", "pu1", include_account=True)
+ assert result.linked is False
+ assert result.account_hint is None
+
@pytest.mark.asyncio
async def test_user_unlinked(self):
with patch("backend.platform_linking.db.PlatformUserLink") as mock_user_link:
@@ -85,6 +119,23 @@ class TestResolve:
assert result.linked is False
+ "email, expected",
+ [
+ ("[email protected]", "b***@agpt.co"),
+ ("[email protected]", "a***@x.io"),
+ ("[email protected]", "f***@sub.example.com"),
+ (None, None),
+ ("", None),
+ ("no-at-sign", None),
+ ("@agpt.co", None),
+ ("user@", None),
+ ],
+)
+def test_mask_email(email, expected):
+ assert mask_email(email) == expected
+
+
# ── Token creation ───────────────────────────────────────────────────
diff --git a/autogpt_platform/backend/backend/platform_linking/manager.py b/autogpt_platform/backend/backend/platform_linking/manager.py
index 4fa4515e26..cc91780ef5 100644
--- a/autogpt_platform/backend/backend/platform_linking/manager.py
+++ b/autogpt_platform/backend/backend/platform_linking/manager.py
@@ -51,10 +51,10 @@ class PlatformLinkingManager(AppService):
@expose
async def resolve_user_link(
- self, platform: Platform, platform_user_id: str
+ self, platform: Platform, platform_user_id: str, include_account: bool = False
) -> ResolveResponse:
return await platform_linking_db().resolve_user_link(
- platform.value, platform_user_id
+ platform.value, platform_user_id, include_account
)
@expose
diff --git a/autogpt_platform/backend/backend/platform_linking/manager_test.py b/autogpt_platform/backend/backend/platform_linking/manager_test.py
index 16b7415831..2a71683b7d 100644
--- a/autogpt_platform/backend/backend/platform_linking/manager_test.py
+++ b/autogpt_platform/backend/backend/platform_linking/manager_test.py
@@ -88,9 +88,26 @@ class TestManagerWiring:
return_value=db_mock,
):
result = await manager.resolve_user_link(Platform.DISCORD, "pu1")
- db_mock.resolve_user_link.assert_awaited_once_with("DISCORD", "pu1")
+ db_mock.resolve_user_link.assert_awaited_once_with("DISCORD", "pu1", False)
assert result.linked is False
+ @pytest.mark.asyncio
+ async def test_resolve_user_link_forwards_include_account(self):
+ manager = PlatformLinkingManager()
+ db_mock = MagicMock()
+ db_mock.resolve_user_link = AsyncMock(
+ return_value=ResolveResponse(linked=True, account_hint="b***@agpt.co")
+ )
+ with patch(
+ "backend.platform_linking.manager.platform_linking_db",
+ return_value=db_mock,
+ ):
+ result = await manager.resolve_user_link(
+ Platform.TELEGRAM, "pu1", include_account=True
+ )
+ db_mock.resolve_user_link.assert_awaited_once_with("TELEGRAM", "pu1", True)
+ assert result.account_hint == "b***@agpt.co"
+
@pytest.mark.asyncio
async def test_get_user_dm_id_returns_matching_platform_link(self):
manager = PlatformLinkingManager()
diff --git a/autogpt_platform/backend/backend/platform_linking/models.py b/autogpt_platform/backend/backend/platform_linking/models.py
index b26b17594c..d642bce30d 100644
--- a/autogpt_platform/backend/backend/platform_linking/models.py
+++ b/autogpt_platform/backend/backend/platform_linking/models.py
@@ -191,6 +191,10 @@ class LinkTokenInfoResponse(BaseModel):
class ResolveResponse(BaseModel):
linked: bool
+ # Masked email of the linked AutoGPT account (e.g. "b***@agpt.co"), only
+ # filled when the caller asks for it, so the bot can tell a user which
+ # account their DMs run as without exposing the full address.
+ account_hint: str | None = None
class PlatformLinkInfo(BaseModel):
@@ -235,6 +239,9 @@ class BotPlatformInfo(BaseModel):
# the UI never calls a Slack workspace a server.
server_noun: str = "server"
add_bot_url: str | None = None
+ # Opens a DM with the bot (currently only Telegram). The settings page
+ # leads with it: DMing the bot is the quickest way to link.
+ dm_url: str | None = None
dm_link: PlatformUserLinkInfo | None = None
server_links: list[PlatformLinkInfo] = Field(default_factory=list)
# Set while an install by this user awaits its account link (currently
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsx
index 7a76863d34..abedeef8ee 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/__tests__/main.test.tsx
@@ -45,6 +45,22 @@ function slackPlatform(
};
}
+function telegramPlatform(
+ overrides: Partial<BotPlatformInfo> = {},
+): BotPlatformInfo {
+ return {
+ platform: "TELEGRAM",
+ display_name: "Telegram",
+ icon: "telegram.png",
+ server_noun: "group",
+ add_bot_url: "https://t.me/AutoGPTBot?startgroup=true",
+ dm_url: "https://t.me/AutoGPTBot?start=connect",
+ dm_link: undefined,
+ server_links: [],
+ ...overrides,
+ };
+}
+
describe("SettingsBotsPage", () => {
test("renders the header and the Discord card with an Add bot button", async () => {
server.use(getListBotPlatformsMockHandler([discordPlatform()]));
@@ -309,4 +325,62 @@ describe("SettingsBotsPage", () => {
expect(screen.getByText("bently")).toBeDefined();
});
});
+
+ test("leads the Telegram card with messaging the bot, and keeps adding to a group as a second option", async () => {
+ server.use(getListBotPlatformsMockHandler([telegramPlatform()]));
+
+ render(<SettingsBotsPage />);
+
+ const message = await screen.findByRole("link", {
+ name: /message bot on telegram/i,
+ });
+ expect(message.getAttribute("href")).toBe(
+ "https://t.me/AutoGPTBot?start=connect",
+ );
+ expect(message.getAttribute("target")).toBe("_blank");
+
+ const addToGroup = screen.getByRole("link", { name: /add to a group/i });
+ expect(addToGroup.getAttribute("href")).toBe(
+ "https://t.me/AutoGPTBot?startgroup=true",
+ );
+ expect(
+ message.compareDocumentPosition(addToGroup) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ screen.queryByRole("link", { name: /add bot to telegram/i }),
+ ).toBeNull();
+ expect(
+ screen.getByText(/no groups linked yet\. use "add to a group"/i),
+ ).toBeDefined();
+ });
+
+ test("falls back to the add-bot button when the backend sends no DM link", async () => {
+ server.use(
+ getListBotPlatformsMockHandler([telegramPlatform({ dm_url: null })]),
+ );
+
+ render(<SettingsBotsPage />);
+
+ const addBot = await screen.findByRole("link", {
+ name: /add bot to telegram/i,
+ });
+ expect(addBot.getAttribute("href")).toBe(
+ "https://t.me/AutoGPTBot?startgroup=true",
+ );
+ expect(
+ screen.queryByRole("link", { name: /message bot on telegram/i }),
+ ).toBeNull();
+ });
+
+ test("only Telegram gets the message-the-bot button", async () => {
+ server.use(getListBotPlatformsMockHandler([discordPlatform()]));
+
+ render(<SettingsBotsPage />);
+
+ expect(
+ await screen.findByRole("link", { name: /add bot to discord/i }),
+ ).toBeDefined();
+ expect(screen.queryByRole("link", { name: /message bot on/i })).toBeNull();
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCard.tsx
index a418d9477d..dd59647ea4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCard.tsx
@@ -9,6 +9,7 @@ import type { BotPlatformInfo } from "@/app/api/__generated__/models/botPlatform
import { BotCardDmTile } from "./BotCardDmTile";
import { BotCardServerList } from "./BotCardServerList";
+import { getAddBotLabel } from "./helpers";
import { useBotCard } from "./useBotCard";
import { ArrowUpRight01Icon, PlusSignIcon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
@@ -23,6 +24,8 @@ export function BotCard({ platform }: Props) {
const pendingInstall = platform.pending_install ?? null;
// Optional in the generated client (it has a server-side default).
const serverNoun = platform.server_noun ?? "server";
+ const dmUrl = platform.dm_url ?? null;
+ const addBotLabel = getAddBotLabel(platform, serverNoun);
return (
<Card className="flex flex-col gap-5 p-5">
@@ -58,6 +61,19 @@ export function BotCard({ platform }: Props) {
Open AutoGPT in {platform.display_name}
</Button>
) : null}
+ {dmUrl ? (
+ <Button
+ as="NextLink"
+ href={dmUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ variant="primary"
+ size="small"
+ rightIcon={<Icon icon={ArrowUpRight01Icon} size={16} />}
+ >
+ Message bot on {platform.display_name}
+ </Button>
+ ) : null}
{/* Kept alongside the pending action, not replaced by it: adding the
bot to a second {serverNoun} is a normal thing to want while the
first install is still waiting on its DM. */}
@@ -67,11 +83,11 @@ export function BotCard({ platform }: Props) {
<Button
as="NextLink"
href={platform.add_bot_url}
- variant={pendingInstall ? "outline" : "primary"}
+ variant={pendingInstall || dmUrl ? "outline" : "primary"}
size="small"
leftIcon={<Icon icon={PlusSignIcon} size={16} />}
>
- Add bot to {platform.display_name}
+ {addBotLabel}
</Button>
) : null}
</div>
@@ -106,6 +122,7 @@ export function BotCard({ platform }: Props) {
<BotCardServerList
platformName={platform.display_name}
serverNoun={serverNoun}
+ addBotLabel={addBotLabel}
serverLinks={serverLinks}
isPending={isPending}
onUnlink={unlinkServerLink}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsx
index cfeceb28b1..2d02246b57 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsx
@@ -16,6 +16,7 @@ import { Icon } from "@/components/atoms/Icon/Icon";
type Props = {
platformName: string;
serverNoun: string;
+ addBotLabel: string;
serverLinks: PlatformLinkInfo[];
isPending: (linkId: string) => boolean;
onUnlink: (linkId: string) => void;
@@ -24,6 +25,7 @@ type Props = {
export function BotCardServerList({
platformName,
serverNoun,
+ addBotLabel,
serverLinks,
isPending,
onUnlink,
@@ -32,9 +34,9 @@ export function BotCardServerList({
return (
<div className="rounded-large border border-dashed border-zinc-200 px-4 py-3">
<Text variant="small" as="span" className="text-zinc-500">
- No {serverNoun}s linked yet. Use &quot;Add bot to {platformName}&quot;{" "}
- to invite the bot — already added it? Run <code>/setup</code> there to
- finish connecting.
+ No {serverNoun}s linked yet. Use &quot;{addBotLabel}&quot; to invite
+ the bot — already added it? Run <code>/setup</code> there to finish
+ connecting.
</Text>
</div>
);
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/helpers.ts
new file mode 100644
index 0000000000..b2bab51324
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/helpers.ts
@@ -0,0 +1,9 @@
+import type { BotPlatformInfo } from "@/app/api/__generated__/models/botPlatformInfo";
+
+export function getAddBotLabel(platform: BotPlatformInfo, serverNoun: string) {
+ // With a DM link the card leads with messaging the bot, so adding it to a
+ // group reads as the optional extra it is.
+ return platform.dm_url
+ ? `Add to a ${serverNoun}`
+ : `Add bot to ${platform.display_name}`;
+}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 073ba9e845..1899cd501b 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -18845,6 +18845,10 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Add Bot Url"
},
+ "dm_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Dm Url"
+ },
"dm_link": {
"anyOf": [
{ "$ref": "#/components/schemas/PlatformUserLinkInfo" },