mcpField
A
agent-slack

agent-slack

github.com/agent-messenger生产力247128 次安装2 天前更新
代码仓库

关于 agent-slack

面向 AI Agent 和 Slack 用户的 TypeScript 命令行工具,用于通过命令与 Slack 工作区交互。它提供二维码登录或从桌面应用、Chromium 浏览器提取凭据,并支持多工作区及 JSON 输出。

主要功能

  1. 01二维码登录或自动提取 Slack 凭据
  2. 02管理多个已认证工作区
  3. 03查看频道、用户、消息和工作区概况
  4. 04发送消息、回复及上传文件
  5. 05管理反应、提醒、书签和保存项目
  6. 06默认提供便于 Agent 使用的 JSON 输出

适用场景

  1. 01获取工作区概况并查找频道
  2. 02发送频道消息或线程回复
  3. 03查看未读活动并管理提醒
  4. 04将文件上传到频道或线程

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/agent-messenger/agent-messenger --skill agent-slack

安装后在 Claude Code 中输入/agent-slack确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
authentication.md
common-patterns.md
templates/
monitor-channel.sh
post-message.sh
workspace-summary.sh

详细介绍

Agent Slack

一个 TypeScript 命令行工具,可让 AI Agent 和用户通过简单的命令行界面与 Slack 工作区交互。支持从 Slack 桌面应用无缝提取令牌(浏览器可作为备用方案),并支持多个工作区。

快速入门

# Get workspace snapshot (credentials are extracted automatically)
agent-slack snapshot

# Send a message
agent-slack message send general "Hello from AI agent!"

# List channels
agent-slack channel list

身份验证

首次使用时,会自动从 Slack 桌面应用中提取凭据(如果不可用,则从 Chromium 浏览器中提取)。无需手动设置——只需运行任意命令,身份验证就会在后台静默完成。

在 macOS 上,首次操作时系统可能会提示输入钥匙串密码(解密 Slack 存储的令牌时需要)。这只会提示一次。

获取令牌的两种方式:

  • agent-slack auth qr——推荐。 使用 Slack“在移动设备上登录”界面中的二维码登录。这是最安全、最可靠的方法:通过纯 HTTP 使用 Slack 自己的登录流程进行身份验证,而不是从磁盘读取凭据;并且不需要桌面应用或浏览器。
  • agent-slack auth extract。 优先从 Slack 桌面应用提取令牌;如果未安装该应用,则改从 Chromium 浏览器提取。最适合自动化/无头环境。
二维码登录(推荐)

使用已登录 Slack 的任意设备上的二维码登录——无需桌面应用或浏览器自动化,全程通过 HTTP 完成:

# In Slack (desktop or web): your name (top-left) → "Sign in on mobile".
# Right-click the QR code → "Copy Image Address", then:
pbpaste | agent-slack auth qr

# Or pass the data URL directly:
agent-slack auth qr "data:image/png;base64,iVBORw0KGgo..."

此命令会解码二维码中的一次性登录链接、建立会话,并像 auth extract 一样存储生成的凭据。二维码链接只能使用一次——如果过期,请生成新的链接。

多工作区支持
# List all authenticated workspaces
agent-slack workspace list

# Switch to a different workspace
agent-slack workspace switch <workspace-id>

# Show current workspace
agent-slack workspace current

# Remove a workspace
agent-slack workspace remove <workspace-id>

# Check auth status
agent-slack auth status

# Run one command against another workspace without switching
agent-slack --workspace <workspace-id> channel list
agent-slack --workspace <workspace-id> auth status

全局 --workspace <id> 标志需放在命令前,并适用于所有使用已存储工作区的命令,包括 auth status 和 auth logout。它只会在本次调用中指定目标工作区,不会更改当前工作区。如果未存储该 ID,auth status 会报错:Workspace not found: <id>。auth extract 和 auth qr 会发现工作区,而不是指定目标,因此该标志对它们不起作用;只有在尚未设置当前工作区时,它们才会将其设为当前工作区。

记忆

