为什么选择 OpenClaw 做自动化?

传统的自动化工具(如 Cron、Jenkins、GitHub Actions)各有局限:

| 工具 | 优势 | 局限 |
|------|------|------|
| **Cron** | 简单定时 | 无智能决策能力,出错难感知 |
| **IFTTT/Zapier** | 可视化编排 | 依赖云服务,隐私顾虑,费用高 |
| **Python 脚本** | 灵活强大 | 需要编码能力,维护成本高 |
| **Jenkins** | 企业级 | 太重,不适合个人日常任务 |

OpenClaw 的独特优势

┌─────────────────────────────────────────┐
│ 自然语言编排工作流 │
│ "每天早上8点抓取科技新闻, │
│ 用 AI 总结要点,发到我的 Telegram" │
├─────────────────────────────────────────┤
│ 失败自动重试 + AI 诊断 │
│ "任务失败?让 AI 分析日志并通知我" │
├─────────────────────────────────────────┤
│ 多通道触达 │
│ 微信/邮件/短信/Slack 灵活切换 │
├─────────────────────────────────────────┤
│ 本地执行,数据不出境 │
│ 敏感操作(如财务数据)完全私密 │
└─────────────────────────────────────────┘


---

## 核心概念:Cron + Agent + Skill

OpenClaw 的自动化由三个层面组成:

### 1. Cron 表达式(触发器)

