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): add Slack adapter (webhook / Events API) (#13508)

Bently9ba6e87f5c72
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.default
index 237f030554..534bbc373a 100644
--- a/autogpt_platform/backend/.env.default
+++ b/autogpt_platform/backend/.env.default
@@ -227,6 +227,9 @@ PLATFORM_LINK_BASE_URL=http://localhost:3000/link
# CoPilot chat-platform bridge (Discord/Telegram/Slack)
# Uses FRONTEND_BASE_URL (above) for link confirmation pages.
AUTOPILOT_BOT_DISCORD_TOKEN=
+# Slack adapter — set BOTH to mount the Slack webhook routes on the main API.
+AUTOPILOT_BOT_SLACK_TOKEN=
+AUTOPILOT_BOT_SLACK_SIGNING_SECRET=
# Communication Services
DISCORD_BOT_TOKEN=
diff --git a/autogpt_platform/backend/backend/copilot/bot/README.md b/autogpt_platform/backend/backend/copilot/bot/README.md
index 792e8faa71..13cca61b54 100644
--- a/autogpt_platform/backend/backend/copilot/bot/README.md
+++ b/autogpt_platform/backend/backend/copilot/bot/README.md
@@ -36,7 +36,8 @@ See `backend/.env.default` for the full list with documentation. Minimum setup:
| Variable | Purpose |
|----------|---------|
-| `AUTOPILOT_BOT_DISCORD_TOKEN` | Discord bot token — enables the Discord adapter |
+| `AUTOPILOT_BOT_DISCORD_TOKEN` | Discord bot token — enables the Discord (socket) adapter |
+| `AUTOPILOT_BOT_SLACK_TOKEN` + `AUTOPILOT_BOT_SLACK_SIGNING_SECRET` | Slack bot token + signing secret — set **both** to mount the Slack (webhook / Events API) adapter on the main backend API |
| `FRONTEND_BASE_URL` | Frontend base URL for link confirmation pages (shared with the rest of the backend) |
| `REDIS_HOST` / `REDIS_PORT` | Session + thread subscription state + copilot stream subscription (inherited from the shared backend config) |
| `PLATFORMLINKINGMANAGER_HOST` | DNS name of the `PlatformLinkingManager` service pod (cluster-internal RPC) |
@@ -54,10 +55,18 @@ bot/
├── webhook_routes.py # Mounts webhook adapters' inbound routes on the main API
└── adapters/
├── base.py # PlatformAdapter (outbound) + SocketAdapter / WebhookAdapter + MessageContext
- └── discord/
- ├── adapter.py # Gateway connection, events, sends, thread creation
- ├── commands.py # Slash commands (/setup, /help, /unlink)
- └── config.py # Discord token + platform limits
+ ├── shared.py # Platform-agnostic adapter helpers (attachments, history budget, bot-loop guard)
+ ├── discord/ # SocketAdapter — Discord Gateway
+ │ ├── adapter.py # Gateway connection, events, sends, thread creation
+ │ ├── commands.py # Slash commands (/setup, /help, /unlink)
+ │ └── config.py # Discord token + platform limits
+ └── slack/ # WebhookAdapter — Slack Events API
+ ├── adapter.py # Inbound event/command routes, sends, mrkdwn, attachments
+ ├── commands.py # Slash commands (/setup, /help, /unlink)
+ ├── config.py # Slack token + signing secret + platform limits
+ ├── signing.py # HMAC-SHA256 request signature verification
+ ├── text.py # CommonMark → Slack mrkdwn
+ └── app-manifest.yaml # Importable Slack app definition (scopes, events, commands)
```
**Connector taxonomy.** `PlatformAdapter` is the outbound contract the core
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/__init__.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py
new file mode 100644
index 0000000000..c6ed48ae18
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py
@@ -0,0 +1,514 @@
+"""Slack adapter — webhook-based (Events API).
+
+Mounts inbound Events API + slash-command routes on the main backend API. All
+platform-agnostic logic (attachment policy, mention allowlist, chunk splitting,
+history budgeting) comes from the shared layer; only Slack API calls and Slack's
+event/ID grammar live here.
+"""
+
+import asyncio
+import json
+import logging
+import re
+from typing import Any, Optional
+
+import httpx
+from fastapi import FastAPI, Request, Response
+from fastapi.responses import JSONResponse, PlainTextResponse
+from slack_sdk.web.async_client import AsyncWebClient
+
+from backend.copilot.bot.adapters.base import (
+ ChannelInfo,
+ ChannelType,
+ FileAttachment,
+ MessageCallback,
+ MessageContext,
+ PostedRef,
+ WebhookAdapter,
+)
+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 . import commands, config, signing
+from .text import to_mrkdwn
+
+logger = logging.getLogger(__name__)
+
+EVENTS_PATH = "/api/copilot-webhooks/slack/events"
+COMMANDS_PATH = "/api/copilot-webhooks/slack/commands"
+
+# Matches both `<@U123>` and `<@U123|displayname>` mention forms.
+_USER_MENTION_RE = re.compile(r"<@(U[A-Z0-9]+)(?:\|[^>]+)?>")
+
+# Slack channel/group/DM IDs — C/G/D + uppercase alphanumerics. Channel *names*
+# are lowercase-with-hyphens, so they never match; used by the proactive-post
+# resolver to tell an ID from a name.
+_CHANNEL_ID_RE = re.compile(r"^[CGD][A-Z0-9]{7,}$")
+
+
+class SlackAdapter(WebhookAdapter):
+ def __init__(self, api: BotBackend):
+ self._api = api
+ self._client = AsyncWebClient(token=config.get_bot_token())
+ self._on_message_callback: Optional[MessageCallback] = None
+ self._bot_user_id: Optional[str] = None
+ self._team_id: Optional[str] = None
+ self._user_name_cache: dict[str, str] = {}
+ # Strong-ref set so the GC doesn't drop fire-and-forget event tasks.
+ self._event_tasks: set[asyncio.Task[None]] = set()
+
+ @property
+ def platform_name(self) -> str:
+ return "slack"
+
+ @property
+ def max_message_length(self) -> int:
+ return config.MAX_MESSAGE_LENGTH
+
+ @property
+ def chunk_flush_at(self) -> int:
+ return config.CHUNK_FLUSH_AT
+
+ @property
+ def max_attachment_bytes(self) -> int:
+ return config.MAX_ATTACHMENT_BYTES
+
+ @property
+ def max_thread_name_length(self) -> int:
+ return config.MAX_THREAD_NAME_LENGTH
+
+ @property
+ def typing_refresh_interval(self) -> float:
+ return config.TYPING_REFRESH_SECONDS
+
+ def looks_like_channel_id(self, ref: str) -> bool:
+ return bool(_CHANNEL_ID_RE.match(ref))
+
+ def localize_markup(self, text: str) -> str:
+ return to_mrkdwn(text)
+
+ def on_message(self, callback: MessageCallback) -> None:
+ self._on_message_callback = callback
+
+ def register_routes(self, app: FastAPI) -> None:
+ app.add_api_route(EVENTS_PATH, self._handle_event_request, methods=["POST"])
+ app.add_api_route(COMMANDS_PATH, self._handle_command_request, methods=["POST"])
+
+ # -- Inbound --
+
+ async def _handle_event_request(self, request: Request) -> Response:
+ raw = await request.body()
+ if not _verify_signature(request, raw):
+ return PlainTextResponse("invalid signature", status_code=401)
+ payload = json.loads(raw)
+ if payload.get("type") == "url_verification":
+ return JSONResponse({"challenge": payload.get("challenge", "")})
+ if payload.get("type") == "event_callback":
+ event = payload.get("event") or {}
+ # The workspace (team) ID lives at the top level of the Events API
+ # payload — it isn't reliably inside the event object — so thread it
+ # through for server_id resolution.
+ team_id = payload.get("team_id")
+ # Fire-and-forget so we ACK within Slack's 3s window.
+ task = asyncio.create_task(self._dispatch_event(event, team_id))
+ self._event_tasks.add(task)
+ task.add_done_callback(self._event_tasks.discard)
+ return PlainTextResponse("ok")
+
+ async def _handle_command_request(self, request: Request) -> Response:
+ raw = await request.body()
+ if not _verify_signature(request, raw):
+ return PlainTextResponse("invalid signature", status_code=401)
+ form_data = await request.form()
+ # Slack slash-command form data is always string-valued; drop anything
+ # else (UploadFile etc.) defensively before passing on.
+ form: dict[str, str] = {
+ k: v for k, v in form_data.items() if isinstance(v, str)
+ }
+ return await commands.handle(self._api, form)
+
+ async def _dispatch_event(
+ self, event: dict[str, Any], team_id: Optional[str] = None
+ ) -> None:
+ if self._on_message_callback is None:
+ return
+ # Skip bot messages (including our own) to avoid reply loops.
+ if event.get("subtype") == "bot_message" or event.get("bot_id"):
+ return
+ event_type = event.get("type")
+ channel_type = event.get("channel_type")
+ ctx: Optional[MessageContext] = None
+ if event_type == "app_mention":
+ ctx = await self._build_context(event, team_id, bot_mentioned=True)
+ elif event_type == "message" and channel_type == "im":
+ ctx = await self._build_context(
+ event, team_id, bot_mentioned=True, is_dm=True
+ )
+ elif (
+ event_type == "message"
+ and channel_type == "channel"
+ and event.get("thread_ts")
+ ):
+ # Reply in a channel thread without an @mention — the handler checks
+ # thread-subscription state and ignores it if it isn't ours.
+ ctx = await self._build_context(event, team_id, bot_mentioned=False)
+ if ctx is None:
+ return
+ try:
+ await self._on_message_callback(ctx, self)
+ except Exception:
+ logger.exception("Slack event handler failed")
+
+ async def _build_context(
+ self,
+ event: dict[str, Any],
+ team_id: Optional[str] = None,
+ *,
+ bot_mentioned: bool,
+ is_dm: bool = False,
+ ) -> Optional[MessageContext]:
+ channel = event.get("channel")
+ ts = event.get("ts")
+ user = event.get("user")
+ text = event.get("text") or ""
+ if not channel or not ts or not user:
+ return None
+
+ thread_ts = event.get("thread_ts")
+ channel_type: ChannelType
+ target_channel_id: str
+ if is_dm:
+ channel_type = "dm"
+ target_channel_id = channel
+ elif thread_ts:
+ channel_type = "thread"
+ target_channel_id = _encode_target(channel, thread_ts)
+ else:
+ channel_type = "channel"
+ target_channel_id = channel
+
+ attachments, skipped = await self._extract_attachments(event)
+ return MessageContext(
+ platform="slack",
+ channel_type=channel_type,
+ # DMs bill to the user (no server); channel/thread need the workspace.
+ server_id=None if is_dm else (event.get("team") or team_id),
+ channel_id=target_channel_id,
+ message_id=ts,
+ user_id=user,
+ username=await self._user_display_name(user),
+ text=await self._strip_mentions(text),
+ bot_mentioned=bot_mentioned,
+ mentionable_users=await self._collect_mentionable_users(text),
+ attachments=attachments,
+ skipped_attachments=skipped,
+ )
+
+ async def _extract_attachments(self, event: dict[str, Any]) -> tuple[tuple, tuple]:
+ files = event.get("files") or []
+ inbound = [
+ InboundFile(
+ filename=f.get("name"),
+ size=int(f.get("size") or 0),
+ mime_type=f.get("mimetype"),
+ fetch=lambda f=f: self._download_slack_file(f),
+ )
+ for f in files
+ ]
+ return await collect_attachments(
+ inbound,
+ max_count=MAX_INBOUND_ATTACHMENTS,
+ max_bytes=self.max_attachment_bytes,
+ )
+
+ async def _download_slack_file(self, file_obj: dict[str, Any]) -> bytes:
+ # Slack file URLs are private — download needs the bot token as a
+ # bearer credential (files:read scope), unlike Discord's public CDN.
+ url = file_obj.get("url_private_download") or file_obj.get("url_private") or ""
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.get(
+ url, headers={"Authorization": f"Bearer {config.get_bot_token()}"}
+ )
+ resp.raise_for_status()
+ return resp.content
+
+ # -- Outbound --
+
+ def _render(self, text: str, mentionable_users: tuple[tuple[str, str], ...]) -> str:
+ # Allowlisted @-mentions → <@Uid> (the allowlist IS Slack's ping
+ # safety — non-allowlisted names stay plain and never ping), then
+ # localize CommonMark → mrkdwn.
+ rendered, _pinged = resolve_mentions(
+ text, mentionable_users, lambda _name, uid: f"<@{uid}>"
+ )
+ return self.localize_markup(rendered)
+
+ async def send_message(
+ self,
+ channel_id: str,
+ text: str,
+ mentionable_users: tuple[tuple[str, str], ...] = (),
+ ) -> None:
+ channel, thread_ts = _decode_target(channel_id)
+ await self._client.chat_postMessage(
+ channel=channel,
+ text=self._render(text, mentionable_users),
+ thread_ts=thread_ts,
+ )
+
+ async def send_reply(
+ self,
+ channel_id: str,
+ text: str,
+ reply_to_message_id: str,
+ mentionable_users: tuple[tuple[str, str], ...] = (),
+ ) -> None:
+ channel, thread_ts = _decode_target(channel_id)
+ await self._client.chat_postMessage(
+ channel=channel,
+ text=self._render(text, mentionable_users),
+ thread_ts=thread_ts or reply_to_message_id,
+ )
+
+ async def send_link(
+ self, channel_id: str, text: str, link_label: str, link_url: str
+ ) -> None:
+ channel, thread_ts = _decode_target(channel_id)
+ rendered = self.localize_markup(text)
+ await self._client.chat_postMessage(
+ channel=channel,
+ text=rendered,
+ thread_ts=thread_ts,
+ blocks=_link_blocks(rendered, link_label, link_url),
+ )
+
+ async def send_file(self, channel_id: str, text: str, file: FileAttachment) -> None:
+ channel, thread_ts = _decode_target(channel_id)
+ await self._client.files_upload_v2(
+ channel=channel,
+ thread_ts=thread_ts,
+ content=file.content,
+ filename=file.filename or "file",
+ initial_comment=self.localize_markup(text) if text else None,
+ )
+
+ async def send_ephemeral(self, channel_id: str, user_id: str, text: str) -> None:
+ channel, _ = _decode_target(channel_id)
+ await self._client.chat_postEphemeral(channel=channel, user=user_id, text=text)
+
+ async def start_typing(self, channel_id: str) -> None:
+ pass # Slack bot apps don't expose a typing indicator API.
+
+ async def stop_typing(self, channel_id: str) -> None:
+ pass
+
+ async def create_thread(
+ self, channel_id: str, message_id: str, name: str
+ ) -> Optional[str]:
+ # Slack threads are implicit — pack (channel, parent_ts) into a single
+ # target_id the handler passes back to the outbound send_* calls.
+ return _encode_target(channel_id, message_id)
+
+ async def rename_thread(self, thread_id: str, name: str) -> bool:
+ return False # Slack threads have no name.
+
+ # -- Proactive output --
+
+ async def list_text_channels(
+ self, server_ids: tuple[str, ...]
+ ) -> list[ChannelInfo]:
+ team_id = await self._team_id_cached()
+ if not team_id or team_id not in server_ids:
+ return []
+ channels: list[ChannelInfo] = []
+ cursor: Optional[str] = None
+ while True:
+ resp = await self._client.conversations_list(
+ types="public_channel",
+ exclude_archived=True,
+ limit=200,
+ cursor=cursor,
+ )
+ for c in resp.get("channels") or []:
+ # Only channels the bot is in can be posted to without a join.
+ if c.get("is_member"):
+ channels.append(
+ ChannelInfo(
+ id=c["id"], name=c.get("name", ""), server_id=team_id
+ )
+ )
+ cursor = (resp.get("response_metadata") or {}).get("next_cursor")
+ if not cursor:
+ break
+ return channels
+
+ async def get_channel_server_id(self, channel_id: str) -> Optional[str]:
+ team_id = await self._team_id_cached()
+ if not team_id:
+ return None
+ try:
+ await self._client.conversations_info(channel=channel_id)
+ except Exception:
+ return None
+ return team_id
+
+ async def post_channel_message(
+ self, channel_id: str, text: str
+ ) -> Optional[PostedRef]:
+ channel, thread_ts = _decode_target(channel_id)
+ first_ts = await self._post_chunked(channel, text, thread_ts=thread_ts)
+ if first_ts is None:
+ return None
+ return PostedRef(id=first_ts, url=await self._permalink(channel, first_ts))
+
+ async def create_channel_thread(
+ self, channel_id: str, name: str, text: str
+ ) -> Optional[PostedRef]:
+ # Slack threads are implicit + unnamed: post text as the root message;
+ # the returned ref threads subsequent sends off it.
+ channel, _ = _decode_target(channel_id)
+ root_ts = await self._post_chunked(channel, text)
+ if root_ts is None:
+ return None
+ return PostedRef(
+ id=_encode_target(channel, root_ts),
+ url=await self._permalink(channel, root_ts),
+ )
+
+ async def _post_chunked(
+ self, channel: str, text: str, thread_ts: Optional[str] = None
+ ) -> Optional[str]:
+ """Post ``text`` chunked under the message cap; return the first ts.
+
+ Later chunks thread off the first so a long post stays one conversation.
+ """
+ first_ts = thread_ts
+ for chunk in iter_chunks(self.localize_markup(text), config.CHUNK_FLUSH_AT):
+ resp = await self._client.chat_postMessage(
+ channel=channel, text=chunk, thread_ts=first_ts
+ )
+ if first_ts is None:
+ first_ts = resp.get("ts")
+ return first_ts
+
+ async def _permalink(self, channel: str, ts: str) -> Optional[str]:
+ try:
+ resp = await self._client.chat_getPermalink(channel=channel, message_ts=ts)
+ return resp.get("permalink")
+ except Exception:
+ return None
+
+ # -- Helpers --
+
+ async def _user_display_name(self, user_id: str) -> str:
+ if user_id in self._user_name_cache:
+ return self._user_name_cache[user_id]
+ try:
+ resp = await self._client.users_info(user=user_id)
+ user = resp.get("user") or {}
+ profile = user.get("profile") or {}
+ name = (
+ profile.get("display_name")
+ or user.get("real_name")
+ or user.get("name")
+ or user_id
+ )
+ except Exception:
+ logger.warning("Failed to fetch Slack user %s", user_id, exc_info=True)
+ name = user_id
+ self._user_name_cache[user_id] = name
+ return name
+
+ async def _strip_mentions(self, text: str) -> str:
+ """Drop the bot's own mention; rewrite others as `@displayname`."""
+ bot_id = await self._bot_user_id_cached()
+ names: dict[str, str] = {}
+ for match in _USER_MENTION_RE.finditer(text):
+ uid = match.group(1)
+ if uid not in names:
+ names[uid] = await self._user_display_name(uid)
+
+ def _replace(match: re.Match[str]) -> str:
+ uid = match.group(1)
+ if bot_id and uid == bot_id:
+ return ""
+ return f"@{names.get(uid, uid)}"
+
+ return _USER_MENTION_RE.sub(_replace, text).strip()
+
+ async def _collect_mentionable_users(
+ self, text: str
+ ) -> tuple[tuple[str, str], ...]:
+ bot_id = await self._bot_user_id_cached()
+ pairs: list[tuple[str, str]] = []
+ for match in _USER_MENTION_RE.finditer(text):
+ uid = match.group(1)
+ if bot_id and uid == bot_id:
+ continue
+ pair = (await self._user_display_name(uid), uid)
+ if pair not in pairs:
+ pairs.append(pair)
+ return tuple(pairs)
+
+ async def _ensure_identity(self) -> None:
+ """Resolve the bot's own user_id + team_id from auth_test, once.
+
+ Only a truthy result is cached — on a transient failure *or* a falsy
+ response the fields stay ``None`` so the next event retries. Otherwise a
+ single blip would permanently break self-mention stripping and channel/
+ team lookups.
+ """
+ if self._bot_user_id and self._team_id:
+ return
+ try:
+ resp = await self._client.auth_test()
+ except Exception:
+ logger.warning("Failed to fetch Slack identity (auth_test)", exc_info=True)
+ return
+ self._bot_user_id = self._bot_user_id or resp.get("user_id") or None
+ self._team_id = self._team_id or resp.get("team_id") or None
+
+ async def _bot_user_id_cached(self) -> str:
+ await self._ensure_identity()
+ return self._bot_user_id or ""
+
+ async def _team_id_cached(self) -> str:
+ await self._ensure_identity()
+ return self._team_id or ""
+
+
+def _verify_signature(request: Request, body: bytes) -> bool:
+ return signing.verify(
+ body=body,
+ timestamp=request.headers.get("X-Slack-Request-Timestamp", ""),
+ signature=request.headers.get("X-Slack-Signature", ""),
+ )
+
+
+def _encode_target(channel_id: str, thread_ts: str) -> str:
+ return f"{channel_id}|{thread_ts}"
+
+
+def _decode_target(target_id: str) -> tuple[str, Optional[str]]:
+ if "|" in target_id:
+ channel, thread_ts = target_id.split("|", 1)
+ return channel, thread_ts
+ return target_id, None
+
+
+def _link_blocks(text: str, link_label: str, link_url: str) -> list[dict[str, Any]]:
+ return [
+ {"type": "section", "text": {"type": "mrkdwn", "text": text}},
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": link_label[:75]},
+ "url": link_url,
+ }
+ ],
+ },
+ ]
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
new file mode 100644
index 0000000000..7ffc310e1d
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.py
@@ -0,0 +1,267 @@
+"""Tests for the Slack webhook adapter."""
+
+import json
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.bot.adapters.base import FileAttachment
+
+from .adapter import SlackAdapter, _decode_target, _encode_target
+
+_SIGN = "backend.copilot.bot.adapters.slack.adapter.signing.verify"
+
+
+def adapter() -> SlackAdapter:
+ with patch("backend.copilot.bot.adapters.slack.adapter.AsyncWebClient"):
+ a = SlackAdapter(MagicMock())
+ client = MagicMock()
+ client.chat_postMessage = AsyncMock(return_value={"ts": "111.222"})
+ client.chat_postEphemeral = AsyncMock()
+ client.chat_getPermalink = AsyncMock(return_value={"permalink": "https://x/p"})
+ client.files_upload_v2 = AsyncMock()
+ client.conversations_info = AsyncMock(return_value={"ok": True})
+ client.users_info = AsyncMock(
+ return_value={"user": {"profile": {"display_name": "Bently"}}}
+ )
+ client.auth_test = AsyncMock(return_value={"user_id": "UBOT", "team_id": "T1"})
+ a._client = client
+ return a
+
+
+def _req(raw: bytes, headers: dict | None = None) -> MagicMock:
+ r = MagicMock()
+ r.body = AsyncMock(return_value=raw)
+ r.headers = headers or {}
+ return r
+
+
+class TestInboundRouting:
+ @pytest.mark.asyncio
+ async def test_invalid_signature_is_rejected(self, adapter):
+ with patch(_SIGN, return_value=False):
+ resp = await adapter._handle_event_request(_req(b"{}"))
+ assert resp.status_code == 401
+
+ @pytest.mark.asyncio
+ async def test_url_verification_echoes_challenge(self, adapter):
+ body = json.dumps({"type": "url_verification", "challenge": "xyz"}).encode()
+ with patch(_SIGN, return_value=True):
+ resp = await adapter._handle_event_request(_req(body))
+ assert json.loads(bytes(resp.body).decode()) == {"challenge": "xyz"}
+
+ @pytest.mark.asyncio
+ async def test_app_mention_builds_channel_context(self, adapter):
+ captured = {}
+
+ async def cb(ctx, ad):
+ captured["ctx"] = ctx
+
+ adapter.on_message(cb)
+ await adapter._dispatch_event(
+ {
+ "type": "app_mention",
+ "channel": "C1",
+ "ts": "1.2",
+ "user": "U1",
+ "text": "<@UBOT> hi there",
+ "team": "T1",
+ }
+ )
+ ctx = captured["ctx"]
+ assert ctx.platform == "slack"
+ assert ctx.channel_type == "channel"
+ assert ctx.bot_mentioned is True
+ assert ctx.text == "hi there" # bot mention stripped
+
+ @pytest.mark.asyncio
+ async def test_thread_reply_is_not_bot_mentioned(self, adapter):
+ captured = {}
+
+ async def cb(ctx, ad):
+ captured["ctx"] = ctx
+
+ adapter.on_message(cb)
+ await adapter._dispatch_event(
+ {
+ "type": "message",
+ "channel_type": "channel",
+ "channel": "C1",
+ "ts": "2.0",
+ "thread_ts": "1.0",
+ "user": "U1",
+ "text": "follow up",
+ }
+ )
+ ctx = captured["ctx"]
+ assert ctx.channel_type == "thread"
+ assert ctx.bot_mentioned is False
+ assert ctx.channel_id == "C1|1.0"
+
+ @pytest.mark.asyncio
+ async def test_channel_uses_top_level_team_id_for_server(self, adapter):
+ # The event has no "team" — server_id must come from the payload's
+ # top-level team_id (threaded via _dispatch_event).
+ captured = {}
+
+ async def cb(ctx, ad):
+ captured["ctx"] = ctx
+
+ adapter.on_message(cb)
+ await adapter._dispatch_event(
+ {
+ "type": "app_mention",
+ "channel": "C1",
+ "ts": "1.2",
+ "user": "U1",
+ "text": "hi",
+ },
+ "T99",
+ )
+ assert captured["ctx"].server_id == "T99"
+
+ @pytest.mark.asyncio
+ async def test_dm_has_no_server_id(self, adapter):
+ captured = {}
+
+ async def cb(ctx, ad):
+ captured["ctx"] = ctx
+
+ adapter.on_message(cb)
+ await adapter._dispatch_event(
+ {
+ "type": "message",
+ "channel_type": "im",
+ "channel": "D1",
+ "ts": "1",
+ "user": "U1",
+ "text": "hi",
+ },
+ "T99",
+ )
+ assert captured["ctx"].channel_type == "dm"
+ assert captured["ctx"].server_id is None
+
+ @pytest.mark.asyncio
+ async def test_bot_messages_are_skipped(self, adapter):
+ called = []
+
+ async def cb(ctx, ad):
+ called.append(ctx)
+
+ adapter.on_message(cb)
+ await adapter._dispatch_event(
+ {"type": "app_mention", "bot_id": "B9", "channel": "C1", "ts": "1"}
+ )
+ assert called == []
+
+ @pytest.mark.asyncio
+ async def test_inbound_files_become_attachments(self, adapter):
+ adapter._download_slack_file = AsyncMock(return_value=b"filedata")
+ captured = {}
+
+ async def cb(ctx, ad):
+ captured["ctx"] = ctx
+
+ adapter.on_message(cb)
+ await adapter._dispatch_event(
+ {
+ "type": "message",
+ "channel_type": "im",
+ "channel": "D1",
+ "ts": "1",
+ "user": "U1",
+ "text": "look",
+ "files": [{"name": "a.txt", "size": 8, "mimetype": "text/plain"}],
+ }
+ )
+ ctx = captured["ctx"]
+ assert ctx.channel_type == "dm"
+ assert len(ctx.attachments) == 1
+ assert ctx.attachments[0].filename == "a.txt"
+ assert ctx.attachments[0].content == b"filedata"
+
+
+class TestOutbound:
+ @pytest.mark.asyncio
+ async def test_send_message_renders_mrkdwn_and_mentions_and_threads(self, adapter):
+ await adapter.send_message("C1|1.2", "**hi** @Bently", (("Bently", "U9"),))
+ call = adapter._client.chat_postMessage.await_args.kwargs
+ assert call["channel"] == "C1"
+ assert call["thread_ts"] == "1.2"
+ assert call["text"] == "*hi* <@U9>"
+
+ @pytest.mark.asyncio
+ async def test_non_allowlisted_mention_is_not_pinged(self, adapter):
+ await adapter.send_message("C1", "hi @Ghost", ())
+ assert adapter._client.chat_postMessage.await_args.kwargs["text"] == "hi @Ghost"
+
+ @pytest.mark.asyncio
+ async def test_send_file_uploads_into_thread(self, adapter):
+ await adapter.send_file(
+ "C1|1.2",
+ "here you go",
+ FileAttachment(filename="r.txt", mime_type="text/plain", content=b"x"),
+ )
+ call = adapter._client.files_upload_v2.await_args.kwargs
+ assert call["channel"] == "C1"
+ assert call["thread_ts"] == "1.2"
+ assert call["filename"] == "r.txt"
+ assert call["content"] == b"x"
+
+ @pytest.mark.asyncio
+ async def test_post_channel_message_returns_ref_with_permalink(self, adapter):
+ ref = await adapter.post_channel_message("C1", "hello")
+ assert ref is not None
+ assert ref.id == "111.222"
+ assert ref.url == "https://x/p"
+
+ @pytest.mark.asyncio
+ async def test_create_thread_encodes_target(self, adapter):
+ assert await adapter.create_thread("C1", "9.9", "name") == "C1|9.9"
+
+ @pytest.mark.asyncio
+ async def test_rename_thread_is_noop(self, adapter):
+ assert await adapter.rename_thread("C1|9.9", "x") is False
+
+
+class TestChannelIdGrammar:
+ def test_slack_ids_match(self, adapter):
+ assert adapter.looks_like_channel_id("C01234567")
+ assert adapter.looks_like_channel_id("D09ABCDEF")
+
+ def test_channel_names_do_not_match(self, adapter):
+ assert not adapter.looks_like_channel_id("general")
+ assert not adapter.looks_like_channel_id("announcements")
+
+
+class TestIdentityCaching:
+ @pytest.mark.asyncio
+ async def test_auth_failure_is_not_cached_and_retries(self, adapter):
+ adapter._client.auth_test = AsyncMock(
+ side_effect=[RuntimeError("blip"), {"user_id": "UBOT", "team_id": "T1"}]
+ )
+ # First call fails → not cached as "".
+ assert await adapter._bot_user_id_cached() == ""
+ assert adapter._bot_user_id is None
+ # Next call recovers.
+ assert await adapter._bot_user_id_cached() == "UBOT"
+ assert adapter._team_id == "T1"
+
+ @pytest.mark.asyncio
+ async def test_empty_auth_response_is_not_cached_and_retries(self, adapter):
+ adapter._client.auth_test = AsyncMock(
+ side_effect=[
+ {"user_id": "", "team_id": ""},
+ {"user_id": "UBOT", "team_id": "T1"},
+ ]
+ )
+ assert await adapter._bot_user_id_cached() == ""
+ assert adapter._bot_user_id is None # falsy response not cached
+ assert await adapter._bot_user_id_cached() == "UBOT"
+
+
+def test_target_encode_decode_roundtrip():
+ assert _decode_target(_encode_target("C1", "1.2")) == ("C1", "1.2")
+ assert _decode_target("D1") == ("D1", None)
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/app-manifest.yaml b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/app-manifest.yaml
new file mode 100644
index 0000000000..42ca11fda5
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/app-manifest.yaml
@@ -0,0 +1,65 @@
+# Slack app manifest for AutoPilot
+#
+# Import at https://api.slack.com/apps → Create New App → From an app manifest.
+# Once the backend is deployed, fill in <BASE_URL> below with the public origin
+# of the main backend API (e.g. https://dev-server.agpt.co) and re-import.
+
+display_information:
+ name: AutoPilot
+ description: AutoPilot — your AutoGPT agent in Slack
+ background_color: "#1a1a1a"
+ long_description: |
+ AutoPilot brings your AutoGPT account into Slack. Mention @AutoPilot in a
+ channel or DM the app to chat with your AutoGPT agent. Run /setup in a
+ channel to link the workspace to your AutoGPT account; DM the app to link
+ your own DMs as a personal account.
+
+features:
+ bot_user:
+ display_name: AutoPilot
+ always_online: true
+ app_home:
+ home_tab_enabled: false
+ messages_tab_enabled: true
+ messages_tab_read_only_enabled: false # let users DM the bot
+ slash_commands:
+ - command: /setup
+ url: <BASE_URL>/api/copilot-webhooks/slack/commands
+ description: Link this Slack workspace to an AutoGPT account
+ should_escape: false
+ - command: /help
+ url: <BASE_URL>/api/copilot-webhooks/slack/commands
+ description: How to use AutoPilot in Slack
+ should_escape: false
+ - command: /unlink
+ url: <BASE_URL>/api/copilot-webhooks/slack/commands
+ description: Disconnect your AutoGPT link from this workspace
+ should_escape: false
+
+oauth_config:
+ scopes:
+ bot:
+ - app_mentions:read # @AutoPilot in any channel the app is in
+ - channels:history # read messages in public channels (for thread follow-ups)
+ - channels:read # list public channels for proactive posting
+ - chat:write # post messages as the bot
+ - chat:write.public # post in channels the bot isn't a member of
+ - commands # slash commands
+ - files:read # download user-attached files into the workspace
+ - files:write # upload generated artifacts back to the user
+ - im:history # read DM history (for thread follow-up context)
+ - im:read # access DM channel metadata
+ - im:write # open DM channels with users
+ - users:read # resolve user names / IDs
+ - team:read # workspace metadata for SERVER linking
+
+settings:
+ event_subscriptions:
+ request_url: <BASE_URL>/api/copilot-webhooks/slack/events
+ bot_events:
+ - app_mention # @bot in any channel the app is in
+ - message.im # DMs to the bot
+ - message.channels # replies in channel threads the bot is part of
+ org_deploy_enabled: false
+ socket_mode_enabled: false
+ token_rotation_enabled: false
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands.py
new file mode 100644
index 0000000000..ca8aa177de
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands.py
@@ -0,0 +1,112 @@
+"""Slack slash-command handlers — /setup, /help, /unlink."""
+
+import logging
+from typing import Any
+
+from fastapi import Response
+from fastapi.responses import JSONResponse
+
+from backend.copilot.bot.bot_backend import BotBackend
+from backend.util.exceptions import LinkAlreadyExistsError
+from backend.util.settings import Settings
+
+logger = logging.getLogger(__name__)
+
+
+async def handle(api: BotBackend, form: dict[str, str]) -> Response:
+ command = form.get("command", "")
+ if command == "/setup":
+ return await _setup(api, form)
+ if command == "/help":
+ return _help()
+ if command == "/unlink":
+ return _unlink()
+ return _ephemeral(f"Unknown command: {command}")
+
+
+async def _setup(api: BotBackend, form: dict[str, str]) -> Response:
+ team_id = form.get("team_id", "")
+ user_id = form.get("user_id", "")
+ user_name = form.get("user_name", "")
+ team_domain = form.get("team_domain", "")
+ channel_id = form.get("channel_id", "")
+
+ if not team_id or not user_id:
+ return _ephemeral(
+ "Slack didn't send the workspace/user info. Try the command again."
+ )
+
+ try:
+ result = await api.create_link_token(
+ platform="slack",
+ platform_server_id=team_id,
+ platform_user_id=user_id,
+ platform_username=user_name,
+ server_name=team_domain,
+ channel_id=channel_id,
+ )
+ except LinkAlreadyExistsError:
+ return _ephemeral(
+ "This workspace is already linked to an AutoGPT account — just "
+ "mention me or DM me to chat. Run /unlink to manage the link."
+ )
+ except Exception:
+ logger.exception("Slack /setup link token creation failed")
+ return _ephemeral(
+ "Something went wrong creating the setup link. Try again in a moment."
+ )
+
+ return _link_response(
+ text=(
+ "*Set up AutoPilot for this workspace*\n\n"
+ "Click the button below to link this workspace to your AutoGPT "
+ "account. The link expires in 30 minutes."
+ ),
+ label="Link Workspace",
+ url=result.link_url,
+ )
+
+
+def _help() -> Response:
+ return _ephemeral(
+ "*AutoPilot for Slack*\n"
+ "• Run `/setup` in this workspace to link it to an AutoGPT account.\n"
+ "• Mention `@AutoPilot` in a channel to start a conversation in a thread.\n"
+ "• DM `@AutoPilot` to chat with your personal AutoPilot account.\n"
+ "• Run `/unlink` to manage your linked workspace and DM."
+ )
+
+
+def _unlink() -> Response:
+ cfg = Settings().config
+ base_url = (cfg.frontend_base_url or cfg.platform_base_url).rstrip("/")
+ if not base_url:
+ return _ephemeral(
+ "Settings page isn't configured — ask an admin to set FRONTEND_BASE_URL."
+ )
+ return _link_response(
+ text="Manage your workspace and DM links from your AutoGPT settings.",
+ label="Open Settings",
+ url=f"{base_url}/profile/settings",
+ )
+
+
+def _ephemeral(text: str) -> Response:
+ return JSONResponse({"response_type": "ephemeral", "text": text})
+
+
+def _link_response(text: str, label: str, url: str) -> Response:
+ blocks: list[dict[str, Any]] = [
+ {"type": "section", "text": {"type": "mrkdwn", "text": text}},
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": label},
+ "url": url,
+ }
+ ],
+ },
+ ]
+ return JSONResponse({"response_type": "ephemeral", "text": text, "blocks": blocks})
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands_test.py
new file mode 100644
index 0000000000..0b1b361cc6
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands_test.py
@@ -0,0 +1,99 @@
+"""Tests for Slack slash-command handlers."""
+
+import json
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from . import commands
+
+
+def _body(resp) -> dict:
+ return json.loads(bytes(resp.body).decode())
+
+
+async def test_setup_returns_link_button():
+ api = MagicMock()
+ api.create_link_token = AsyncMock(
+ return_value=MagicMock(link_url="https://example.com/link/abc")
+ )
+ resp = await commands.handle(
+ api, {"command": "/setup", "team_id": "T1", "user_id": "U1"}
+ )
+ body = _body(resp)
+ assert body["response_type"] == "ephemeral"
+ assert body["blocks"][1]["elements"][0]["url"] == "https://example.com/link/abc"
+ api.create_link_token.assert_awaited_once()
+ assert api.create_link_token.await_args.kwargs["platform"] == "slack"
+
+
+async def test_setup_without_team_is_rejected():
+ api = MagicMock()
+ api.create_link_token = AsyncMock()
+ resp = await commands.handle(api, {"command": "/setup", "user_id": "U1"})
+ assert "workspace/user info" in _body(resp)["text"]
+ api.create_link_token.assert_not_awaited()
+
+
+async def test_setup_already_linked_gets_friendly_message():
+ from backend.util.exceptions import LinkAlreadyExistsError
+
+ api = MagicMock()
+ api.create_link_token = AsyncMock(side_effect=LinkAlreadyExistsError("linked"))
+ resp = await commands.handle(
+ api, {"command": "/setup", "team_id": "T1", "user_id": "U1"}
+ )
+ assert "already linked" in _body(resp)["text"]
+
+
+async def test_setup_link_failure_is_graceful():
+ api = MagicMock()
+ api.create_link_token = AsyncMock(side_effect=RuntimeError("boom"))
+ resp = await commands.handle(
+ api, {"command": "/setup", "team_id": "T1", "user_id": "U1"}
+ )
+ assert "went wrong" in _body(resp)["text"]
+
+
+async def test_help_is_ephemeral():
+ resp = await commands.handle(MagicMock(), {"command": "/help"})
+ assert _body(resp)["response_type"] == "ephemeral"
+ assert "/setup" in _body(resp)["text"]
+
+
+async def test_unlink_points_at_settings():
+ settings = MagicMock()
+ settings.config.frontend_base_url = "https://app.example"
+ settings.config.platform_base_url = ""
+ with patch(
+ "backend.copilot.bot.adapters.slack.commands.Settings", return_value=settings
+ ):
+ resp = await commands.handle(MagicMock(), {"command": "/unlink"})
+ assert (
+ _body(resp)["blocks"][1]["elements"][0]["url"]
+ == "https://app.example/profile/settings"
+ )
+
+
+async def test_unlink_without_base_url_returns_error():
+ settings = MagicMock()
+ settings.config.frontend_base_url = ""
+ settings.config.platform_base_url = ""
+ with patch(
+ "backend.copilot.bot.adapters.slack.commands.Settings", return_value=settings
+ ):
+ resp = await commands.handle(MagicMock(), {"command": "/unlink"})
+ assert "FRONTEND_BASE_URL" in _body(resp)["text"]
+
+
+async def test_unknown_command():
+ resp = await commands.handle(MagicMock(), {"command": "/wat"})
+ assert "Unknown command" in _body(resp)["text"]
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/config.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/config.py
new file mode 100644
index 0000000000..b625a86b33
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/config.py
@@ -0,0 +1,34 @@
+"""Slack-specific configuration."""
+
+from backend.util.settings import Settings
+
+
+def get_bot_token() -> str:
+ return Settings().secrets.autopilot_bot_slack_token
+
+
+def get_signing_secret() -> str:
+ return Settings().secrets.autopilot_bot_slack_signing_secret
+
+
+# Slack's hard cap is 40000 chars per message; 4000 is the practical ceiling
+# for readability.
+MAX_MESSAGE_LENGTH = 4000
+
+# Flush at 3800 — leaves 200-char headroom under the cap for the boundary
+# splitter to reach a natural break point.
+CHUNK_FLUSH_AT = 3800
+
+# Cap on a single inbound/outbound file. Slack allows far larger, but the bot
+# only shuttles chat artifacts; over-cap outbound artifacts fall back to a
+# link-to-chat button, and over-cap inbound files are skipped with a note.
+MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024
+
+# Slack threads have no name (they're implicit off a parent message), so this
+# is unused — create_thread encodes channel|ts and rename_thread is a no-op.
+# Present only to satisfy the adapter contract.
+MAX_THREAD_NAME_LENGTH = 100
+
+# Slack bot apps expose no typing indicator, so start_typing is a no-op and
+# this cadence is unused; present only to satisfy the adapter contract.
+TYPING_REFRESH_SECONDS = 5.0
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/signing.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/signing.py
new file mode 100644
index 0000000000..4aafe3384c
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/signing.py
@@ -0,0 +1,22 @@
+"""Slack request signature verification (HMAC-SHA256)."""
+
+from slack_sdk.signature import SignatureVerifier
+
+from . import config
+
+
+def verify(body: bytes, timestamp: str, signature: str) -> bool:
+ """Validate a Slack request against the configured signing secret.
+
+ Fails closed on any malformed input (missing/empty headers, a non-numeric
+ timestamp) rather than raising — a garbage request becomes a clean 401, not
+ a 500/400 leaking an ``int('')`` error.
+ """
+ if not timestamp or not signature:
+ return False
+ try:
+ return SignatureVerifier(config.get_signing_secret()).is_valid(
+ body=body, timestamp=timestamp, signature=signature
+ )
+ except Exception:
+ return False
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/signing_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/signing_test.py
new file mode 100644
index 0000000000..f5bbfbf308
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/signing_test.py
@@ -0,0 +1,40 @@
+"""Tests for Slack request signature verification."""
+
+import hashlib
+import hmac
+import time
+from unittest.mock import patch
+
+from . import signing
+
+_SECRET = "test-signing-secret"
+
+
+def _sign(body: bytes, timestamp: str) -> str:
+ basestring = f"v0:{timestamp}:{body.decode()}".encode()
+ digest = hmac.new(_SECRET.encode(), basestring, hashlib.sha256).hexdigest()
+ return f"v0={digest}"
+
+
+class TestVerify:
+ def test_missing_timestamp_fails_closed(self):
+ # A malformed request (no headers) must return False, not raise.
+ assert signing.verify(b"{}", "", "v0=abc") is False
+
+ def test_missing_signature_fails_closed(self):
+ assert signing.verify(b"{}", str(int(time.time())), "") is False
+
+ def test_non_numeric_timestamp_fails_closed(self):
+ assert signing.verify(b"{}", "not-a-number", "v0=abc") is False
+
+ def test_valid_signature_passes(self):
+ body = b'{"type":"event_callback"}'
+ ts = str(int(time.time()))
+ with patch.object(signing.config, "get_signing_secret", return_value=_SECRET):
+ assert signing.verify(body, ts, _sign(body, ts)) is True
+
+ def test_wrong_signature_fails(self):
+ body = b'{"type":"event_callback"}'
+ ts = str(int(time.time()))
+ with patch.object(signing.config, "get_signing_secret", return_value=_SECRET):
+ assert signing.verify(body, ts, "v0=deadbeef") is False
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/text.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/text.py
new file mode 100644
index 0000000000..e19ac5f7c1
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/text.py
@@ -0,0 +1,19 @@
+"""Convert the bot's canonical CommonMark output into Slack mrkdwn.
+
+Only the markup dialect differs here — ``**bold**`` → ``*bold*`` and
+``[label](url)`` → ``<url|label>``. User @-mention resolution is the shared,
+allowlist-guarded ``text.resolve_mentions`` policy, applied separately in the
+adapter's send methods.
+"""
+
+import re
+
+_BOLD_RE = re.compile(r"\*\*(.+?)\*\*")
+_LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")
+
+
+def to_mrkdwn(text: str) -> str:
+ """Render CommonMark bold + links in Slack's mrkdwn dialect."""
+ text = _BOLD_RE.sub(r"*\1*", text)
+ text = _LINK_RE.sub(r"<\2|\1>", text)
+ return text
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/text_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/text_test.py
new file mode 100644
index 0000000000..f70e1c6ad4
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/text_test.py
@@ -0,0 +1,19 @@
+"""Tests for Slack mrkdwn conversion."""
+
+from .text import to_mrkdwn
+
+
+def test_bold_is_converted():
+ assert to_mrkdwn("a **bold** word") == "a *bold* word"
+
+
+def test_link_is_converted():
+ assert to_mrkdwn("see [docs](https://x.dev)") == "see <https://x.dev|docs>"
+
+
+def test_bold_and_link_together():
+ assert to_mrkdwn("**hi** [x](y)") == "*hi* <y|x>"
+
+
+def test_plain_text_unchanged():
+ assert to_mrkdwn("nothing to convert") == "nothing to convert"
diff --git a/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py
index d2807afcc2..fbfb3b03e2 100644
--- a/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py
+++ b/autogpt_platform/backend/backend/copilot/bot/webhook_routes.py
@@ -12,6 +12,8 @@ import logging
from fastapi import FastAPI
from .adapters.base import WebhookAdapter
+from .adapters.slack import config as slack_config
+from .adapters.slack.adapter import SlackAdapter
from .bot_backend import BotBackend
from .handler import MessageHandler
@@ -40,4 +42,7 @@ def _build_webhook_adapters(api: BotBackend) -> list[WebhookAdapter]:
mounts nothing.
"""
adapters: list[WebhookAdapter] = []
+ if slack_config.get_bot_token() and slack_config.get_signing_secret():
+ adapters.append(SlackAdapter(api))
+ logger.info("Slack adapter enabled")
return adapters
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 81ed7af805..9c35bf587f 100644
--- a/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/webhook_routes_test.py
@@ -7,9 +7,26 @@ from fastapi import FastAPI
from .adapters.base import WebhookAdapter
from .webhook_routes import _build_webhook_adapters, register_webhook_adapters
+_SLACK_CFG = "backend.copilot.bot.webhook_routes.slack_config"
-def test_build_webhook_adapters_starts_empty():
- assert _build_webhook_adapters(MagicMock()) == []
+
+def test_build_webhook_adapters_empty_without_slack_creds():
+ with (
+ patch(f"{_SLACK_CFG}.get_bot_token", return_value=""),
+ patch(f"{_SLACK_CFG}.get_signing_secret", return_value=""),
+ ):
+ assert _build_webhook_adapters(MagicMock()) == []
+
+
+def test_build_webhook_adapters_includes_slack_when_configured():
+ with (
+ patch(f"{_SLACK_CFG}.get_bot_token", return_value="xoxb-x"),
+ patch(f"{_SLACK_CFG}.get_signing_secret", return_value="secret"),
+ patch("backend.copilot.bot.adapters.slack.adapter.AsyncWebClient"),
+ ):
+ adapters = _build_webhook_adapters(MagicMock())
+ assert len(adapters) == 1
+ assert adapters[0].platform_name == "slack"
def test_register_webhook_adapters_wires_each_adapter():
diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.py
index 65cac15b1f..9586c63c89 100644
--- a/autogpt_platform/backend/backend/util/settings.py
+++ b/autogpt_platform/backend/backend/util/settings.py
@@ -767,6 +767,18 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):
description="Discord permissions bitfield for the 'Add to server' "
"invite URL. Overrides the built-in default when non-empty.",
)
+ autopilot_bot_slack_token: str = Field(
+ default="",
+ description="Slack bot (xoxb-) token for the CoPilot chat bridge. When "
+ "set together with the signing secret, the bridge mounts its Slack "
+ "webhook adapter (Events API) on the main backend API.",
+ )
+ autopilot_bot_slack_signing_secret: str = Field(
+ default="",
+ description="Slack app signing secret — verifies inbound Slack request "
+ "signatures (HMAC-SHA256). Required alongside the token to enable the "
+ "Slack adapter.",
+ )
smtp_server: str = Field(default="", description="SMTP server IP")
smtp_port: str = Field(default="", description="SMTP server port")
diff --git a/autogpt_platform/backend/poetry.lock b/autogpt_platform/backend/poetry.lock
index 3cd279a940..af3f13f81d 100644
--- a/autogpt_platform/backend/poetry.lock
+++ b/autogpt_platform/backend/poetry.lock
@@ -6911,6 +6911,21 @@ files = [
{file = "six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81"},
]
+[[package]]
+name = "slack-sdk"
+version = "3.43.0"
+description = "The Slack API Platform SDK for Python"
+optional = false
+python-versions = ">=3.7"
+groups = ["main"]
+files = [
+ {file = "slack_sdk-3.43.0-py2.py3-none-any.whl", hash = "sha256:4b6557c65577fc172f685af218b811f9f3b4909e24cddd839ada09565f10c585"},
+ {file = "slack_sdk-3.43.0.tar.gz", hash = "sha256:0553152e46c4259eb69f7464cdadc35ba4802ca10f9f5a849c92cf03d6c2ba07"},
+]
+
+[package.extras]
+optional = ["SQLAlchemy (>=2.0.49,<3)", "aiodns (>1.0)", "aiohttp (>=3.13.5,<4) ; python_version >= \"3.9\"", "aiohttp (>=3.7.3,<3.11) ; python_version == \"3.8\"", "aiohttp (>=3.7.3,<3.9) ; python_version == \"3.7\"", "boto3 (<=2)", "websocket-client (>=1,<2)", "websockets (>=9.1,<16)"]
+
[[package]]
name = "sniffio"
version = "1.3.1"
@@ -8648,4 +8663,4 @@ cffi = ["cffi (>=1.17,<2.0) ; platform_python_implementation != \"PyPy\" and pyt
[metadata]
lock-version = "2.1"
python-versions = ">=3.10,<3.14"
-content-hash = "5e12386c4a72e8674b912a8cb531b972c2bd501e4dd026251549a3894aea3edb"
+content-hash = "16987f8436cb1534eda5c73bb992e07d20b436afabcf3e8da830ef1d4117b423"
diff --git a/autogpt_platform/backend/pyproject.toml b/autogpt_platform/backend/pyproject.toml
index 3efb791653..2a5a0b40f7 100644
--- a/autogpt_platform/backend/pyproject.toml
+++ b/autogpt_platform/backend/pyproject.toml
@@ -69,6 +69,7 @@ redis = "^6.2.0"
regex = "^2025.9.18"
replicate = "^1.0.6"
sentry-sdk = {extras = ["anthropic", "fastapi", "launchdarkly", "openai", "sqlalchemy"], version = "^2.44.0"}
+slack-sdk = "^3.41.0"
sqlalchemy = "^2.0.40"
strenum = "^0.4.9"
stripe = "^11.5.0"