Agent 会维护 ~/.config/agent-messenger/MEMORY.md 文件,作为跨会话的持久记忆。此文件由 Agent 管理——CLI 不会读取或写入该文件。使用 Read 和 Write 工具来管理记忆文件。

读取记忆

在每项任务开始时,使用 Read 工具读取 ~/.config/agent-messenger/MEMORY.md,加载之前发现的工作区 ID、频道 ID、用户 ID 和偏好设置。

  • 如果文件尚不存在,不必担心——继续执行,并在首次有有用信息需要保存时创建该文件。
  • 如果无法读取文件(权限问题、目录不存在),则不使用记忆继续执行——不要报错退出。
写入记忆

发现有用信息后,使用 Write 工具更新 ~/.config/agent-messenger/MEMORY.md。以下情况应触发写入:

  • 发现工作区 ID 后(通过 workspace list)
  • 发现有用的频道 ID 和名称后(通过 channel list、snapshot 等)
  • 发现用户 ID 和名称后(通过 user list、user me 等)
  • 用户提供别名或偏好后(例如“把这个称为部署频道”“我的主工作区是 X”)
  • 发现频道结构后(侧边栏分区、频道类别)

写入时,请包含完整的文件内容——Write 工具会覆盖整个文件。

应存储的内容
  • 带名称的工作区 ID
  • 带名称和用途的频道 ID
  • 带显示名称的用户 ID
  • 用户提供的别名(“部署频道”“主工作区”)
  • 常用的线程时间戳
  • 交互过程中表达的任何用户偏好
不应存储的内容

绝不要存储令牌、Cookie、凭据或任何敏感数据。绝不要存储完整的消息内容(只存储 ID 和频道上下文)。绝不要存储文件上传内容。

处理过期数据

如果记忆中的 ID 返回错误(找不到频道、找不到用户),请将其从 MEMORY.md 中删除。不要盲目信任记忆中的数据——发现异常时请进行验证。与其使用可能已过期的记忆 ID,不如重新列出。

格式 / 示例
# Agent Messenger Memory

## Slack Workspaces

- `T0ABC1234` — Acme Corp (default)
- `T0DEF5678` — Side Project

## Channels (Acme Corp)

- `C012ABC` — #general (company-wide announcements)
- `C034DEF` — #engineering (team discussion)
- `C056GHI` — #deploys (CI/CD notifications)

## Users (Acme Corp)

- `U0ABC123` — Alice (engineering lead)
- `U0DEF456` — Bob (backend)

## Aliases

