Skip to main content

OpenClaw 自动化工作流设计指南

·3737 words·8 mins

自动化工作流概念图


引言
#

自动化不是替代人力,而是解放人力。

在上一篇《OpenClaw 实战:打造零成本的本地 AI 工厂》中,我们展示了如何用 OpenClaw 搭建多设备协同的 AI 工厂。但这只是开始——真正的价值在于自动化工作流

本文将深入解析 OpenClaw 工作流的设计模式,从触发器、执行器到完整的工作流编排,包含 10+ 个实战案例和可复用的模板。


一、工作流核心概念
#

1.1 什么是工作流?
#

工作流 = 触发器 + 执行步骤 + 条件判断 + 输出

传统方式:

人工监控 → 手动执行 → 检查结果 → 处理异常

OpenClaw 工作流:

自动触发 → 执行步骤 → 条件判断 → 自动输出

1.2 核心组件
#

组件 作用 示例
触发器 启动工作流 定时、事件、API 调用
执行器 执行具体任务 脚本、API、命令
条件 控制流程分支 if/else、switch
变量 传递数据 输入参数、中间结果
输出 工作流结果 文件、消息、API 响应

1.3 工作流生命周期
#

触发 → 初始化 → 执行步骤 1 → 条件判断 → 执行步骤 2 → ... → 输出 → 清理

二、触发器设计
#

2.1 定时触发器
#

场景: 每天早上 9 点自动抓取热点并生成文章

# workflows/daily-content.yaml
name: 每日内容生成

triggers:
  - type: cron
    schedule: "0 9 * * *"  # 每天 9:00

steps:
  - name: 抓取 X 平台热点
    tool: x-search
    params:
      query: "AI agent"
      limit: 50
      output: /tmp/hot-topics.json
  
  - name: LLM 分析趋势
    tool: llm-infer
    params:
      prompt: "分析以下热点,提取 3 个主要趋势"
      input: /tmp/hot-topics.json
      output: /tmp/trend-analysis.md
  
  - name: 生成文章
    tool: llm-infer
    params:
      prompt: "根据趋势分析撰写 3000 字文章"
      input: /tmp/trend-analysis.md
      output: /var/www/ai.mylog.vip/content/posts/daily-$(date +%Y%m%d).md
  
  - name: 构建站点
    tool: shell
    command: "cd /var/www/ai.mylog.vip && hugo --minify"
  
  - name: 发送通知
    tool: feishu-notify
    params:
      message: "今日文章已发布"
      url: "https://ai.mylog.vip/posts/daily-$(date +%Y%m%d)/"

Cron 表达式参考:

表达式 含义
0 9 * * * 每天 9:00
0 */2 * * * 每 2 小时
0 9 * * 1-5 工作日 9:00
0 0 * * 0 每周日 0:00
0 0 1 * * 每月 1 日 0:00

2.2 事件触发器
#

场景: 文件变化时自动处理

# workflows/file-watcher.yaml
name: 文件监控处理

