Skip to content

Latest commit

 

History

History
679 lines (535 loc) · 15.2 KB

File metadata and controls

679 lines (535 loc) · 15.2 KB

TaskSentinel 集成指南

中文 | English

本文档介绍如何将 TaskSentinel 与各种应用程序和工具集成,实现自动化通知。

🔌 支持的集成

1. Claude Code (官方支持)

TaskSentinel 提供专门的 Claude Code 适配器,支持无缝集成。

快速配置

# 1. 复制示例配置
cp config/claude-settings.example.json .claude/settings.json

# 2. 配置通知设置
nano ~/.tasksentry/config.json

# 3. 测试集成
echo '{"type": "notification", "message": "测试消息"}' | ./scripts/claude-hook-adapter.sh

支持的钩子事件

  • Notification: Claude Code 通知事件,支持@提及相关开发者
  • Stop: 主任务完成事件,自动@任务负责人
  • SubagentStop: 子任务完成事件,通知项目进度

@提及功能集成

TaskSentinel 的@提及功能与 Claude Code 完美配合:

钉钉配置示例:

{
  "platforms": {
    "dingtalk": {
      "enabled": true,
      "webhook_url": "your_webhook_url",
      "mentions": {
        "enabled": true,
        "user_mappings": {
          "developer": {
            "name": "开发者",
            "mobile": "13800138000"
          },
          "pm": {
            "name": "项目经理", 
            "mobile": "13800138001"
          }
        },
        "event_mentions": {
          "task_complete": ["developer"],    // 任务完成通知开发者
          "error": ["developer", "pm"],      // 错误时通知开发者和项目经理
          "info": ["pm"]                     // 进度信息通知项目经理
        }
      }
    }
  }
}

企业微信配置详解

企业微信支持多种消息格式,不同格式对 @提及功能的支持程度不同。

如需使用 @提及功能,推荐使用 text 格式:

{
  "platforms": {
    "wechat": {
      "enabled": true,
      "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY",
      "format": "text",
      "mentions": {
        "enabled": true,
        "user_mappings": {
          "developer": {
            "userid": "developer_userid_here",
            "mobile": "13800138000"
          },
          "pm": {
            "userid": "pm_userid_here",
            "mobile": "13800138001"
          }
        },
        "event_mentions": {
          "task_complete": ["developer"],    // 任务完成通知开发者
          "error": ["developer", "pm"],      // 错误时通知开发者和项目经理
          "info": ["pm"]                     // 进度信息通知项目经理
        }
      }
    }
  }
}

如需更丰富的格式,可使用 markdown 或 markdown_v2 格式:

{
  "platforms": {
    "wechat": {
      "enabled": true,
      "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY",
      "format": "markdown_v2"
    }
  }
}

消息格式对比

格式 @提及功能 富文本支持 推荐场景
text ✅ 支持 ❌ 纯文本 需要@提及用户的通知
markdown ❌ 不支持 ✅ 基础格式 不需要@提及的格式化消息
markdown_v2 ❌ 不支持 ✅ 丰富格式 不需要@提及的精美消息

markdown_v2 格式详细说明

消息参数:

参数 是否必填 说明
msgtype 消息类型,固定为 markdown_v2
content markdown_v2 内容,最长不超过 4096 个字节,必须是 utf8 编码

特殊说明:

  1. 不支持的功能

    • 字体颜色设置
    • @群成员语法(@all 和 @specific_user 不可用)
  2. 客户端版本要求

    • Android 客户端:4.1.38 及以上版本
    • iOS 客户端:4.1.36 及以上版本
    • 低版本客户端将显示为纯文本格式

支持的 markdown_v2 语法示例:

# 标题
## 二级标题
### 三级标题

**粗体文本**
*斜体文本*

- 无序列表项1
- 无序列表项2

1. 有序列表项1
2. 有序列表项2

`行内代码`