```yaml
# workflows/daily-report.yaml
trigger:
  type: cron
  schedule: "0 9 * * 1-5"  # 工作日早上9点
  
  # 或者使用自然语言(需要安装 natural-cron skill)
  # natural: "每个工作日早上9点"
  
  # 时区设置
  timezone: "Asia/Shanghai"
  
  # 延迟执行(防止整点峰值)
  jitter: "0-10m"  # 随机延迟0-10分钟

2. Agent(执行大脑)

executor:
  agent: scheduler-agent
  model: openai/gpt-4-turbo-preview
  
  # 给调度器专门的系统提示词
  systemPrompt: |
    你是一个任务调度助手,擅长:
    1. 分析任务执行结果
    2. 决定是否需要重试
    3. 生成简洁的执行报告
    
    规则:
    - 成功任务:一句话总结
    - 失败任务:分析原因,给出建议
    - 异常数据:标记并告警

3. Skill(能力原子)

steps:
  - name: fetch-news
    skill: web-search
    input:
      query: "科技新闻 人工智能 今日"
      limit: 5
      
  - name: summarize
    skill: text-process
    input:
      action: summarize
      content: "{{steps.fetch-news.output}}"
      maxLength: 200
      
  - name: notify
    skill: telegram-send
    input:
      chatId: "{{secrets.TELEGRAM_CHAT_ID}}"
      message: "📰 今日科技早报\n\n{{steps.summarize.output}}"

实战 1:每日信息早报

目标:每天早上自动抓取新闻、天气、股票,生成个性化早报推送到手机。

配置结构

workflows/
├── morning-briefing/
│   ├── workflow.yaml      # 主配置
│   ├── prompts/
│   │   └── summary.txt    # AI 总结模板
│   └── scripts/
│       └── format.js      # 数据格式化

完整配置

# workflows/morning-briefing/workflow.yaml
name: morning-briefing
description: 每日早报生成
version: 1.0.0

trigger:
  type: cron
  schedule: "0 8 * * *"  # 每天8点
  timezone: "Asia/Shanghai"

variables:
  # 用户配置
  city: "北京"
  stockCodes: ["000001", "AAPL"]
  newsKeywords: ["人工智能", "前端技术", "科技"]

steps:
  # 步骤1:获取天气
  - id: weather
    name: 获取天气
    skill: weather
    action: getForecast
    input:
      location: "{{vars.city}}"
      days: 1
      
  # 步骤2:并行获取多条股票
  - id: stocks
    name: 获取股票
    skill: stock-query
    action: batchQuery
    parallel: true  # 并行执行
    input:
      symbols: "{{vars.stockCodes}}"
      
  # 步骤3:搜索新闻
  - id: news
    name: 获取新闻
    skill: web-search
    input:
      queries: "{{vars.newsKeywords}}"
      limit: 3
      source: "news"
      
  # 步骤4:AI 总结生成早报
  - id: generate
    name: 生成早报
    skill: llm-generate
    model: openai/gpt-4
    input:
      template: |
        请根据以下信息生成一份简洁的早报(300字以内):
        
        【天气】{{steps.weather.output}}
        【股市】{{steps.stocks.output}}
        【新闻要点】{{steps.news.output}}
        
        要求:
        1. 语气轻松,像朋友在聊天
        2. 股票涨跌幅用 📈📉 表情
        3. 最后加一句今日寄语
        
  # 步骤5:推送消息
  - id: send
    name: 发送消息
    skill: telegram-send
    condition: "{{steps.generate.status == 'success'}}"  # 条件执行
    input:
      chatId: "{{secrets.USER_CHAT_ID}}"
      message: "☀️ 早安!{{steps.generate.output}}"
      parseMode: "Markdown"
      
  # 失败处理
  onFailure:
    - skill: telegram-send
      input:
        chatId: "{{secrets.USER_CHAT_ID}}"
        message: "⚠️ 早报生成失败:{{error.message}}"
        
    - skill: log-store  # 记录错误日志
      input:
        level: error
        message: "{{error.stack}}"

数据格式化脚本

// workflows/morning-briefing/scripts/stockFormatter.js
module.exports = function formatStocks(stockData) {
  return stockData.map(s => {
    const emoji = s.change >= 0 ? '📈' : '📉';
    const changeStr = (s.change >= 0 ? '+' : '') + s.changePercent + '%';
    return `${emoji} ${s.name}: ${s.price} (${changeStr})`;
  }).join('\n');
};

使用方式:

- id: formatStocks
  name: 格式化股票数据
  script: "./scripts/stockFormatter.js"
  input: "{{steps.stocks.output}}"

执行效果:

☀️ 早安!
今天是2024年1月15日,北京晴,温度-2~8°C,记得穿厚点!

📈 平安银行: 10.52 (+1.25%)
📉 苹果: 185.92 (-0.82%)

【今日科技动态】
1. OpenAI 发布 GPT-5 预览版,多模态能力大幅提升
2. React 19 进入 RC 阶段,新特性值得期待
3. 国内首个 AI 编程助手通过备案...

💡 今日寄语:冬天到了,春天还会远吗?

实战 2:智能文件整理助手

目标:监控下载文件夹,自动分类整理文件,并用 AI 生成摘要。

触发器:文件系统监控

# workflows/file-organizer/workflow.yaml
trigger:
  type: filesystem
  watch:
    path: "~/Downloads"
    events: ["create"]  # 新文件创建时触发
    filter:
      exclude: ["*.tmp", "*.crdownload", ".DS_Store"]
      
  # 防抖:文件写入完成后触发(避免大文件未写完就处理)
  debounce: "5s"

文件分类逻辑

steps:
  # 步骤1:分析文件类型
  - id: classify
    name: 文件分类
    skill: file-classifier
    input:
      filePath: "{{trigger.filePath}}"
      rules:
        - pattern: "*.pdf"
          category: "documents"
          subClassify: true  # PDF 再细分
          
        - pattern: "*.{jpg,png,heic}"
          category: "images"
          
        - pattern: "*.{mp4,mov,avi}"
          category: "videos"
          
        - pattern: "*.{zip,rar,7z}"
          category: "archives"
          
        - pattern: "*.{exe,dmg,pkg}"
          category: "installers"

  # 步骤2:根据类型处理
  - id: process
    name: 处理文件
    switch: "{{steps.classify.output.category}}"
    
    cases:
      documents:
        - skill: pdf-extract
          input:
            file: "{{trigger.filePath}}"
          output: docContent
            
        - skill: llm-generate
          input:
            prompt: |
              总结这份文档的核心内容(100字以内):
              {{steps.process.docContent}}
          output: summary
          
        - skill: file-move
          input:
            source: "{{trigger.filePath}}"
            dest: "~/Documents/{{steps.classify.output.subCategory}}/"
            
        - skill: metadata-write
          input:
            file: "~/Documents/{{steps.classify.output.subCategory}}/{{trigger.fileName}}"
            meta:
              summary: "{{steps.process.summary}}"
              originalName: "{{trigger.fileName}}"
              processedAt: "{{now}}"

      images:
        - skill: image-recognize
          input:
            image: "{{trigger.filePath}}"
          output: imageInfo
          
        - skill: file-move
          input:
            source: "{{trigger.filePath}}"
            dest: "~/Pictures/{{steps.process.imageInfo.date|format:'YYYY-MM'}}/"

      videos:
        - skill: file-move
          input:
            source: "{{trigger.filePath}}"
            dest: "~/Movies/"

      default:
        - skill: notify
          input:
            message: "未分类文件:{{trigger.fileName}}"

处理结果展示

文件移动后,会生成一个索引文件:

// ~/Documents/.index.json
{
  "files": [
    {
      "name": "react-best-practices.pdf",
      "path": "documents/frontend/react-best-practices.pdf",
      "summary": "React 性能优化指南,涵盖 useMemo、useCallback 使用场景...",
      "tags": ["react", "performance"],
      "processedAt": "2024-01-15T09:23:00Z"
    }
  ]
}

配合搜索 Skill,可以快速找到文件:

用户: 查找关于 React 性能的文件
AI: 找到 1 个文件:
    📄 react-best-practices.pdf
    摘要:React 性能优化指南...
    路径:documents/frontend/

实战 3:服务器监控告警

目标:定时检测服务器状态,异常时自动诊断并通知。

监控工作流

# workflows/server-monitor/workflow.yaml
trigger:
  type: cron
  # 每5分钟检查一次
  schedule: "*/5 * * * *"

steps:
  # 步骤1:收集系统指标
  - id: metrics
    name: 获取指标
    parallel:
      - skill: ssh-exec
        name: cpu
        input:
          host: "{{secrets.SERVER_HOST}}"
          command: "top -bn1 | grep 'Cpu(s)'"
          
      - skill: ssh-exec
        name: memory
        input:
          host: "{{secrets.SERVER_HOST}}"
          command: "free -m | awk 'NR==2{printf \"%.2f%%\", $3*100/$2}'"
          
      - skill: ssh-exec
        name: disk
        input:
          host: "{{secrets.SERVER_HOST}}"
          command: "df -h / | awk 'NR==2 {print $5}'"
          
      - skill: ssh-exec
        name: load
        input:
          host: "{{secrets.SERVER_HOST}}"
          command: "uptime | awk -F'load average:' '{print $2}'"

  # 步骤2:AI 分析健康状况
  - id: analyze
    name: 健康分析
    skill: llm-generate
    model: openai/gpt-3.5-turbo  # 简单任务用轻量模型
    input:
      prompt: |
        分析以下服务器指标,判断健康状态(healthy/warning/critical):
        
        CPU: {{steps.metrics.cpu.output}}
        内存: {{steps.metrics.memory.output}}
        磁盘: {{steps.metrics.disk.output}}
        负载: {{steps.metrics.load.output}}
        
        输出JSON格式:{"status": "...", "issues": [], "suggestions": []}

  # 步骤3:根据严重程度处理
  - id: alert
    name: 告警处理
    switch: "{{steps.analyze.output.status}}"
    
    cases:
      critical:
        - skill: telegram-send
          priority: high
          input:
            message: |
              🚨 服务器紧急告警
              
              主机:{{secrets.SERVER_HOST}}
              状态:严重
              问题:{{steps.analyze.output.issues}}
              
              建议操作:{{steps.analyze.output.suggestions}}
              
        - skill: phone-call  # 紧急时打电话
          input:
            number: "{{secrets.ADMIN_PHONE}}"
            message: "服务器严重告警,请立即查看"
            
      warning:
        - skill: telegram-send
          input:
            message: |
              ⚠️ 服务器预警
              
              主机:{{secrets.SERVER_HOST}}
              问题:{{steps.analyze.output.issues}}
              
      healthy:
        - skill: log-store  # 只记录,不打扰
          input:
            level: info
            message: "健康检查通过"

自动修复扩展

对于常见问题,可以让 AI 尝试自动修复:

- id: autoFix
  name: 自动修复
  condition: "{{steps.analyze.output.autoFixable == true}}"
  
  skill: ssh-exec
  input:
    host: "{{secrets.SERVER_HOST}}"
    command: "{{steps.analyze.output.fixCommand}}"
    
  onSuccess:
    - skill: notify
      input:
        message: "✅ 自动修复成功:{{steps.analyze.output.issue}}"
        
  onFailure:
    - skill: notify
      input:
        message: "❌ 自动修复失败,需要人工介入"

进阶:条件触发与分支逻辑

复合条件触发

trigger:
  type: composite
  conditions:
    # 条件1:每周五下午5点
    - type: cron
      schedule: "0 17 * * 5"
      
    # 条件2:且代码仓库有提交
    - type: webhook
      endpoint: "/github/push"
      filter: "refs/heads/main"
      
    # 条件3:且不在假期
    - type: calendar
      calendar: "work-calendar"
      condition: "not holiday"

分支与循环

steps:
  # 批量处理多个文件
  - id: batchProcess
    name: 批量处理
    forEach: "{{trigger.files}}"
    steps:
      - skill: image-resize
        input:
          file: "{{item}}"
          width: 800
          
      - skill: upload
        condition: "{{steps.batchProcess.image-resize.status == 'success'}}"
        input:
          file: "{{steps.batchProcess.image-resize.output}}"
          
  # 重试逻辑
  - id: fetchWithRetry
    name: 带重试的获取
    retry:
      maxAttempts: 3
      delay: "5s"
      backoff: exponential  # 指数退避
      
    skill: http-request
    input:
      url: "https://api.example.com/data"
      timeout: "30s"

人工审批节点

- id: approval
  name: 等待审批
  skill: human-in-the-loop
  input:
    assignee: "manager@company.com"
    message: "请审批发布生产环境"
    timeout: "2h"  # 2小时超时
    
  onTimeout:
    - skill: notify
      input:
        message: "审批超时,任务取消"

与其他自动化工具对比

场景 OpenClaw GitHub Actions Jenkins n8n
定时任务 ✅ 原生支持 ⚠️ 需配置 ✅ 支持 ✅ 支持
AI 决策 ✅ 内置 ❌ 需外部API ❌ 需插件 ⚠️ 需配置
自然语言编排 ✅ 支持
本地文件操作 ✅ 直接访问 ⚠️ 需 self-hosted ⚠️ 需配置
消息推送 ✅ 多通道 ⚠️ 需配置 ⚠️ 需插件
复杂度 中等 中等
学习曲线 平缓 陡峭 陡峭 中等

OpenClaw 最适合:

  • 需要 AI 参与决策的工作流
  • 本地环境自动化(文件、系统操作)
  • 个人/小团队快速搭建
  • 对数据隐私有要求

故障排查与调试技巧

1. 本地调试模式

# 单步执行工作流
openclaw workflow run morning-briefing --dry-run

# 查看详细日志
openclaw workflow run morning-briefing --verbose

# 从指定步骤恢复
openclaw workflow run morning-briefing --resume-from=step2

2. 日志分析

# 在工作流中插入检查点
steps:
  - id: debug1
    name: 检查中间状态
    skill: log-store
    level: debug
    input:
      message: "中间数据:{{steps.previous.output|json}}"

3. 常见错误处理

错误 原因 解决方案
skill not found Skill 未安装 openclaw skill install xxx
timeout 步骤执行超时 增加 timeout: "60s" 配置
rate limit API 限流 添加 rateLimit 中间件
secret not found 密钥未配置 检查 .env 文件

4. 性能优化

# 并行执行独立步骤
steps:
  - parallelGroup:
      parallel: true
      steps:
        - skill: fetchA
        - skill: fetchB
        - skill: fetchC
        
# 缓存重复请求
- id: cachedStep
  skill: http-request
  cache:
    enabled: true
    ttl: "5m"  # 5分钟缓存

总结

OpenClaw 的工作流系统让自动化任务具备了智能决策能力

  • 自然语言编排:用描述代替代码
  • AI 中间件:每个步骤都可以调用 LLM 分析
  • 灵活触发:定时、事件、Webhook、文件监控
  • 本地优先:敏感操作不出本机

下一步建议:

  1. 从简单的定时任务开始(如每日早报)
  2. 逐步添加 AI 分析步骤
  3. 建立个人的自动化工作流库
  4. 分享你的 Skill 到社区

让 OpenClaw 成为你的数字生活管家!

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