triggers:
  - type: event
    event: file.created
    path: /var/www/ai.mylog.vip/content/posts/*.md

steps:
  - name: 检查文件
    tool: shell
    command: "head -20 {{event.file}}"
  
  - name: 提取 front matter
    tool: yaml-parse
    params:
      file: "{{event.file}}"
  
  - name: 生成封面图
    tool: text-to-image
    params:
      prompt: "{{frontmatter.description}}"
      output: "/var/www/ai.mylog.vip/static/images/cover-{{frontmatter.title}}.jpg"
  
  - name: 构建站点
    tool: shell
    command: "cd /var/www/ai.mylog.vip && hugo --minify"

2.3 API 触发器
#

场景: 接收外部系统调用

# workflows/webhook.yaml
name: Webhook 处理

triggers:
  - type: webhook
    path: /api/v1/deploy
    method: POST
    auth: bearer_token

steps:
  - name: 验证请求
    tool: auth-verify
    params:
      token: "{{request.headers.Authorization}}"
  
  - name: 拉取代码
    tool: shell
    command: "cd /var/www/ai.mylog.vip && git pull"
  
  - name: 构建站点
    tool: shell
    command: "hugo --minify"
  
  - name: 返回结果
    tool: response
    params:
      status: 200
      body: '{"status": "success", "message": "部署完成"}'

2.4 手动触发器
#

场景: 需要人工确认的操作

# workflows/manual-deploy.yaml
name: 手动部署

triggers:
  - type: manual
    confirm: true
    message: "确认要部署到生产环境吗?"

steps:
  - name: 备份当前版本
    tool: shell
    command: "tar -czf /backup/prod-$(date +%Y%m%d-%H%M%S).tar.gz /var/www/ai.mylog.vip/public/"
  
  - name: 部署
    tool: shell
    command: "./deploy.sh production"
  
  - name: 验证
    tool: http-check
    params:
      url: "https://ai.mylog.vip"
      expected_status: 200

三、执行器设计
#

3.1 Shell 执行器
#

场景: 执行系统命令

steps:
  - name: 清理缓存
    tool: shell
    command: "rm -rf /var/www/ai.mylog.vip/public/*"
    timeout: 30
  
  - name: 构建站点
    tool: shell
    command: "cd /var/www/ai.mylog.vip && hugo --minify"
    timeout: 300
    env:
      HUGO_ENV: production
  
  - name: 同步到 CDN
    tool: shell
    command: "aws s3 sync /var/www/ai.mylog.vip/public/ s3://my-cdn-bucket/"
    timeout: 600

最佳实践:

  • 设置超时时间,避免无限等待
  • 使用环境变量传递敏感信息
  • 记录输出日志便于调试

3.2 HTTP 执行器
#

场景: 调用外部 API

steps:
  - name: 发送飞书消息
    tool: http
    params:
      url: "https://open.feishu.cn/open-apis/bot/v2/hook/xxx"
      method: POST
      headers:
        Content-Type: application/json
      body:
        msg_type: text
        content:
          text: "文章已发布:{{output.url}}"
  
  - name: 提交到搜索引擎
    tool: http
    params:
      url: "http://data.zz.baidu.com/urls?site=ai.mylog.vip&token=xxx"
      method: POST
      body:
        urls:
          - "{{output.url}}"

3.3 AI 执行器
#

场景: 调用本地 LLM

steps:
  - name: 文章摘要
    tool: llm-infer
    params:
      model: llama3.1:70b
      prompt: "总结以下文章,生成 200 字摘要"
      input: "{{article.content}}"
      max_tokens: 500
  
  - name: 关键词提取
    tool: llm-infer
    params:
      model: llama3.1:8b
      prompt: "提取 5 个关键词,用逗号分隔"
      input: "{{article.content}}"
  
  - name: 封面图提示词
    tool: llm-infer
    params:
      model: llama3.1:8b
      prompt: "根据文章内容生成图片生成提示词(英文)"
      input: "{{article.content}}"
      output: /tmp/image-prompt.txt
  
  - name: 生成封面图
    tool: text-to-image
    params:
      prompt_file: /tmp/image-prompt.txt
      output: "/var/www/ai.mylog.vip/static/images/cover-{{article.id}}.jpg"

3.4 数据库执行器
#

场景: 读写数据库

steps:
  - name: 查询文章统计
    tool: mysql
    params:
      host: localhost
      database: blog
      query: "SELECT COUNT(*) as count FROM posts WHERE date >= DATE_SUB(NOW(), INTERVAL 7 DAY)"
  
  - name: 更新缓存
    tool: redis
    params:
      host: localhost
      command: "SET weekly_stats {{query.count}} EX 3600"

四、条件判断与流程控制
#

4.1 If/Else 条件
#

场景: 根据条件执行不同分支

steps:
  - name: 检查磁盘空间
    tool: shell
    command: "df -h / | awk 'NR==2 {print $5}' | sed 's/%//'"
    output: disk_usage
  
  - name: 条件判断
    if: "{{disk_usage}} > 80"
    then:
      - name: 清理日志
        tool: shell
        command: "find /var/log -name '*.log' -mtime +7 -delete"
      
      - name: 发送告警
        tool: feishu-notify
        params:
          message: "⚠️ 磁盘空间不足:{{disk_usage}}%"
    else:
      - name: 记录正常
        tool: log
        params:
          message: "磁盘空间正常:{{disk_usage}}%"

4.2 Switch 多分支
#

场景: 根据文章类型执行不同处理

steps:
  - name: 获取文章分类
    tool: yaml-parse
    params:
      file: "{{article.path}}"
      field: categories[0]
    output: category
  
  - name: 分类处理
    switch: "{{category}}"
    cases:
      "AI 运维":
        - name: 添加 AI 标签
          tool: tag-add
          params:
            tags: ["AI", "运维", "自动化"]
      
      "技术教程":
        - name: 添加教程标签
          tool: tag-add
          params:
            tags: ["教程", "实战", "代码"]
      
      "工具实践":
        - name: 添加工具标签
          tool: tag-add
          params:
            tags: ["工具", "评测", "推荐"]
      
      default:
        - name: 添加通用标签
          tool: tag-add
          params:
            tags: ["博客", "文章"]

4.3 循环处理
#

场景: 批量处理多个文件

steps:
  - name: 获取文章列表
    tool: shell
    command: "find /var/www/ai.mylog.vip/content/posts/ -name '*.md' -type f"
    output: files
  
  - name: 批量处理
    foreach: "{{files}}"
    steps:
      - name: 检查 front matter
        tool: yaml-validate
        params:
          file: "{{item}}"
          required_fields: ["title", "date", "draft"]
      
      - name: 修复缺失字段
        if: "{{validation.missing}}"
        then:
          - name: 添加默认值
            tool: yaml-update
            params:
              file: "{{item}}"
              updates:
                draft: "false"
                author: "森哥"
      
      - name: 生成摘要
        tool: llm-infer
        params:
          prompt: "总结以下文章"
          input: "{{item}}"

五、错误处理与重试
#

5.1 错误捕获
#

steps:
  - name: 发布文章
    tool: hugo-deploy
    params:
      output: /var/www/ai.mylog.vip/
    
    on_error:
      - name: 记录错误
        tool: log
        params:
          level: error
          message: "发布失败:{{error.message}}"
      
      - name: 发送告警
        tool: feishu-notify
        params:
          message: "❌ 发布失败:{{error.message}}"
      
      - name: 回滚
        tool: shell
        command: "git checkout -- /var/www/ai.mylog.vip/content/posts/"

5.2 重试机制
#

steps:
  - name: 调用外部 API
    tool: http
    params:
      url: "https://api.example.com/endpoint"
      method: POST
    retry:
      max_attempts: 3
      delay: 5  # 秒
      backoff: exponential  # 指数退避
    on_error:
      - name: 记录失败
        tool: log
        params:
          message: "API 调用失败,已重试 {{retry.attempts}} 次"

5.3 超时处理
#

steps:
  - name: 长时间任务
    tool: shell
    command: "./long-running-task.sh"
    timeout: 300  # 5 分钟超时
    on_timeout:
      - name: 清理资源
        tool: shell
        command: "pkill -f long-running-task"
      
      - name: 记录超时
        tool: log
        params:
          message: "任务超时,已终止"

六、实战案例
#

6.1 案例 1:每日热点文章生成
#

# workflows/daily-hot-article.yaml
name: 每日热点文章

triggers:
  - type: cron
    schedule: "0 8 * * *"  # 每天 8:00

steps:
  - name: 抓取 X 平台热点
    tool: x-search
    params:
      queries:
        - "AI agent"
        - "local AI"
        - "OpenClaw"
      limit: 100
      days: 1
    output: hot_topics
  
  - name: 分析趋势
    tool: llm-infer
    params:
      prompt: |
        分析以下热点推文,提取:
        1. 3 个主要趋势
        2. 5 个关键词
        3. 1 个文章主题建议
      input: "{{hot_topics}}"
    output: analysis
  
  - name: 撰写文章
    tool: llm-infer
    params:
      prompt: |
        根据分析结果撰写一篇 3000 字技术文章
        要求:
        - 有具体案例
        - 有代码示例
        - 有数据支撑
      input: "{{analysis}}"
      max_tokens: 4000
    output: draft.md
  
  - name: 生成封面图
    tool: text-to-image
    params:
      prompt: "{{analysis.keywords[0]}}, tech illustration"
      output: /var/www/ai.mylog.vip/static/images/cover-daily-$(date +%Y%m%d).jpg
  
  - name: 发布文章
    tool: shell
    command: |
      mv draft.md /var/www/ai.mylog.vip/content/posts/daily-$(date +%Y%m%d).md
      cd /var/www/ai.mylog.vip && hugo --minify
    output: url
  
  - name: 发送通知
    tool: feishu-notify
    params:
      message: "📝 每日热点文章已发布"
      url: "{{url}}"

6.2 案例 2:网站健康监控
#

# workflows/health-check.yaml
name: 网站健康监控

triggers:
  - type: cron
    schedule: "*/15 * * * *"  # 每 15 分钟

