> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Slack 将 Agent 添加到 Slack,让用户可以在共享 Channel 线程或私信中向其发送消息。收到消息后,Mastra 会通过常规 Agent 流水线运行 Agent,并将响应流式传回 Slack。Slack 适配器会代你处理 Slack AI 指示器和交互式卡片。 ## 安装 从 Chat SDK 安装 Slack 适配器: **npm**: ```bash npm install @chat-adapter/slack ``` **pnpm**: ```bash pnpm add @chat-adapter/slack ``` **Yarn**: ```bash yarn add @chat-adapter/slack ``` **Bun**: ```bash bun add @chat-adapter/slack ``` 将 `createSlackAdapter()` 添加到 Agent 的 `channels.adapters` 对象: ```typescript import { Agent } from '@mastra/core/agent' import { createSlackAdapter } from '@chat-adapter/slack' export const yourAgent = new Agent({ id: 'your-agent', name: 'Your Agent', instructions: 'Help people plan tasks, answer questions, and coordinate work in Slack.', model: 'anthropic/claude-opus-4-7', channels: { adapters: { slack: createSlackAdapter(), }, }, }) ``` ## 创建 Slack 应用 要连接 Agent,请在希望运行 Agent 的 Workspace 中创建 Slack 应用。Slack 应用控制 Agent 在 Slack 中的显示方式、功能以及接收的事件。 本指南使用 [manifest](https://docs.slack.dev/app-manifests/configuring-apps-with-app-manifests/#creating_manifests),即一个代你创建 Slack 应用设置的配置文件。当你要将 Agent 添加到自己的 Workspace 时,这是最快的方法。本指南不涵盖由其他 Workspace 安装 Agent 的平台 OAuth 流程。 通过 manifest 创建 Slack 应用: 1. 打开 [api.slack.com/apps](https://api.slack.com/apps)。 2. 选择 **Create an app**。 3. 选择 **From a manifest**。 4. 选择 Agent 应运行的 Workspace。 5. 粘贴以下 manifest,然后选择 **Create**。Slack 接受 JSON 或 YAML,因此请选择与应用创建模态框中所示格式对应的选项卡: **JSON**: ```json { "display_information": { "name": "mastra-agent" }, "features": { "app_home": { "home_tab_enabled": false, "messages_tab_enabled": true, "messages_tab_read_only_enabled": false }, "bot_user": { "display_name": "mastra-agent", "always_online": true } }, "oauth_config": { "scopes": { "bot": [ "im:write", "app_mentions:read", "channels:history", "channels:read", "chat:write", "users:read", "im:read", "im:history" ] }, "pkce_enabled": false }, "settings": { "event_subscriptions": { "request_url": "https:///api/agents//channels/slack/webhook", "bot_events": ["app_mention", "message.channels", "message.im"] }, "interactivity": { "is_enabled": true, "request_url": "https:///api/agents//channels/slack/webhook" }, "org_deploy_enabled": false, "socket_mode_enabled": false, "token_rotation_enabled": false, "is_mcp_enabled": false } } ``` **YAML**: ```yaml display_information: name: mastra-agent features: app_home: home_tab_enabled: false messages_tab_enabled: true messages_tab_read_only_enabled: false bot_user: display_name: mastra-agent always_online: true oauth_config: scopes: bot: - im:write - app_mentions:read - channels:history - channels:read - chat:write - users:read - im:read - im:history pkce_enabled: false settings: event_subscriptions: request_url: https:///api/agents//channels/slack/webhook bot_events: - app_mention - message.channels - message.im interactivity: is_enabled: true request_url: https:///api/agents//channels/slack/webhook org_deploy_enabled: false socket_mode_enabled: false token_rotation_enabled: false is_mcp_enabled: false ``` 此 manifest 配置以下内容: - `display_information.name` 和 `features.bot_user.display_name`:设置 Agent 在 Slack 中的名称。你可以随时更新。更改名称或权限后,请记得重新安装应用。 - `app_home.messages_tab_enabled` 和 `app_home.messages_tab_read_only_enabled`:启用来自 Slack 应用 **Messages** 选项卡的私信。 - `always_online`:将 Slack 机器人用户显示为始终在线。 - `oauth_config.scopes.bot`:授予在机器人所在 Channel 中发送和读取消息的权限。同时涵盖提及和私信,以及用户查询。 - `event_subscriptions`:告知 Slack 要将哪些消息事件发送到 webhook。 - `interactivity`:启用交互式卡片,并告知 Slack 将卡片操作发送到何处。 创建应用后,打开 **Install App**,选择 **Install to Workspace**,并批准所请求的 scope。 ## 设置 Slack 凭据 在 Mastra 中设置 Slack 凭据,使其能够验证 Slack 请求并向 Slack 发回消息。 在 Slack 应用设置中复制以下值: - **Basic Information** > **App Credentials** > **Signing Secret** - **OAuth & Permissions** > **Bot User OAuth Token** 在 Mastra 环境中设置这些值: ```bash SLACK_SIGNING_SECRET=your-signing-secret SLACK_BOT_TOKEN=xoxb-your-bot-token ``` Mastra 会自动读取这些环境变量。 ## 配置 webhook 路由 Slack 通过 webhook 将 Channel 活动发送到 Mastra。Webhook 是 Slack 在发生事件时调用的 HTTP 端点,例如出现新消息、有人提及 Agent,或用户选择交互式卡片。 Mastra 会自动为 Agent 注册 Slack webhook 路由: ```text /api/agents//channels/slack/webhook ``` 使用公开的 Mastra Server URL 和生成的路由构建 webhook URL: ```text https:///api/agents//channels/slack/webhook ``` Slack 无法向 `localhost` 发送事件。本地开发时,请保持 Mastra 开发 Server 运行,并在 Slack 中保存请求 URL 前,通过隧道公开 `http://localhost:4111`。 本地开发可使用 `cloudflared` 或 `ngrok` 等隧道: **npm**: ```bash npx cloudflared tunnel --url http://localhost:4111 ``` **pnpm**: ```bash pnpm dlx cloudflared tunnel --url http://localhost:4111 ``` **Yarn**: ```bash yarn dlx cloudflared tunnel --url http://localhost:4111 ``` **Bun**: ```bash bun x cloudflared tunnel --url http://localhost:4111 ``` 使用生成的隧道主机作为 ``,例如: ```text https://abc123.trycloudflare.com/api/agents/your-agent/channels/slack/webhook ``` 在 Slack 中更新请求 URL: 1. 在 Slack 应用设置中打开 **Event Subscriptions**。 2. 将 **Request URL** 替换为最终 webhook URL。 3. 选择 **Save Changes**。 4. 打开 **Interactivity & Shortcuts**。 5. 将 **Request URL** 替换为相同的 webhook URL。 6. 选择 **Save Changes**。 7. 如果 Slack 要求重新安装应用,请打开 **OAuth & Permissions** 并选择 **Reinstall to Workspace**。 ## 在 Slack 中试用 打开与 Slack 机器人用户的私信并发送消息。由于 manifest 包含 `message.im` 事件和 `im:*` scope,因此私信可以正常工作。 要在 Channel 中使用 Agent,请先邀请 Slack 机器人用户: ```text /invite @your-bot-name ``` 在 Channel 中提及机器人: ```text @your-bot-name What can you help me with? ``` Agent 会在线程中响应。响应内容取决于 Agent 上配置的模型、instructions、Memory 和 Tool。 ## 身份验证 Slack 适配器没有内置的用户 allowlist。安装应用后,Workspace 中的任何人都可以通过向 Agent 发送私信,或在 Agent 所在 Channel 中提及它来与之交流。Slack 使用签名 secret 验证每个请求,Mastra 则会针对 webhook 收到的每条有效消息运行 Agent。 控制访问的主要机制是 Channel 成员资格。机器人只会接收私信事件,以及来自它已受邀加入的 Channel 的事件,因此机器人所属的 Channel 集合决定了哪些人可以访问它。不要将机器人加入不应响应的 Channel;要切断访问,可将其从 Channel 中移除。 若需更细粒度的控制,请根据发送者身份设置门禁。每个请求都在 Channel [request context](#request-context) 中携带发送者的 Slack 用户 ID,因此可在 Agent 操作前,通过输入处理器或 Tool 允许或拒绝特定用户。 ### Server 身份验证 Slack webhook 路由不受 Mastra [Server 身份验证](https://mastra.zisheng.pro/docs/server/auth)约束。Slack 无法发送 bearer token,因此 Mastra 会将 Channel webhook 注册为公开路由,并改用 Slack 签名 secret 验证每个请求。即使启用 [`MastraAuthSimple`](https://mastra.zisheng.pro/docs/server/auth/simple-auth) 等 Provider,也是如此:API 的其余部分仍受保护,但 webhook 路由依赖签名 secret,而不是 Server 身份验证。请确保设置 `SLACK_SIGNING_SECRET`,以便适配器拒绝并非由 Slack 签名的请求。 ### 外部 Channel 共享 Channel([Slack Connect](https://slack.com/connect))允许其他 Workspace 的用户加入对话。如果 Workspace 成员将机器人添加到共享 Channel,该 Channel 中的所有人都可以与 Agent 交流,包括组织之外的外部成员。任何能够访问 Agent 的人,也能访问 Agent 有权使用的 Tool 和数据。 请将机器人加入共享或外部 Channel 视为向这些参与者授予 Agent 访问权限。在执行此操作前,请确认 Agent 的 Tool 和数据可以安全地向外部成员开放;需要限制 Agent 响应对象时,请根据发送者的用户 ID 设置门禁。 ## 请求上下文 对于每条消息,Mastra 都会将 Channel context 对象放在 [request context](https://mastra.zisheng.pro/docs/server/request-context) 的 `channel` 键下。它包含发送者的 Slack 显示名称和用户 ID、机器人的身份,以及消息来源的详细信息。可从输入处理器或 Tool 中读取该对象,以识别用户或根据对话类型进行分支: ```typescript import { createTool } from '@mastra/core/tools' import type { ChannelContext } from '@mastra/core/channels' import { z } from 'zod' export const whoami = createTool({ id: 'whoami', description: 'Return the Slack identity of the current user', inputSchema: z.object({}), execute: async (_input, context) => { const channel = context?.requestContext?.get('channel') as ChannelContext | undefined return { platform: channel?.platform, userId: channel?.userId, userName: channel?.userName, isDM: channel?.isDM, } }, }) ``` Channel context 包含: - `botMention`、`botUserId` 和 `botUserName`:机器人在 Slack 中的身份。 - `channelId` 和 `threadId`:消息到达的 Slack Channel 和线程。 - `isDM`:该消息是否为私信。 - `platform`:平台标识符,此适配器为 `slack`。 - `userId` 和 `userName`:发送者的 Slack 用户 ID 和显示名称。 Mastra 还会将此 context 转换为一条简短的系统消息。Agent 会获知平台及其自身身份,以及对话是私信还是公开 Channel。如需了解如何更改此行为,请参阅 Channels 概览中的[线程上下文](https://mastra.zisheng.pro/docs/capabilities/channels/overview)。 ## 生产环境部署 部署 Mastra Server 时,请将 Slack 应用设置中的两个请求 URL 都更新为生产环境 webhook URL。本地开发使用的隧道 URL 是临时的,会在隧道重启时发生变化。 Serverless 平台上的 Channels 可能需要配置 `waitUntil` 和共享 pub/sub,才能让后台响应和线程租约跨短暂存活的实例正常工作。请参阅 Channels 概览中的 [serverless 部署](https://mastra.zisheng.pro/docs/capabilities/channels/overview)。 ### 空闲 Server 平台 Server 在未接收流量时会缩容至空闲状态,这对 Slack 没有影响。下一个事件(例如提及或私信)会通过投递 webhook 请求唤醒 Server,随后 Server 会恢复处理请求。Server 空闲后首次响应可能因启动而稍慢,这是正常现象。Slack 要求在 3 秒内收到 `200` 确认;当投递失败或超时时,它最多会重试事件三次。因此,如果冷启动非常慢,可能需要一次重试 Agent 才能响应。在 Server 保持热状态期间,后续消息会以正常速度响应。 ## 相关内容 - [Channels 概览](https://mastra.zisheng.pro/docs/capabilities/channels/overview) - [更多适配器](https://mastra.zisheng.pro/docs/capabilities/channels/other-adapters) - [Channels Reference](https://mastra.zisheng.pro/reference/agents/channels) - [部署概览](https://mastra.zisheng.pro/docs/deployment/overview)