Slack机器人构建器Skill slack-bot-builder

此技能用于使用Slack的Bolt框架构建高效、安全的Slack应用,支持Python、JavaScript和Java,涵盖Block Kit丰富UI、交互组件、斜杠命令、事件处理、OAuth安装流程和工作流构建器集成,专注于生产就绪应用的最佳实践。关键词:Slack应用、Bolt框架、Block Kit、Python、JavaScript、Java、OAuth、生产就绪。

后端开发 0 次安装 0 次浏览 更新于 3/21/2026

名称: slack-bot-builder 描述: “使用Bolt框架在Python、JavaScript和Java中构建Slack应用。涵盖Block Kit用于丰富UI、交互组件、斜杠命令、事件处理、OAuth安装流程和工作流构建器集成。专注于生产就绪的Slack应用的最佳实践。使用时机: slack机器人、slack应用、bolt框架、block kit、斜杠命令。” 来源: vibeship-spawner-skills (Apache 2.0)

Slack机器人构建器

模式

Bolt应用基础模式

Bolt框架是Slack推荐的构建应用的方法。 它处理认证、事件路由、请求验证和HTTP请求处理,让您可以专注于应用逻辑。

关键优势:

  • 几行代码处理事件
  • 内置安全检查与负载验证
  • 组织化、一致的模式
  • 适用于实验和生产

可用语言:Python、JavaScript(Node.js)、Java

使用时机: [‘启动任何新Slack应用’, ‘从旧版Slack API迁移’, ‘构建生产Slack集成’]

# Python Bolt应用
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
import os

# 从环境变量初始化令牌
app = App(
    token=os.environ["SLACK_BOT_TOKEN"],
    signing_secret=os.environ["SLACK_SIGNING_SECRET"]
)

# 处理包含"hello"的消息
@app.message("hello")
def handle_hello(message, say):
    """响应包含'hello'的消息。"""
    user = message["user"]
    say(f"嘿,<@{user}>!")

# 处理斜杠命令
@app.command("/ticket")
def handle_ticket_command(ack, body, client):
    """处理/ticket斜杠命令。"""
    # 立即确认(3秒内)
    ack()

    # 打开工单创建模态
    client.views_open(
        trigger_id=body["trigger_id"],
        view={
            "type": "modal",
            "callback_id": "ticket_modal",
            "title": {"type": "plain_text", "text": "创建工单"},
            "submit": {"type": "plain_text", "text": "提交"},
            "blocks": [
                {
                    "type": "input",
                    "block_id": "title_block",
                    "element": {
                        "type": "plain_text_input",
                        "action_id": "title_input"
                    },
                    "label": {"type": "plain_text", "text": "标题"}
                },
                {
                    "type": "input",
                    "block_id": "desc_block",
                    "element": {
                        "type": "plain_text_input",
                        "multiline": True,
                        "action_id": "desc_input"
                    },
                    "label": {"type": "plain_text", "text": "描述"}
                },
                {
                    "type": "input",
                    "block_id": "priority_block",
                    "element": {
                        "type": "static_select",
                        "action_id": "priority_select",
                    }
                }
            ]
        }
    )

Block Kit UI模式

Block Kit是Slack的UI框架,用于构建丰富、交互式消息。 使用块(部分、操作、输入)和元素(按钮、菜单、文本输入)组合消息。

限制:

  • 每条消息最多50个块
  • 模态/首页选项卡最多100个块
  • 块文本限制为3000字符

使用Block Kit Builder进行原型设计:https://app.slack.com/block-kit-builder

使用时机: [‘构建丰富消息布局’, ‘向消息添加交互组件’, ‘在模态中创建表单’, ‘构建首页选项卡体验’]

from slack_bolt import App
import os

app = App(token=os.environ["SLACK_BOT_TOKEN"])