- "deploys" → `C056GHI` (#deploys in Acme Corp)
- "main workspace" → `T0ABC1234` (Acme Corp)

## Notes

- User prefers --pretty output for snapshots
- Main workspace is "Acme Corp"

记忆功能可让你跳过重复调用 channel list 和 workspace list。如果你已经从之前的会话中知道某个 ID,请直接使用。

命令

身份验证命令
# Extract tokens from Slack desktop app or browser (usually automatic)
agent-slack auth extract
agent-slack auth extract --debug
agent-slack auth extract --browser-profile ~/browser-data
agent-slack auth extract --browser-profile ~/work-profile --browser-profile ~/personal-profile

# --browser-profile accepts repeatable or comma-separated Chromium profile/user-data dirs

# Sign in with a QR code from Slack's "Sign in on mobile" screen (no desktop app needed)
agent-slack auth qr "data:image/png;base64,..."
pbpaste | agent-slack auth qr
agent-slack auth qr --debug   # show each redirect hop for troubleshooting

# Check auth status
agent-slack auth status

# Logout from a workspace (defaults to the --workspace selection, then current)
agent-slack auth logout
agent-slack auth logout <workspace-id>
agent-slack --workspace <workspace-id> auth logout
Whoami 命令
# Show current authenticated user
agent-slack whoami
agent-slack whoami --pretty

输出包含已通过身份验证的用户身份信息。

消息命令
# Send a message
agent-slack message send <channel> <text>
agent-slack message send general "Hello world"

# Send a threaded reply
agent-slack message send general "Reply" --thread <ts>

# List messages
agent-slack message list <channel>
agent-slack message list general --limit 50

# Search messages across workspace
agent-slack message search <query>
agent-slack message search "project update"
agent-slack message search "from:@user deadline" --limit 50
agent-slack message search "in:#general meeting" --sort timestamp

# Get a single message by timestamp
agent-slack message get <channel> <ts>
agent-slack message get general 1234567890.123456

# Get thread replies (includes parent message)
agent-slack message replies <channel> <thread_ts>
agent-slack message replies general 1234567890.123456
agent-slack message replies general 1234567890.123456 --limit 50
agent-slack message replies general 1234567890.123456 --oldest 1234567890.000000
agent-slack message replies general 1234567890.123456 --cursor <next_cursor>

# Edit a message
agent-slack message edit <channel> <ts> <new-text>

# Delete a message
agent-slack message delete <channel> <ts> --force

# Schedule a message (post_at is a Unix timestamp)
agent-slack message schedule <channel> <text> <post-at>
agent-slack message schedule general "Friday update" 1700000000
agent-slack message schedule general "Thread reply" 1700000000 --thread 1234567890.123456

# List scheduled messages
agent-slack message scheduled-list
agent-slack message scheduled-list --channel general

# Delete a scheduled message
agent-slack message scheduled-delete <channel> <scheduled-message-id>

# Post ephemeral message (visible only to a specific user)
agent-slack message ephemeral <channel> <user-id> <text>

# Get a permanent link to a message
agent-slack message permalink <channel> <ts>
频道命令
# List channels (excludes archived by default)
agent-slack channel list
agent-slack channel list --type public
agent-slack channel list --type private
agent-slack channel list --type dm
agent-slack channel list --include-archived

# Get channel info
agent-slack channel info <channel>
agent-slack channel info general

# Get channel history (alias for message list)
agent-slack channel history <channel> --limit 100

# Open a DM channel with a user (returns channel ID)
agent-slack channel open <user_id>
agent-slack channel open U0ABC123

# Open a group DM with multiple users
agent-slack channel open U0ABC123,U0DEF456

# List users in a channel
agent-slack channel users <channel>
agent-slack channel users general --include-bots

# Create a new channel
agent-slack channel create <name>
agent-slack channel create my-new-channel --private

# Archive a channel
agent-slack channel archive <channel>

# Set channel topic
agent-slack channel set-topic <channel> <topic>

# Set channel purpose
agent-slack channel set-purpose <channel> <purpose>

# Invite users to a channel (comma-separated user IDs)
agent-slack channel invite <channel> <users>
agent-slack channel invite general U0ABC123,U0DEF456

# Join a channel
agent-slack channel join <channel>

# Leave a channel
agent-slack channel leave <channel>
用户命令
# List users
agent-slack user list
agent-slack user list --include-bots

# Get user info
agent-slack user info <user>

# Get current user
agent-slack user me

# Look up user by email
agent-slack user lookup <email>
agent-slack user lookup [email protected] --pretty

# Get detailed user profile
agent-slack user profile <user-id>

# Set your status (emoji name without colons)
agent-slack user set-status <status-text>
agent-slack user set-status "In a meeting" --emoji calendar
agent-slack user set-status "On vacation" --emoji palm_tree --expiration 1700100000
表情回应命令
# Add reaction
agent-slack reaction add <channel> <ts> <emoji>
agent-slack reaction add general 1234567890.123456 thumbsup

# Remove reaction
agent-slack reaction remove <channel> <ts> <emoji>

# List reactions on a message
agent-slack reaction list <channel> <ts>
文件命令
# Upload file(s)
agent-slack file upload <channel> <path...>
agent-slack file upload general ./report.pdf

# Upload into a thread with a comment (files grouped into one message)
agent-slack file upload general ./shot.png --thread 1700000000.000100 --comment "triage notes"
agent-slack file upload general ./a.png ./b.png --thread 1700000000.000100 --title "screenshots"

# --filename overrides the name (single file only); output is an object for one file, an array for several
agent-slack file upload general ./report.pdf --filename q3-report.pdf

# List files
agent-slack file list
agent-slack file list --channel general

# Get file info
agent-slack file info <file-id>

# Download file
agent-slack file download <file-id>
agent-slack file download <file-id> [output-path]
agent-slack file download F0ABC123 ./downloads/

# Delete a file
agent-slack file delete <file-id>
未读命令
# Get unread counts for all channels
agent-slack unread counts

# Get thread subscription details
agent-slack unread threads <channel> <thread_ts>

# Mark channel as read up to timestamp
agent-slack unread mark <channel> <ts>
活动命令
# List activity feed (mentions, reactions, replies)
agent-slack activity list
agent-slack activity list --limit 50
agent-slack activity list --unread
agent-slack activity list --types thread_reply,message_reaction
已保存项目命令
# List saved items
agent-slack saved list
agent-slack saved list --limit 10
agent-slack saved list --cursor <next_cursor>
草稿命令
# List all drafts
agent-slack drafts list
agent-slack drafts list --limit 10
agent-slack drafts list --cursor <next_cursor>
频道分区命令
# List channel sections (sidebar organization)
agent-slack sections list
agent-slack sections list --pretty
置顶命令
# Pin a message
agent-slack pin add <channel> <ts>

# Unpin a message
agent-slack pin remove <channel> <ts>

# List pinned messages in a channel
agent-slack pin list <channel>
agent-slack pin list general --pretty
书签命令
# Add a bookmark to a channel
agent-slack bookmark add <channel> <title> <link>
agent-slack bookmark add general "Our Docs" https://docs.example.com --emoji books --type link

# Edit a bookmark
agent-slack bookmark edit <channel> <bookmark-id> --title "New Title"
agent-slack bookmark edit <channel> <bookmark-id> --link https://new.example.com

# Remove a bookmark
agent-slack bookmark remove <channel> <bookmark-id>

# List bookmarks in a channel
agent-slack bookmark list <channel>
agent-slack bookmark list general --pretty
提醒命令
# Add a reminder (time is a Unix timestamp)
agent-slack reminder add "Review PR" 1700000000
agent-slack reminder add "Team standup" 1700000000 --user U0ABC123

# List all reminders
agent-slack reminder list
agent-slack reminder list --pretty

# Complete a reminder
agent-slack reminder complete <reminder-id>

# Delete a reminder
agent-slack reminder delete <reminder-id>
用户组命令
# List all user groups
agent-slack usergroup list
agent-slack usergroup list --include-disabled
agent-slack usergroup list --include-users --pretty

# Create a user group
agent-slack usergroup create "Marketing Team"
agent-slack usergroup create "Marketing Team" --handle marketing-team --description "Marketing gurus"
agent-slack usergroup create "Engineering" --channels C012ABC,C034DEF

# Update a user group (name, handle, description, channels)
agent-slack usergroup update <usergroup-id> --name "New Name"
agent-slack usergroup update S0616NG6M --handle new-handle --description "Updated description"
agent-slack usergroup update S0616NG6M --channels C012ABC,C034DEF

# Enable a disabled user group
agent-slack usergroup enable <usergroup-id>

# Disable a user group
agent-slack usergroup disable <usergroup-id>

# List members of a user group
agent-slack usergroup members <usergroup-id>
agent-slack usergroup members S0616NG6M --include-disabled --pretty

# Update members of a user group (replaces all members)
agent-slack usergroup members-update <usergroup-id> <comma-separated-user-ids>
agent-slack usergroup members-update S0616NG6M U060R4BJ4,U060RNRCZ
Emoji 命令
# List all custom emoji in the workspace
agent-slack emoji list
agent-slack emoji list --pretty
快照命令

获取工作区概览,供 AI Agent 使用(默认简要):

# Brief snapshot (default) — fast, minimal API calls
agent-slack snapshot

# Full snapshot — includes messages, users, user groups (slow, large output)
agent-slack snapshot --full

# Filtered full snapshots
agent-slack snapshot --full --channels-only
agent-slack snapshot --full --users-only

# Limit messages per channel (only with --full)
agent-slack snapshot --full --limit 10

默认返回包含以下内容的简要 JSON:

  • 工作区元数据
  • 频道(id、name)——仅包含未归档频道
  • 后续命令提示

使用 --full 时,返回包含以下内容的完整 JSON:

  • 工作区元数据
  • 频道(id、name、topic、purpose、is_private、is_archived)
  • 最近的消息(ts、text、user、channel)
  • 用户(id、name、profile)
  • 用户组(id、name、handle、description、user_count、users)

输出格式

JSON(默认)

所有命令默认输出 JSON,供 AI 使用:

{
  "ts": "1234567890.123456",
  "text": "Hello world",
  "channel": "C123456"
}
Pretty(人类可读)

使用 --pretty 标志输出格式化内容:

agent-slack channel list --pretty

常见模式

典型的 AI Agent 工作流请参见 references/common-patterns.md。

模板

可运行示例请参见 templates/ 目录:

  • post-message.sh - 发送消息并处理错误
  • monitor-channel.sh - 监控频道中的新消息
  • workspace-summary.sh - 生成工作区摘要

错误处理

所有命令都返回统一的错误格式:

{
  "error": "No workspace authenticated. Run: agent-slack auth extract"
}

常见错误:

  • NO_WORKSPACE:没有通过身份验证的工作区(自动提取失败——请参见故障排除)
  • SLACK_API_ERROR:Slack API 返回错误
  • RATE_LIMIT:触发 Slack 速率限制(自动退避重试)

配置

凭据存储在 ~/.config/agent-messenger/slack-credentials.json 中(权限为 0600)。格式和安全详情请参见 references/authentication.md。

SDK:二维码登录

loginWithQr 可通过普通 HTTP 将 Slack“在手机上登录”二维码图像转换为可用会话(令牌 + cookie)——无需浏览器或桌面应用。

import { loginWithQr, SlackClient, SlackCredentialManager } from 'agent-messenger/slack'

// dataUrl is the QR image as a "data:image/png;base64,..." string
const session = await loginWithQr(dataUrl)

const client = await new SlackClient().login({ token: session.token, cookie: session.cookie })
const { team_id, team } = await client.testAuth()

// Persist for later, like the CLI does
await new SlackCredentialManager().setWorkspace({
  workspace_id: team_id,
  workspace_name: team ?? session.workspace,
  token: session.token,
  cookie: session.cookie,
})

loginWithQr(dataUrl, options) 接受可选参数 { debug, fetchImpl, maxRedirects, requestConfirmationCode }。如果操作失败,它会抛出代码为 qr_session_failed(链接已过期 / 没有会话)或 qr_token_failed(无法获取令牌)的 SlackError。若要在不登录的情况下解码二维码,请使用 decodeSlackQr(dataUrl),它会返回 { url, workspace, teamId, userId }。

处理 Slack 确认码(工作区双重身份验证)

有些工作区在签发会话 Cookie 前,会在 QR 登录流程中显示确认码页面(电子邮件验证码、短信验证码、TOTP 等)。传入 requestConfirmationCode 即可完成此步骤。只有 Slack 实际显示确认页面时才会调用此回调——直接收到会话 Cookie 的普通 QR 登录不会要求输入提示词。

import { loginWithQr, type SlackConfirmationChallenge } from 'agent-messenger/slack'

const session = await loginWithQr(dataUrl, {
  requestConfirmationCode: async (challenge: SlackConfirmationChallenge) => {
    // challenge.email is the address Slack sent the code to.
    // challenge.type is the mechanism ("email", "sms", "totp", ...) or null if unknown.
    return await promptUserForCode(challenge)
  },
})

约定:

  • 返回原始验证码,类型为 string。提交前会去除空白字符。
  • 返回空字符串(或全为空白字符)以中止操作——loginWithQr 会抛出 qr_session_failed,且不会提交任何验证码。
  • 验证码会提交到与 QR 载荷绑定的确切 https://<workspace>.slack.com/login/<qrSecret> 端点。如果重定向到其他工作区主机或意外的路径名,则会在调用回调前拒绝此流程。
  • 回调以及 email/type 字段绝不会出现在 debug 输出中。

SDK:实时事件

SlackListener 会连接到 Slack 的 RTM WebSocket,即时流式接收事件。无需轮询——事件会实时到达。

设置
import { SlackClient, SlackListener } from 'agent-messenger/slack'

const client = await new SlackClient().login()
const listener = new SlackListener(client)

也可以使用手动凭据:

import { SlackClient, SlackListener } from 'agent-messenger/slack'

const client = await new SlackClient().login({ token, cookie })
const listener = new SlackListener(client)
监听事件
listener.on('connected', (info) => {
  console.log(`Connected as ${info.self.id} on ${info.team.id}`)
})

listener.on('message', (event) => {
  // event.type, event.channel, event.user, event.text, event.ts
})

listener.on('reaction_added', (event) => {
  // event.user, event.reaction, event.item.channel, event.item.ts
})

listener.on('reaction_removed', (event) => {
  // same shape as reaction_added
})

listener.on('member_joined_channel', (event) => {
  // event.user, event.channel
})

listener.on('member_left_channel', (event) => {
  // event.user, event.channel
})

listener.on('user_typing', (event) => {
  // event.user, event.channel
})

listener.on('presence_change', (event) => {
  // event.user, event.presence ('active' | 'away')
})

// Catch-all for any RTM event type
listener.on('slack_event', (event) => {
  // event.type + all fields
})

listener.on('error', (err) => {
  console.error(err.message)
})

listener.on('disconnected', () => {
  // auto-reconnects with exponential backoff
})
生命周期
await listener.start()  // connects via RTM WebSocket
listener.stop()         // clean shutdown
事件类型
事件说明
message新消息、编辑、删除、线程回复、加入/离开子类型
reaction_added为消息添加表情回应
reaction_removed移除消息上的表情回应
member_joined_channel用户加入频道
member_left_channel用户离开频道
user_typing用户正在输入
presence_change用户变为活跃/离开状态
channel_created创建新频道
channel_deleted删除频道
channel_rename重命名频道
channel_archive归档频道
channel_unarchive取消归档频道
slack_event捕获所有 RTM 事件
connectedWebSocket 已连接
disconnectedWebSocket 已断开(会自动重新连接)
error连接或 API 错误
说明
  • 接收已认证用户在工作区中的所有事件——无需订阅频道
  • 使用指数退避自动重新连接(1 秒 → 最长 30 秒)
  • 每 30 秒发送一次 ping/pong 保活信号
  • 使用 Slack 的 RTM API 和 xoxc 用户令牌

限制

  • 仅支持纯文本消息(v1 不支持 blocks/格式)

故障排除

agent-slack: command not found

agent-slack 不是 npm 包名称。 npm 包名为 agent-messenger。

如果已全局安装该包,可直接使用 agent-slack:

agent-slack message list general

如果尚未安装该包,默认使用 npx -y。不要询问用户要使用哪个包运行器——直接运行即可:

npx -y agent-messenger slack message list general
bunx agent-messenger slack message list general
pnpm dlx agent-messenger slack message list general

如果你已知用户偏好的包运行器(例如 bunx、pnpm dlx),则改用该运行器。

绝不要运行 npx agent-slack、bunx agent-slack 或 pnpm dlx agent-slack——npm 上有一个名称为 agent-slack 的独立无关包。它会静默安装错误的包,且提供的命令不同(更少)。

Failed to read Slack cookies

如果看到:

{"error":"Failed to read Slack cookies. The Slack app is currently running and locking the cookie database. Quit the Slack app completely and try again."}

告知用户你需要退出 Slack 应用以提取凭据,并征求确认。如果用户同意,请退出 Slack 并重试该命令。

其他故障排除内容(身份验证提取、令牌问题、Keychain)请参阅身份验证指南。

参考资料

评论

支持 Markdown