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.

feat(backend/copilot-bot): proactive posting for Slack and Telegram (#13588)

Bentlyd2c85510310f
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py
index e4b5fbdcc4..1a12167a5b 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py
@@ -40,11 +40,10 @@ from backend.copilot.bot.adapters.shared import InboundFile, collect_attachments
from backend.copilot.bot.bot_backend import BotBackend
from backend.copilot.bot.config import MAX_INBOUND_ATTACHMENTS
from backend.copilot.bot.text import iter_chunks, resolve_mentions
-from backend.data.bot_installs import (
- get_bot_install,
- is_install_revoked,
- revoke_bot_install,
-)
+
+# Accessor, not direct Prisma: the outbound half also runs in the Prisma-less
+# copilot-bot bridge pod, which must go through the DatabaseManager.
+from backend.data.db_accessors import bot_installs_db
from backend.platform_linking.models import Platform
from . import commands, config, oauth, signing
@@ -147,13 +146,19 @@ class SlackAdapter(WebhookAdapter):
):
return client
self._evict(team_id)
- install = await get_bot_install(Platform.SLACK, team_id) if team_id else None
+ install = (
+ await bot_installs_db().get_bot_install(Platform.SLACK, team_id)
+ if team_id
+ else None
+ )
if install is None:
# A workspace that explicitly uninstalled / revoked us gets NOTHING —
# the static token belongs to the app's own workspace and must never
# be used on a revoked one's behalf. Fallback is only for
# never-installed refs (single-workspace mode, raw proactive refs).
- if team_id and await is_install_revoked(Platform.SLACK, team_id):
+ if team_id and await bot_installs_db().is_install_revoked(
+ Platform.SLACK, team_id
+ ):
return None
token = config.get_bot_token()
else:
@@ -212,7 +217,7 @@ class SlackAdapter(WebhookAdapter):
if event.get("type") in _UNINSTALL_EVENTS:
if team_id:
self._evict(team_id)
- await revoke_bot_install(Platform.SLACK, team_id)
+ await bot_installs_db().revoke_bot_install(Platform.SLACK, team_id)
return
if self._on_message_callback is None:
return
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.py
index 53a97c1e01..4e1c2a9265 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.py
@@ -228,10 +228,11 @@ class TestUninstall:
async def test_uninstall_event_revokes_and_evicts(self, adapter):
adapter._clients["T5"] = MagicMock()
adapter._bot_user_ids["T5"] = "UBOT"
+ revoke = AsyncMock()
with patch(
- "backend.copilot.bot.adapters.slack.adapter.revoke_bot_install",
- new=AsyncMock(),
- ) as revoke:
+ "backend.copilot.bot.adapters.slack.adapter.bot_installs_db",
+ return_value=MagicMock(revoke_bot_install=revoke),
+ ):
await adapter._dispatch_event({"type": "app_uninstalled"}, "T5")
revoke.assert_awaited_once()
assert "T5" not in adapter._clients
@@ -301,11 +302,12 @@ class TestPerWorkspaceClient:
install = BotInstallCredentials(
team_id="T1", bot_token="xoxb-abc", bot_user_id="UBOT"
)
+ lookup = AsyncMock(return_value=install)
with (
patch(
- "backend.copilot.bot.adapters.slack.adapter.get_bot_install",
- new=AsyncMock(return_value=install),
- ) as lookup,
+ "backend.copilot.bot.adapters.slack.adapter.bot_installs_db",
+ return_value=MagicMock(get_bot_install=lookup),
+ ),
patch(
"backend.copilot.bot.adapters.slack.adapter.AsyncWebClient"
) as web_client,
@@ -322,12 +324,11 @@ class TestPerWorkspaceClient:
a = SlackAdapter(MagicMock())
with (
patch(
- "backend.copilot.bot.adapters.slack.adapter.get_bot_install",
- new=AsyncMock(return_value=None),
- ),
- patch(
- "backend.copilot.bot.adapters.slack.adapter.is_install_revoked",
- new=AsyncMock(return_value=False),
+ "backend.copilot.bot.adapters.slack.adapter.bot_installs_db",
+ return_value=MagicMock(
+ get_bot_install=AsyncMock(return_value=None),
+ is_install_revoked=AsyncMock(return_value=False),
+ ),
),
patch(
"backend.copilot.bot.adapters.slack.adapter.config.get_bot_token",
@@ -349,8 +350,8 @@ class TestPerWorkspaceClient:
install = BotInstallCredentials(team_id="T1", bot_token="xoxb-new")
with (
patch(
- "backend.copilot.bot.adapters.slack.adapter.get_bot_install",
- new=AsyncMock(return_value=install),
+ "backend.copilot.bot.adapters.slack.adapter.bot_installs_db",
+ return_value=MagicMock(get_bot_install=AsyncMock(return_value=install)),
),
patch(
"backend.copilot.bot.adapters.slack.adapter.AsyncWebClient"
@@ -367,12 +368,11 @@ class TestPerWorkspaceClient:
a = SlackAdapter(MagicMock())
with (
patch(
- "backend.copilot.bot.adapters.slack.adapter.get_bot_install",
- new=AsyncMock(return_value=None),
- ),
- patch(
- "backend.copilot.bot.adapters.slack.adapter.is_install_revoked",
- new=AsyncMock(return_value=True),
+ "backend.copilot.bot.adapters.slack.adapter.bot_installs_db",
+ return_value=MagicMock(
+ get_bot_install=AsyncMock(return_value=None),
+ is_install_revoked=AsyncMock(return_value=True),
+ ),
),
patch(
"backend.copilot.bot.adapters.slack.adapter.config.get_bot_token",
@@ -389,8 +389,8 @@ class TestPerWorkspaceClient:
lookup = AsyncMock(return_value=None)
with (
patch(
- "backend.copilot.bot.adapters.slack.adapter.get_bot_install",
- new=lookup,
+ "backend.copilot.bot.adapters.slack.adapter.bot_installs_db",
+ return_value=MagicMock(get_bot_install=lookup),
),
patch(
"backend.copilot.bot.adapters.slack.adapter.config.get_bot_token",
diff --git a/autogpt_platform/backend/backend/copilot/bot/app.py b/autogpt_platform/backend/backend/copilot/bot/app.py
index 6822872465..6b35867341 100644
--- a/autogpt_platform/backend/backend/copilot/bot/app.py
+++ b/autogpt_platform/backend/backend/copilot/bot/app.py
@@ -24,6 +24,7 @@ from .adapters.discord.adapter import DiscordAdapter
from .bot_backend import BotBackend
from .handler import MessageHandler
from .outbound import DeliveryResult
+from .webhook_routes import build_webhook_adapters
logger = logging.getLogger(__name__)
@@ -63,14 +64,19 @@ class CoPilotChatBridge(AppService):
async def _run_adapters(self) -> None:
api = BotBackend()
self._api = api
- adapters = _build_socket_adapters(api)
- self._adapters_by_platform = {a.platform_name: a for a in adapters}
-
- if not adapters:
+ socket_adapters = _build_socket_adapters(api)
+ # Webhook adapters' outbound halves are stateless HTTP senders — build
+ # them here too (no routes, no handler) so proactive RPCs reach them.
+ outbound_only = build_webhook_adapters(api)
+ self._adapters_by_platform = {
+ a.platform_name: a for a in (*outbound_only, *socket_adapters)
+ }
+
+ if not socket_adapters:
logger.info(
- "CoPilotChatBridge: no platform adapters configured — idling. "
- "Set AUTOPILOT_BOT_DISCORD_TOKEN (or another platform token) to "
- "enable an adapter."
+ "CoPilotChatBridge: no socket adapters configured — idling "
+ "(outbound-only webhook adapters stay reachable). Set "
+ "AUTOPILOT_BOT_DISCORD_TOKEN to enable one."
)
self._adapters_healthy = True
try:
@@ -80,14 +86,16 @@ class CoPilotChatBridge(AppService):
await api.close()
handler = MessageHandler(api)
- for adapter in adapters:
+ for adapter in socket_adapters:
adapter.on_message(handler.handle)
self._adapters_healthy = True
try:
- await asyncio.gather(*(a.start() for a in adapters))
+ await asyncio.gather(*(a.start() for a in socket_adapters))
finally:
- await asyncio.gather(*(a.stop() for a in adapters), return_exceptions=True)
+ await asyncio.gather(
+ *(a.stop() for a in socket_adapters), return_exceptions=True
+ )
await api.close()
def _on_adapters_exit(self, future: "Future[None]") -> None:
diff --git a/autogpt_platform/backend/backend/copilot/bot/app_test.py b/autogpt_platform/backend/backend/copilot/bot/app_test.py
index f6525e1e63..3245697da2 100644
--- a/autogpt_platform/backend/backend/copilot/bot/app_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/app_test.py
@@ -5,6 +5,7 @@ into ``outbound`` — including the casing round-trip (``platform.value`` vs
``platform_name``) and the no-adapter guard.
"""
+import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -91,3 +92,67 @@ async def test_list_channels_routes_to_outbound():
result = await bridge.list_channels(platform=Platform.DISCORD, user_id="u1")
assert result == []
lister.assert_awaited_once()
+
+
+async def test_send_message_reaches_webhook_platform_adapter():
+ # Webhook platforms (Slack/Telegram) live in _adapters_by_platform too —
+ # the proactive RPC must resolve them just like the socket ones.
+ bridge, _ = _bridge()
+ telegram = MagicMock()
+ telegram.platform_name = "telegram"
+ bridge._adapters_by_platform["telegram"] = telegram
+ expected = DeliveryResult(ok=True, kind="message", channel_id="-100555")
+ with patch(
+ "backend.copilot.bot.app.outbound.deliver_message",
+ new=AsyncMock(return_value=expected),
+ ) as deliver:
+ result = await bridge.send_message_to_channel(
+ platform=Platform.TELEGRAM, user_id="u1", channel="-100555", content="hi"
+ )
+ assert result is expected
+ assert deliver.await_args.args[0] is telegram
+
+
+async def test_run_adapters_exposes_webhook_adapters_outbound_only():
+ # With no socket adapters the bridge idles, but webhook adapters must
+ # still be registered for outbound — and never started or route-mounted.
+ bridge = CoPilotChatBridge.__new__(CoPilotChatBridge)
+ bridge._adapters_healthy = False
+ bridge._api = None
+ bridge._adapters_by_platform = {}
+
+ slack = MagicMock()
+ slack.platform_name = "slack"
+ telegram = MagicMock()
+ telegram.platform_name = "telegram"
+ api = MagicMock()
+ api.close = AsyncMock()
+
+ with (
+ patch("backend.copilot.bot.app.BotBackend", return_value=api),
+ patch("backend.copilot.bot.app._build_socket_adapters", return_value=[]),
+ patch(
+ "backend.copilot.bot.app.build_webhook_adapters",
+ return_value=[slack, telegram],
+ ),
+ ):
+ task = asyncio.create_task(bridge._run_adapters())
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+ try:
+ assert bridge._adapters_by_platform == {
+ "slack": slack,
+ "telegram": telegram,
+ }
+ assert bridge._adapters_healthy is True
+ # Outbound-only: no inbound wiring in the bridge.
+ slack.on_message.assert_not_called()
+ slack.register_routes.assert_not_called()
+ telegram.on_message.assert_not_called()
+ telegram.register_routes.assert_not_called()
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
diff --git a/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py
index 8ef1fa1e85..65eaf3e3e3 100644
--- a/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py
+++ b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py
@@ -29,19 +29,25 @@ def register_webhook_adapters(app: FastAPI, api: BotBackend) -> None:
cleanup) — matching the pattern used by the socket bridge in ``app.py``.
"""
handler = MessageHandler(api)
- adapters = _build_webhook_adapters(api)
+ adapters = build_webhook_adapters(api)
for adapter in adapters:
adapter.on_message(handler.handle)
adapter.register_routes(app)
logger.info(f"Mounted {len(adapters)} webhook adapter(s) on the main backend API")
-def _build_webhook_adapters(api: BotBackend) -> list[WebhookAdapter]:
+def build_webhook_adapters(api: BotBackend) -> list[WebhookAdapter]:
"""Instantiate webhook adapters from configured platform credentials.
Slack / Telegram / Teams / WhatsApp adapters slot in here as they land —
each gated on its own credentials being set, so an unconfigured platform
mounts nothing.
+
+ Two consumers share this factory (keeping platform names confined to it):
+ ``register_webhook_adapters`` mounts the adapters' inbound routes on the
+ main backend API, and the copilot-bot bridge (``app.py``) builds them
+ outbound-only — no routes, no message handler — so proactive posts can
+ reach every configured platform.
"""
adapters: list[WebhookAdapter] = []
# Signing secret is always required (inbound verification, one per app). Then
diff --git a/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py b/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py
index 6e396791d6..62b47e5218 100644
--- a/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py
@@ -5,7 +5,7 @@ from unittest.mock import MagicMock, patch
from fastapi import FastAPI
from .adapters.base import WebhookAdapter
-from .webhook_routes import _build_webhook_adapters, register_webhook_adapters
+from .webhook_routes import build_webhook_adapters, register_webhook_adapters
_SLACK_CFG = "backend.copilot.bot.webhook_routes.slack_config"
_TELEGRAM_CFG = "backend.copilot.bot.webhook_routes.telegram_config"
@@ -17,7 +17,7 @@ def test_build_webhook_adapters_empty_without_creds():
patch(f"{_SLACK_CFG}.get_signing_secret", return_value=""),
patch(f"{_TELEGRAM_CFG}.get_bot_token", return_value=""),
):
- assert _build_webhook_adapters(MagicMock()) == []
+ assert build_webhook_adapters(MagicMock()) == []
def test_build_webhook_adapters_includes_slack_when_configured():
@@ -27,7 +27,7 @@ def test_build_webhook_adapters_includes_slack_when_configured():
patch(f"{_SLACK_CFG}.get_signing_secret", return_value="secret"),
patch("backend.copilot.bot.adapters.slack.adapter.AsyncWebClient"),
):
- adapters = _build_webhook_adapters(MagicMock())
+ adapters = build_webhook_adapters(MagicMock())
assert len(adapters) == 1
assert adapters[0].platform_name == "slack"
@@ -39,7 +39,7 @@ def test_build_webhook_adapters_includes_telegram_when_configured():
patch(f"{_TELEGRAM_CFG}.get_bot_token", return_value="123:abc"),
patch(f"{_TELEGRAM_CFG}.get_webhook_secret", return_value="s3cret"),
):
- adapters = _build_webhook_adapters(MagicMock())
+ adapters = build_webhook_adapters(MagicMock())
assert len(adapters) == 1
assert adapters[0].platform_name == "telegram"
@@ -51,7 +51,7 @@ def test_telegram_needs_both_token_and_webhook_secret():
patch(f"{_TELEGRAM_CFG}.get_bot_token", return_value="123:abc"),
patch(f"{_TELEGRAM_CFG}.get_webhook_secret", return_value=""),
):
- assert _build_webhook_adapters(MagicMock()) == []
+ assert build_webhook_adapters(MagicMock()) == []
def test_register_webhook_adapters_wires_each_adapter():
@@ -60,7 +60,7 @@ def test_register_webhook_adapters_wires_each_adapter():
api = MagicMock()
with patch(
- "backend.copilot.bot.webhook_routes._build_webhook_adapters",
+ "backend.copilot.bot.webhook_routes.build_webhook_adapters",
return_value=[adapter],
):
register_webhook_adapters(app, api)
diff --git a/autogpt_platform/backend/backend/copilot/tools/chat_platform.py b/autogpt_platform/backend/backend/copilot/tools/chat_platform.py
index 3eb55a39f8..b64099c0a3 100644
--- a/autogpt_platform/backend/backend/copilot/tools/chat_platform.py
+++ b/autogpt_platform/backend/backend/copilot/tools/chat_platform.py
@@ -1,11 +1,11 @@
"""Tools for the copilot to post to a linked chat platform on the user's behalf.
``post_to_chat_platform`` lets AutoPilot send a standalone message or open a new
-thread in a channel of a chat platform (Discord today; Slack/Telegram as their
-adapters land) the user has linked. The headline use case is *scheduled*
-output: "every Monday post an update in #standup" — AutoPilot schedules a
-follow-up turn (via ``schedule_followup``) whose message instructs it to post,
-and at fire time it calls this tool.
+thread in a channel of a chat platform (Discord, Slack, or Telegram) the user
+has linked. The headline use case is *scheduled* output: "every Monday post an
+update in #standup" — AutoPilot schedules a follow-up turn (via
+``schedule_followup``) whose message instructs it to post, and at fire time it
+calls this tool.
A single ``platform`` enum keeps the tool surface flat as platforms are added,
instead of one ``post_to_<platform>`` tool per platform. Delivery and
@@ -40,7 +40,14 @@ logger = logging.getLogger(__name__)
# Chat platforms with a wired bridge adapter. Add a value here (and its bot
# token check in ``_any_chat_platform_configured``) when a new adapter ships —
# the tool surface stays the same.
-SUPPORTED_PLATFORMS: tuple[str, ...] = ("discord",)
+SUPPORTED_PLATFORMS: tuple[str, ...] = ("discord", "slack", "telegram")
+
+# Telegram's Bot API can't enumerate a bot's chats, so name→ID resolution is
+# impossible there — posts must target a linked group's numeric chat ID.
+_TELEGRAM_TARGETING_HINT = (
+ "Telegram can't list channels — post using the numeric chat ID of a "
+ "group that's linked to this account."
+)
# Maps the bridge's stable DeliveryResult error codes to user-facing text the
# model can relay or act on. Anything unmapped falls back to the raw code.
@@ -78,25 +85,57 @@ def _any_chat_platform_configured() -> bool:
Cached because ``get_available_tools`` reads ``is_available`` for every tool
on every request, and constructing ``Settings()`` re-parses the env each
- time. The bot token is fixed at deploy time, so a one-time read is safe.
+ time. Bot tokens are fixed at deploy time, so a one-time read is safe.
- Assumes the copilot/executor process shares the bot token env with the
- bridge pod (true for ``poetry run app`` and the standard deployment).
+ Mirrors each platform's adapter gate (``_build_socket_adapters`` /
+ ``build_webhook_adapters``) so the tool only appears when at least one
+ platform could actually deliver. Assumes the copilot/executor process
+ shares the bot token env with the bridge pod (true for ``poetry run app``
+ and the standard deployment).
"""
- return bool(Settings().secrets.autopilot_bot_discord_token)
+ secrets = Settings().secrets
+ slack_configured = bool(
+ secrets.autopilot_bot_slack_signing_secret
+ and (
+ (
+ secrets.autopilot_bot_slack_client_id
+ and secrets.autopilot_bot_slack_client_secret
+ )
+ or secrets.autopilot_bot_slack_token
+ )
+ )
+ telegram_configured = bool(
+ secrets.autopilot_bot_telegram_token
+ and secrets.autopilot_bot_telegram_webhook_secret
+ )
+ return bool(
+ secrets.autopilot_bot_discord_token or slack_configured or telegram_configured
+ )
-def _error_message(code: str | None) -> str:
+def _error_message(code: str | None, platform_name: str = "") -> str:
if not code:
return "The post could not be completed."
- return _ERROR_MESSAGES.get(code, f"The post failed ({code}).")
+ message = _ERROR_MESSAGES.get(code, f"The post failed ({code}).")
+ if platform_name == "telegram" and code in (
+ "channel_not_found",
+ "ambiguous_channel",
+ ):
+ # The generic messages steer toward list_chat_platform_channels,
+ # which can't help on Telegram — replace them entirely.
+ return f"That chat could not be resolved. {_TELEGRAM_TARGETING_HINT}"
+ return message
def _platform_param() -> dict[str, Any]:
return {
"type": "string",
"enum": list(SUPPORTED_PLATFORMS),
- "description": "Chat platform to post to; defaults to 'discord'.",
+ "description": (
+ "Chat platform to post to: 'discord' (default), 'slack', or "
+ "'telegram'. On Telegram, 'channel' must be the numeric chat ID "
+ "of a linked group (names can't be listed there)."
+ ),
}
@@ -118,11 +157,13 @@ class PostToChatPlatformTool(BaseTool):
@property
def description(self) -> str:
return (
- "Post to a linked chat platform (e.g. Discord) for the user. "
- "mode='message' sends a message; mode='thread' opens a new thread "
- "(needs thread_name). 'channel' is a name (#standup) or numeric ID. "
- "Pair with schedule_followup for recurring posts. If the channel "
- "can't be resolved, call list_chat_platform_channels first."
+ "Post to a linked chat platform (Discord, Slack, or Telegram) for "
+ "the user. mode='message' sends a message; mode='thread' opens a "
+ "new thread (needs thread_name). 'channel' is a name (#standup) or "
+ "numeric ID — on Telegram it must be a linked group's numeric chat "
+ "ID. Pair with schedule_followup for recurring posts. On Discord "
+ "or Slack, if the channel can't be resolved, call "
+ "list_chat_platform_channels first."
)
@property
@@ -248,7 +289,7 @@ class PostToChatPlatformTool(BaseTool):
if not result.ok:
return ErrorResponse(
- message=_error_message(result.error),
+ message=_error_message(result.error, platform_name),
error=result.error or "chat_platform_post_failed",
session_id=session_id,
)
@@ -277,8 +318,9 @@ class ListChatPlatformChannelsTool(BaseTool):
def description(self) -> str:
return (
"List channels the bot can post to on a linked chat platform "
- "(e.g. Discord). Use to resolve a channel name to an ID or pick "
- "one before post_to_chat_platform."
+ "(Discord or Slack). Use to resolve a channel name to an ID or "
+ "pick one before post_to_chat_platform. Telegram can't list "
+ "channels — post there with a linked group's numeric chat ID."
)
@property
@@ -334,6 +376,8 @@ class ListChatPlatformChannelsTool(BaseTool):
message = (
f"Found {len(summaries)} channel(s) you can post to on {platform_name}."
)
+ elif platform_name == "telegram":
+ message = _TELEGRAM_TARGETING_HINT
else:
message = (
f"No postable {platform_name} channels found. Link a server via "
diff --git a/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py b/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py
index 73d4cbddd4..624a29b57a 100644
--- a/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py
@@ -9,6 +9,7 @@ from backend.copilot.bot.outbound import DeliveryResult
from backend.copilot.tools.chat_platform import (
ListChatPlatformChannelsTool,
PostToChatPlatformTool,
+ _any_chat_platform_configured,
)
from backend.copilot.tools.models import (
ChatPlatformChannelListResponse,
@@ -227,3 +228,117 @@ async def test_list_channels_requires_auth(session):
)
assert isinstance(result, ErrorResponse)
assert result.error == "auth_required"
+
+
+# ── Multi-platform (Slack / Telegram) ──────────────────────────────
+
+
[email protected]("platform_name", ["slack", "telegram"])
+async def test_post_routes_slack_and_telegram(session, platform_name):
+ bridge = _bridge()
+ bridge.send_message_to_channel.return_value = DeliveryResult(
+ ok=True, kind="message", channel_id="chan-1", ref_id="1"
+ )
+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):
+ result = await PostToChatPlatformTool()._execute(
+ user_id=_USER,
+ session=session,
+ platform=platform_name,
+ channel="-100555" if platform_name == "telegram" else "#standup",
+ content="hi",
+ )
+ assert isinstance(result, ChatPlatformPostedResponse)
+ assert result.platform == platform_name
+ forwarded = bridge.send_message_to_channel.await_args.kwargs["platform"]
+ assert forwarded.value == platform_name.upper()
+
+
+async def test_post_telegram_channel_not_found_adds_targeting_hint(session):
+ # Telegram can't list channels, so a failed name lookup must steer the
+ # model toward numeric chat IDs instead of list_chat_platform_channels.
+ bridge = _bridge()
+ bridge.send_message_to_channel.return_value = DeliveryResult(
+ ok=False, kind="message", error="channel_not_found"
+ )
+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):
+ result = await PostToChatPlatformTool()._execute(
+ user_id=_USER,
+ session=session,
+ platform="telegram",
+ channel="general",
+ content="hi",
+ )
+ assert isinstance(result, ErrorResponse)
+ assert "numeric chat ID" in result.message
+ assert "list_chat_platform_channels" not in result.message
+
+
+async def test_list_channels_telegram_empty_explains_no_listing(session):
+ bridge = _bridge()
+ bridge.list_channels.return_value = []
+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):
+ result = await ListChatPlatformChannelsTool()._execute(
+ user_id=_USER, session=session, platform="telegram"
+ )
+ assert isinstance(result, ChatPlatformChannelListResponse)
+ assert result.count == 0
+ assert "numeric chat ID" in result.message
+
+
+def _secrets(**overrides) -> MagicMock:
+ secrets = MagicMock()
+ secrets.autopilot_bot_discord_token = ""
+ secrets.autopilot_bot_slack_token = ""
+ secrets.autopilot_bot_slack_signing_secret = ""
+ secrets.autopilot_bot_slack_client_id = ""
+ secrets.autopilot_bot_slack_client_secret = ""
+ secrets.autopilot_bot_telegram_token = ""
+ secrets.autopilot_bot_telegram_webhook_secret = ""
+ for key, value in overrides.items():
+ setattr(secrets, key, value)
+ return secrets
+
+
+ "overrides,expected",
+ [
+ ({}, False),
+ ({"autopilot_bot_discord_token": "d-token"}, True),
+ # Slack mirrors the webhook mount gate: signing secret + creds.
+ ({"autopilot_bot_slack_signing_secret": "s"}, False),
+ (
+ {
+ "autopilot_bot_slack_signing_secret": "s",
+ "autopilot_bot_slack_token": "xoxb",
+ },
+ True,
+ ),
+ (
+ {
+ "autopilot_bot_slack_signing_secret": "s",
+ "autopilot_bot_slack_client_id": "id",
+ "autopilot_bot_slack_client_secret": "sec",
+ },
+ True,
+ ),
+ # Telegram needs token + webhook secret, like its mount gate.
+ ({"autopilot_bot_telegram_token": "123:abc"}, False),
+ (
+ {
+ "autopilot_bot_telegram_token": "123:abc",
+ "autopilot_bot_telegram_webhook_secret": "hex",
+ },
+ True,
+ ),
+ ],
+)
+def test_configured_gate_mirrors_adapter_gates(overrides, expected):
+ _any_chat_platform_configured.cache_clear()
+ settings = MagicMock()
+ settings.secrets = _secrets(**overrides)
+ with patch(f"{_PATH}.Settings", return_value=settings):
+ assert _any_chat_platform_configured() is expected
+ _any_chat_platform_configured.cache_clear()
diff --git a/autogpt_platform/backend/backend/data/db_accessors.py b/autogpt_platform/backend/backend/data/db_accessors.py
index 6026cf4bf2..0667e50ee7 100644
--- a/autogpt_platform/backend/backend/data/db_accessors.py
+++ b/autogpt_platform/backend/backend/data/db_accessors.py
@@ -207,3 +207,16 @@ def bot_analytics_db():
bot_analytics_db = get_database_manager_async_client()
return bot_analytics_db
+
+
+def bot_installs_db():
+ if db.is_connected():
+ from backend.data import bot_installs as _bot_installs_db
+
+ bot_installs_db = _bot_installs_db
+ else:
+ from backend.util.clients import get_database_manager_async_client
+
+ bot_installs_db = get_database_manager_async_client()
+
+ return bot_installs_db
diff --git a/autogpt_platform/backend/backend/data/db_accessors_test.py b/autogpt_platform/backend/backend/data/db_accessors_test.py
index 2577f70c77..906b7d9bb8 100644
--- a/autogpt_platform/backend/backend/data/db_accessors_test.py
+++ b/autogpt_platform/backend/backend/data/db_accessors_test.py
@@ -3,6 +3,7 @@
from unittest.mock import MagicMock, patch
from backend.api.features.orgs import db as orgs_module
+from backend.data import bot_installs as bot_installs_module
from backend.data import db_accessors
@@ -23,3 +24,22 @@ def test_orgs_db_falls_back_to_database_manager_client():
),
):
assert db_accessors.orgs_db() is client
+
+
+def test_bot_installs_db_uses_direct_module_when_connected():
+ with patch("backend.data.db_accessors.db.is_connected", return_value=True):
+ assert db_accessors.bot_installs_db() is bot_installs_module
+
+
+def test_bot_installs_db_falls_back_to_database_manager_client():
+ # The copilot-bot bridge pod has no Prisma connection — Slack's
+ # per-workspace token lookups must route through the DatabaseManager.
+ client = MagicMock()
+ with (
+ patch("backend.data.db_accessors.db.is_connected", return_value=False),
+ patch(
+ "backend.util.clients.get_database_manager_async_client",
+ return_value=client,
+ ),
+ ):
+ assert db_accessors.bot_installs_db() is client
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index f5d9839c64..7035cb676e 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -46,6 +46,7 @@ from backend.api.features.store.embeddings import backfill_missing_embeddings
from backend.copilot import db as chat_db
from backend.copilot.sharing.db import link_new_execution_to_chat_share
from backend.data import bot_analytics as bot_analytics_db
+from backend.data import bot_installs as bot_installs_db
from backend.data import db
from backend.data.analytics import (
get_accuracy_trends_and_alerts,
@@ -456,6 +457,14 @@ class DatabaseManager(AppService):
)
fetch_workspace_artifact = _(platform_linking_db.fetch_workspace_artifact)
+ # ============ Bot Installs ============ #
+ # Exposed so the Prisma-less copilot-bot bridge pod can resolve per-workspace
+ # install tokens via db_accessors.bot_installs_db().
+ get_bot_install = _(bot_installs_db.get_bot_install)
+ is_install_revoked = _(bot_installs_db.is_install_revoked)
+ upsert_bot_install = _(bot_installs_db.upsert_bot_install)
+ revoke_bot_install = _(bot_installs_db.revoke_bot_install)
+
# ============ Bot Analytics ============ #
record_bot_event = _(bot_analytics_db.record_bot_event)
record_guild_joined = _(bot_analytics_db.record_guild_joined)
@@ -727,6 +736,12 @@ class DatabaseManagerAsyncClient(AppServiceClient):
cleanup_expired_platform_link_tokens = d.cleanup_expired_platform_link_tokens
fetch_workspace_artifact = d.fetch_workspace_artifact
+ # ============ Bot Installs ============ #
+ get_bot_install = d.get_bot_install
+ is_install_revoked = d.is_install_revoked
+ upsert_bot_install = d.upsert_bot_install
+ revoke_bot_install = d.revoke_bot_install
+
# ============ Bot Analytics ============ #
record_bot_event = d.record_bot_event
record_guild_joined = d.record_guild_joined