def build_notification_blocks(incident: dict) -> list:
    """为事件通知构建Block Kit块。"""
    severity_emoji = {
        "critical": ":red_circle:",
        "high": ":large_orange_circle:",
        "medium": ":large_yellow_circle:",
        "low": ":white_circle:"
    }

    return [
        # 头部
        {
            "type": "header",
            "text": {
                "type": "plain_text",
                "text": f"{severity_emoji.get(incident['severity'], '')} 事件警报"
            }
        },
        # 详细信息部分
        {
            "type": "section",
            "fields": [
                {
                    "type": "mrkdwn",
                    "text": f"*事件:*
{incident['title']}"
                },
                {
                    "type": "mrkdwn",
                    "text": f"*严重性:*
{incident['severity'].upper()}"
                },
                {
                    "type": "mrkdwn",
                    "text": f"*服务:*
{incident['service']}"
                },
                {
                    "type": "mrkdwn",
                    "text": f"*报告时间:*
<!date^{incident['timestamp']}^{date_short} {time}|{incident['timestamp']}>"
                }
            ]
        },
        # 描述
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": f"*描述:*
{incident['description'][:2000]}"
            }
        },
        # 分隔符
        {"type": "divider"},
        # 操作按钮
        {
            "type": "actions",
            "block_id": f"incident_actions_{incident['id']}",
            "elements": [
                {
                    "type": "button",
                    "text": {"type": "plain_text", "text": "确认"},
                    "style": "primary",
                    "action_id": "acknowledge"
                }
            ]
        }
    ]

OAuth安装模式

通过OAuth 2.0允许用户在他们的工作区安装您的应用。 Bolt处理大部分OAuth流程,但您需要配置并安全存储令牌。

关键OAuth概念:

  • 范围定义权限(请求最小所需)
  • 令牌是工作区特定的
  • 安装数据必须持久存储
  • 用户可以稍后添加范围(可叠加)

70%的用户在遇到过多权限请求时会放弃安装 - 仅请求所需内容!

使用时机: [‘分发应用到多个工作区’, ‘构建公开Slack应用’, ‘企业级集成’]

from slack_bolt import App
from slack_bolt.oauth.oauth_settings import OAuthSettings
from slack_sdk.oauth.installation_store import FileInstallationStore
from slack_sdk.oauth.state_store import FileOAuthStateStore
import os

# 对于生产环境,使用数据库支持的存储
# 例如:PostgreSQL、MongoDB、Redis

class DatabaseInstallationStore:
    """在您的数据库中存储安装数据。"""

    async def save(self, installation):
        """用户完成OAuth时保存安装。"""
        await db.installations.upsert({
            "team_id": installation.team_id,
            "enterprise_id": installation.enterprise_id,
            "bot_token": encrypt(installation.bot_token),
            "bot_user_id": installation.bot_user_id,
            "bot_scopes": installation.bot_scopes,
            "user_id": installation.user_id,
            "installed_at": installation.installed_at
        })

    async def find_installation(self, *, enterprise_id, team_id, user_id=None, is_enterprise_install=False):
        """为工作区查找安装。"""
        record = await db.installations.find_one({
            "team_id": team_id,
            "enterprise_id": enterprise_id
        })

        if record:
            return Installation(
                bot_token=decrypt(record["bot_token"]),
                # ... 其他字段
            )
        return None

# 初始化启用OAuth的应用
app = App(
    signing_secret=os.environ["SLACK_SIGNING_SECRET"],
    oauth_settings=OAuthSettings(
        client_id=os.environ["SLACK_CLIENT_ID"],
        client_secret=os.environ["SLACK_CLIENT_SECRET"],
        scopes=[
            "channels:history",
            "channels:read",
            "chat:write",
            "commands",
            "users:read"
        ],
        user_scopes=[],  # 如果需要用户令牌范围
        installation_store=DatabaseInstallationStore(),
        state_store=FileOAuthStateStore(expiration_seconds=600)
    )
)

# OAuth路由由Bolt处理

⚠️ 注意事项

问题 严重性 解决方案
立即确认,稍后处理 关键 确保在3秒内确认请求
正确状态验证 关键 验证所有状态以防止安全漏洞
切勿硬编码或记录令牌 关键 使用环境变量并加密存储
请求最小所需范围 仅请求应用功能必需的范围
了解并尊重限制 遵循Slack API的限制以避免错误
Socket模式:仅用于开发 在生产中使用HTTP模式
Bolt自动处理验证 关键 依赖框架的内置安全功能