steps:
  - name: 检查网站可用性
    tool: http-check
    params:
      url: "https://ai.mylog.vip"
      expected_status: 200
      timeout: 10
    output: site_status
  
  - name: 检查 SSL 证书
    tool: ssl-check
    params:
      domain: "ai.mylog.vip"
      warn_days: 30
    output: ssl_status
  
  - name: 检查磁盘空间
    tool: shell
    command: "df -h / | awk 'NR==2 {print $5}' | sed 's/%//'"
    output: disk_usage
  
  - name: 条件告警
    if: "{{site_status.failed}} or {{ssl_status.warn}} or {{disk_usage}} > 80"
    then:
      - name: 发送告警
        tool: feishu-notify
        params:
          message: |
            ⚠️ 网站健康告警
            
            网站状态:{{site_status}}
            SSL 证书:{{ssl_status}}
            磁盘使用:{{disk_usage}}%

6.3 案例 3:自动备份
#

# workflows/auto-backup.yaml
name: 自动备份

triggers:
  - type: cron
    schedule: "0 3 * * *"  # 每天 3:00

steps:
  - name: 备份博客内容
    tool: shell
    command: |
      tar -czf /backup/blog-$(date +%Y%m%d).tar.gz \
        /var/www/ai.mylog.vip/content/ \
        /var/www/ai.mylog.vip/hugo.toml \
        /var/www/ai.mylog.vip/layouts/
  
  - name: 备份 OpenClaw 配置
    tool: shell
    command: |
      tar -czf /backup/openclaw-$(date +%Y%m%d).tar.gz \
        /root/.openclaw/workspace/MEMORY.md \
        /root/.openclaw/workspace/memory/ \
        /root/.openclaw/openclaw.json
  
  - name: 清理旧备份(保留 30 天)
    tool: shell
    command: "find /backup/ -name '*.tar.gz' -mtime +30 -delete"
  
  - name: 上传到云存储(可选)
    tool: rclone
    params:
      source: /backup/
      destination: "remote:backup/"
  
  - name: 记录备份结果
    tool: log
    params:
      message: "备份完成:blog-$(date +%Y%m%d).tar.gz, openclaw-$(date +%Y%m%d).tar.gz"