\```
代码块
\```

[链接文本](https://example.com)

> 引用文本

---
分割线

重要提醒

  • 如果需要使用 @提及功能,必须选择 text 格式
  • markdownmarkdown_v2 格式均不支持 @提及功能
  • 企业微信的 user_mappings 中:
    • userid:必填,企业微信的用户ID(通过企业微信管理后台获取)
    • mobile:可选,作为备选的手机号提及方式
    • 不需要 name 字段,企业微信API不使用显示名称

详细配置请参考 Claude Code Hooks 配置文档

2. GitHub Actions

在 GitHub Actions 工作流中使用 TaskSentinel 发送构建和部署通知。

配置示例

name: CI/CD Pipeline
on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup TaskSentinel
        run: |
          curl -fsSL https://raw.githubusercontent.com/TaskSentinel/TaskSentinel/main/scripts/install.sh | bash
          echo '${{ secrets.TASKSENTRY_CONFIG }}' > ~/.tasksentry/config.json
      
      - name: Build Application
        run: |
          npm ci
          npm run build
          
      - name: Notify Build Success
        if: success()
        run: |
          tasksentry --message "✅ 构建成功: ${{ github.repository }} @ ${{ github.sha }}"
          
      - name: Notify Build Failure
        if: failure()
        run: |
          tasksentry --message "❌ 构建失败: ${{ github.repository }} @ ${{ github.sha }}"

配置 Secrets

在 GitHub 仓库设置中添加:

TASKSENTRY_CONFIG = {
  "platform": "dingtalk",
  "webhook_url": "your_webhook_url",
  "secret": "your_secret",
  "format": "markdown",
  "mentions": {
    "enabled": true,
    "user_mappings": {
      "admin": {
        "name": "管理员",
        "mobile": "13800138000"
      },
      "devops": {
        "name": "运维",
        "mobile": "13800138001"
      }
    },
    "event_mentions": {
      "error": ["admin", "devops"],
      "warning": ["devops"],
      "task_complete": ["devops"],
      "info": []
    }
  }
}

带@提及的高级配置示例

- name: Notify Build Success with Mentions
  if: success()
  run: |
    echo '{"event": "task_complete", "message": "CI/CD 构建成功: ${{ github.repository }} @ ${{ github.sha }}"}' | \
    tasksentry
    
- name: Notify Build Failure with Mentions
  if: failure()  
  run: |
    echo '{"event": "error", "message": "CI/CD 构建失败: ${{ github.repository }} @ ${{ github.sha }},请检查构建日志"}' | \
    tasksentry

3. Jenkins

在 Jenkins 管道中集成 TaskSentinel。

Pipeline 示例

pipeline {
    agent any
    
    stages {
        stage('Setup') {
            steps {
                script {
                    // 安装 TaskSentinel
                    sh 'curl -fsSL https://raw.githubusercontent.com/TaskSentinel/TaskSentinel/main/scripts/install.sh | bash'
                    
                    // 配置文件
                    writeFile file: '/home/jenkins/.tasksentry/config.json', text: env.TASKSENTRY_CONFIG
                }
            }
        }
        
        stage('Build') {
            steps {
                sh 'npm ci && npm run build'
            }
            post {
                success {
                    sh 'tasksentry --message "✅ Jenkins 构建成功: ${JOB_NAME} #${BUILD_NUMBER}"'
                }
                failure {
                    sh 'tasksentry --message "❌ Jenkins 构建失败: ${JOB_NAME} #${BUILD_NUMBER}"'
                }
            }
        }
        
        stage('Deploy') {
            when {
                branch 'main'
            }
            steps {
                sh 'npm run deploy'
            }
            post {
                success {
                    sh 'tasksentry --message "🚀 部署成功: ${JOB_NAME} #${BUILD_NUMBER} 已部署到生产环境"'
                }
            }
        }
    }
}

4. Docker

在 Docker 容器中使用 TaskSentinel。

Dockerfile 示例

FROM ubuntu:22.04

# 安装依赖
RUN apt-get update && apt-get install -y \
    curl \
    jq \
    openssl \
    && rm -rf /var/lib/apt/lists/*

# 安装 TaskSentinel
RUN curl -fsSL https://raw.githubusercontent.com/TaskSentinel/TaskSentinel/main/scripts/install.sh | bash

# 复制配置文件
COPY config.json /root/.tasksentry/config.json

# 应用启动脚本
COPY start.sh /usr/local/bin/start.sh
RUN chmod +x /usr/local/bin/start.sh

CMD ["/usr/local/bin/start.sh"]

启动脚本示例

#!/bin/bash
# start.sh

set -e

# 发送启动通知
tasksentry --message "🐳 容器启动: $(hostname) @ $(date)"

# 启动应用
exec "$@"

# 捕获退出信号
trap 'tasksentry --message "🛑 容器停止: $(hostname) @ $(date)"' EXIT

5. Cron Jobs

在定时任务中使用 TaskSentinel。

示例配置

# 编辑 crontab
crontab -e

# 每日备份通知
0 2 * * * /usr/local/bin/backup.sh && tasksentry --message "✅ 每日备份完成" || tasksentry --message "❌ 每日备份失败"

# 每小时健康检查
0 * * * * curl -f http://localhost:8080/health && tasksentry --message "✅ 服务健康检查通过" || tasksentry --message "⚠️ 服务健康检查失败"

# 每周系统更新
0 3 * * 0 sudo apt update && sudo apt upgrade -y && tasksentry --message "🔄 系统更新完成"

6. Systemd 服务

在 systemd 服务中集成通知。

服务文件示例

# /etc/systemd/system/myapp.service
[Unit]
Description=My Application
After=network.target

[Service]
Type=simple
User=myapp
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/start.sh
ExecStartPost=/usr/local/bin/tasksentry --message "🚀 服务启动: MyApp"
ExecStopPost=/usr/local/bin/tasksentry --message "🛑 服务停止: MyApp"
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

7. Monitoring 工具集成

Nagios

# /usr/local/nagios/etc/objects/commands.cfg
define command{
    command_name    notify-tasksentry
    command_line    /usr/local/bin/tasksentry --message "$NOTIFICATIONTYPE$: $HOSTALIAS$ - $SERVICEDESC$ is $SERVICESTATE$"
}

Zabbix

在 Zabbix 中创建媒体类型:

# 脚本: /usr/lib/zabbix/alertscripts/tasksentry.sh
#!/bin/bash
MESSAGE="$3"
SUBJECT="$2"
tasksentry --message "⚠️ Zabbix 告警: $SUBJECT - $MESSAGE"

8. 自定义应用集成

Shell 脚本集成

#!/bin/bash
# 您的脚本

# 开始通知
tasksentry --message "🚀 开始执行: $(basename "$0")"

# 执行业务逻辑
if your_command; then
    tasksentry --message "✅ 执行成功: $(basename "$0")"
else
    tasksentry --message "❌ 执行失败: $(basename "$0")"
    exit 1
fi

Python 集成

#!/usr/bin/env python3
import subprocess
import sys

def notify(message, event_type="info"):
    """发送 TaskSentinel 通知"""
    try:
        json_data = f'{{"message": "{message}", "event": "{event_type}"}}'
        subprocess.run(
            ['tasksentry'], 
            input=json_data,
            text=True,
            check=True
        )
    except subprocess.CalledProcessError as e:
        print(f"通知发送失败: {e}", file=sys.stderr)

# 使用示例
notify("Python 脚本开始执行")

try:
    # 您的业务逻辑
    result = perform_task()
    notify("✅ Python 脚本执行成功", "task_complete")
except Exception as e:
    notify(f"❌ Python 脚本执行失败: {str(e)}", "error")
    sys.exit(1)

Node.js 集成

const { spawn } = require('child_process');

function notify(message, eventType = 'info') {
    return new Promise((resolve, reject) => {
        const tasksentry = spawn('tasksentry');
        
        const jsonData = JSON.stringify({
            message: message,
            event: eventType
        });
        
        tasksentry.stdin.write(jsonData);
        tasksentry.stdin.end();
        
        tasksentry.on('close', (code) => {
            if (code === 0) {
                resolve();
            } else {
                reject(new Error(`TaskSentinel exited with code ${code}`));
            }
        });
    });
}

// 使用示例
async function main() {
    try {
        await notify('Node.js 应用启动');
        
        // 您的业务逻辑
        await performTask();
        
        await notify('✅ Node.js 任务完成', 'task_complete');
    } catch (error) {
        await notify(`❌ Node.js 任务失败: ${error.message}`, 'error');
        process.exit(1);
    }
}

main();

🔧 高级集成技巧

1. 环境变量配置

# 设置全局配置路径
export TASKSENTRY_CONFIG="$HOME/.tasksentry/config.json"

# 启用调试模式
export TASKSENTRY_DEBUG=true

# 自定义节流时间
export TASKSENTRY_THROTTLE=120

2. 多平台配置管理

为不同环境和平台创建配置文件模板:

# 开发环境 - 只启用钉钉
cp config/config.dev.json ~/.tasksentry/config.json

# 测试环境 - 启用钉钉和企业微信
cp config/config.test.json ~/.tasksentry/config.json

# 生产环境 - 启用所有平台
cp config/config.prod.json ~/.tasksentry/config.json

环境特定配置示例

开发环境配置 (config.dev.json):

{
  "debug": true,
  "throttle_seconds": 30,
  "platforms": {
    "dingtalk": {
      "enabled": true,
      "webhook_url": "...",
      "format": "text"
    },
    "wechat": {
      "enabled": false
    },
    "slack": {
      "enabled": false
    }
  }
}

生产环境配置 (config.prod.json):

{
  "debug": false,
  "throttle_seconds": 60,
  "platforms": {
    "dingtalk": {
      "enabled": true,
      "webhook_url": "...",
      "format": "text"
    },
    "wechat": {
      "enabled": true,
      "webhook_url": "...",
      "format": "markdown"
    },
    "slack": {
      "enabled": true,
      "webhook_url": "...",
      "format": "json"
    }
  }
}

3. 批量通知

#!/bin/bash
# 批量发送多个通知

MESSAGES=(
    "任务1完成"
    "任务2完成" 
    "任务3完成"
)

for msg in "${MESSAGES[@]}"; do
    tasksentry --message "$msg"
    sleep 2  # 避免频率限制
done

4. 条件通知

#!/bin/bash
# 仅在特定条件下发送通知

ENVIRONMENT="${NODE_ENV:-development}"

if [[ "$ENVIRONMENT" == "production" ]]; then
    tasksentry --message "生产环境部署完成"
elif [[ "$ENVIRONMENT" == "staging" ]]; then
    tasksentry --message "预发布环境部署完成"
fi

🚨 故障排除

常见集成问题

  1. 权限问题

    chmod +x /usr/local/bin/tasksentry
    chmod 600 ~/.tasksentry/config.json
  2. 路径问题

    which tasksentry
    echo $PATH
  3. 配置问题

    tasksentry --debug --message "测试消息"
  4. 网络问题

    curl -X POST -H "Content-Type: application/json" -d '{"msgtype":"text","text":{"content":"测试"}}' "YOUR_WEBHOOK_URL"

📚 更多资源


如需更多集成支持,请访问 GitHub Issues 提交请求。