6.4 案例 4:SEO 自动提交
#

# workflows/seo-submit.yaml
name: SEO 自动提交

triggers:
  - type: event
    event: article.published

steps:
  - name: 提交到百度
    tool: http
    params:
      url: "http://data.zz.baidu.com/urls?site=ai.mylog.vip&token=xxx"
      method: POST
      body:
        urls:
          - "{{article.url}}"
  
  - name: 提交到 Bing
    tool: http
    params:
      url: "https://www.bing.com/indexingnow/index"
      method: POST
      headers:
        Content-Type: application/json
      body:
        url: "{{article.url}}"
  
  - name: 提交到 Google
    tool: http
    params:
      url: "https://indexing.googleapis.com/v3/urlNotifications:publish"
      method: POST
      headers:
        Authorization: "Bearer {{google_token}}"
      body:
        url: "{{article.url}}"
        type: URL_UPDATED
  
  - name: 记录提交结果
    tool: log
    params:
      message: "SEO 提交完成:{{article.url}}"

6.5 案例 5:社交媒体同步
#

# workflows/social-sync.yaml
name: 社交媒体同步

triggers:
  - type: event
    event: article.published

steps:
  - name: 生成推文
    tool: llm-infer
    params:
      prompt: |
        根据文章内容生成一条推文(280 字以内)
        要求:
        - 有吸引力的开头
        - 包含 2-3 个要点
        - 添加 2-3 个相关标签
      input: "{{article.content}}"
    output: tweet
  
  - name: 发布到 X 平台
    tool: x-post
    params:
      content: "{{tweet}}"
      link: "{{article.url}}"
  
  - name: 生成小红书文案
    tool: llm-infer
    params:
      prompt: |
        根据文章内容生成小红书文案
        要求:
        - 有 emoji
        - 分段清晰
        - 添加热门标签
      input: "{{article.content}}"
    output: xiaohongshu
  
  - name: 发布到飞书
    tool: feishu-notify
    params:
      message: |
        📝 新文章发布
        
        {{article.title}}
        
        {{article.description}}
        
        阅读:{{article.url}}

七、最佳实践
#

7.1 工作流设计原则
#

原则 说明 示例
单一职责 每个工作流只做一件事 发布工作流不负责备份
幂等性 多次执行结果相同 先检查是否存在再创建
可恢复 失败后可从中断点继续 记录执行进度
可观测 有完整的日志和监控 记录每个步骤的输入输出
可配置 参数外部化 使用环境变量

7.2 变量命名规范
#

# 好的命名
variables:
  article_title: "文章标题"
  publish_url: "发布 URL"
  backup_path: "/backup/xxx"

# 避免的命名
variables:
  a: "xxx"  # 无意义
  data: "xxx"  # 太泛
  temp: "xxx"  # 不明确

7.3 日志记录
#

steps:
  - name: 发布文章
    tool: hugo-deploy
    log:
      level: info
      message: "开始发布文章:{{article.title}}"
      on_success: "发布成功:{{output.url}}"
      on_error: "发布失败:{{error.message}}"
      on_timeout: "发布超时,已执行 {{duration}} 秒"

7.4 资源清理
#

steps:
  - name: 处理任务
    tool: process
    params:
      command: "./process.sh"
  
  - name: 清理临时文件
    tool: shell
    command: "rm -rf /tmp/process-*"
    always: true  # 无论成功失败都执行
  
  - name: 释放锁
    tool: lock-release
    params:
      name: "process.lock"
    always: true

八、调试技巧
#

8.1 干运行(Dry Run)
#

# 不实际执行,只查看计划
openclaw workflow run daily-content.yaml --dry-run

8.2 单步执行
#

# 执行单个步骤
openclaw workflow run daily-content.yaml --step 2

8.3 日志查看
#

# 实时查看日志
openclaw workflow logs daily-content --follow

# 查看历史日志
openclaw workflow logs daily-content --limit 50

8.4 变量调试
#

steps:
  - name: 调试变量
    tool: log
    params:
      message: |
        变量调试:
        article_title: {{article.title}}
        publish_url: {{output.url}}
        timestamp: {{now}}

总结
#

OpenClaw 工作流的核心价值:

  1. 自动化 - 减少重复劳动
  2. 可靠性 - 错误处理和重试机制
  3. 可扩展 - 模块化设计,易于复用
  4. 可观测 - 完整的日志和监控

行动建议:

  1. 从简单工作流开始(如定时备份)
  2. 逐步增加复杂度
  3. 建立工作流模板库
  4. 定期审查和优化

参考资料
#

  1. OpenClaw 工作流文档
  2. Cron 表达式生成器
  3. YAML 语法指南
  4. 前文:OpenClaw 实战

作者: 森哥
发布日期: 2026-03-15
分类: AI 运维 / 技术教程
标签: OpenClaw, 自动化,工作流,脚本,最佳实践