Skip to content

OpenClaw 自动化工作流

构建自动化流程,提升工作效率。


🎯 自动化场景

常见场景

场景频率自动化前自动化后
每日早报每天手动整理 30 分钟自动发送 0 分钟
数据备份每天手动备份 15 分钟自动备份 0 分钟
周报生成每周手动编写 2 小时自动生成 5 分钟
客户跟进实时手动回复 10 分钟自动回复 0 分钟

⏰ 定时任务配置

Cron 配置

基本语法

cron
# 分 时 日 月 周 命令
* * * * * command

常用示例

cron
# 每天早上 8 点
0 8 * * * /path/to/script.sh

# 每周一早上 9 点
0 9 * * 1 /path/to/script.sh

# 每小时执行
0 * * * * /path/to/script.sh

# 每 5 分钟执行
*/5 * * * * /path/to/script.sh

OpenClaw Cron 配置

json
{
  "cron": {
    "jobs": [
      {
        "name": "每日早报",
        "schedule": {
          "kind": "cron",
          "expr": "0 8 * * *",
          "tz": "Asia/Shanghai"
        },
        "payload": {
          "kind": "agentTurn",
          "message": "生成今日早报,包括天气、新闻、日程"
        },
        "delivery": {
          "mode": "announce"
        }
      }
    ]
  }
}

📧 邮件自动化

自动回复配置

javascript
// 邮件自动回复脚本
const imap = require('imap');
const openclaw = require('openclaw-sdk');

const config = {
  user: 'your@email.com',
  password: 'your-password',
  host: 'imap.email.com',
  port: 993,
  tls: true
};

const imapClient = new imap(config);

imapClient.on('mail', async (num) => {
  // 获取新邮件
  const email = await fetchEmail(num);
  
  // AI 生成回复
  const reply = await openclaw.generate({
    prompt: `回复这封邮件:${email.body}`,
    tone: 'professional'
  });
  
  // 发送回复
  await sendReply(email.from, reply);
});

imapClient.connect();

邮件分类规则

javascript
const rules = {
  '工作': ['项目', '会议', '报告'],
  '账单': ['发票', '付款', '账单'],
  '订阅': ['订阅', '续费', '会员'],
  '通知': ['通知', '提醒', '更新']
};

function classifyEmail(subject) {
  for (const [category, keywords] of Object.entries(rules)) {
    if (keywords.some(k => subject.includes(k))) {
      return category;
    }
  }
  return '其他';
}

📊 数据自动化

自动数据备份

bash
#!/bin/bash
# backup.sh - 自动备份脚本

DATE=$(date +%Y%m%d)
BACKUP_DIR="/backups"
SOURCE_DIR="/home/pao/.openclaw"

# 创建备份
tar -czf ${BACKUP_DIR}/openclaw-${DATE}.tar.gz ${SOURCE_DIR}

# 删除 30 天前的备份
find ${BACKUP_DIR} -name "openclaw-*.tar.gz" -mtime +30 -delete

# 上传到云存储
aws s3 cp ${BACKUP_DIR}/openclaw-${DATE}.tar.gz s3://bucket/backups/

echo "备份完成:${DATE}"

配置定时执行

bash
# 添加到 crontab
crontab -e

# 每天凌晨 2 点执行
0 2 * * * /home/pao/scripts/backup.sh

📝 文档自动化

自动生成周报

javascript
// weekly-report.js
const openclaw = require('openclaw-sdk');

async function generateWeeklyReport() {
  // 收集本周数据
  const tasks = await getCompletedTasks();
  const meetings = await getMeetings();
  const issues = await getIssues();
  
  // AI 生成报告
  const report = await openclaw.generate({
    prompt: `
生成周报,包括:
1. 本周完成的工作
2. 参加的会议
3. 解决的问题
4. 下周计划

数据:
- 任务:${JSON.stringify(tasks)}
- 会议:${JSON.stringify(meetings)}
- 问题:${JSON.stringify(issues)}
    `,
    format: 'markdown'
  });
  
  // 发送报告
  await sendEmail('team@company.com', '周报', report);
  
  return report;
}

// 每周五下午 5 点执行
cron.schedule('0 17 * * 5', generateWeeklyReport);

💬 消息自动化

自动回复配置

javascript
// auto-reply.js
const openclaw = require('openclaw-sdk');

// 配置自动回复规则
const replyRules = {
  '你好': '你好!有什么可以帮助你的?',
  '价格': '我们的产品定价如下:...',
  '发货': '工作日 16:00 前下单,当天发货',
  '退换': '支持 7 天无理由退换'
};

async function handleMessage(message) {
  const text = message.text.toLowerCase();
  
  // 检查是否有匹配规则
  for (const [keyword, reply] of Object.entries(replyRules)) {
    if (text.includes(keyword)) {
      return reply;
    }
  }
  
  // 没有匹配,使用 AI 生成回复
  const aiReply = await openclaw.generate({
    prompt: `回复用户问题:${message.text}`,
    context: message.history
  });
  
  return aiReply;
}

群消息监控

javascript
// group-monitor.js
const openclaw = require('openclaw-sdk');

// 监控群消息
openclaw.on('group-message', async (message) => {
  const { group, user, text } = message;
  
  // 检查是否@机器人
  if (text.includes('@机器人')) {
    const reply = await handleMention(text, message);
    await openclaw.send(group, reply);
  }
  
  // 检查关键词
  if (isImportant(text)) {
    await notifyAdmin(message);
  }
});

function isImportant(text) {
  const importantKeywords = ['紧急', '重要', '帮助', '问题'];
  return importantKeywords.some(k => text.includes(k));
}

🔄 工作流引擎

定义工作流

yaml
# workflow.yaml
name: 客户咨询处理
trigger:
  type: message
  conditions:
    - contains: "咨询"
    
steps:
  - name: 理解问题
    type: ai
    config:
      task: "分析客户问题,提取关键信息"
      
  - name: 查询知识库
    type: search
    config:
      source: "knowledge-base"
      query: "${step1.keywords}"
      
  - name: 生成回复
    type: ai
    config:
      task: "根据查询结果生成回复"
      context: "${step2.results}"
      
  - name: 发送回复
    type: send
    config:
      target: "${message.user}"
      content: "${step3.response}"

执行工作流

javascript
const workflow = require('./workflow.yaml');

openclaw.on('message', async (message) => {
  // 检查是否匹配工作流触发条件
  if (matchWorkflow(message, workflow.trigger)) {
    // 执行工作流
    const result = await executeWorkflow(workflow, message);
    console.log('工作流完成:', result);
  }
});

📈 自动化监控

监控指标

javascript
// monitoring.js
const metrics = {
  messagesProcessed: 0,
  autoRepliesSent: 0,
  errorsCount: 0,
  avgResponseTime: 0
};

// 更新指标
function updateMetrics(event) {
  metrics.messagesProcessed++;
  if (event.type === 'auto-reply') {
    metrics.autoRepliesSent++;
  }
  if (event.type === 'error') {
    metrics.errorsCount++;
  }
}

// 发送监控报告
cron.schedule('0 9 * * 1', async () => {
  const report = generateReport(metrics);
  await sendToAdmin(report);
});

告警配置

javascript
// alerts.js
const thresholds = {
  errorRate: 0.05,      // 错误率超过 5%
  responseTime: 5000,   // 响应时间超过 5 秒
  queueSize: 100        // 队列超过 100
};

function checkAlerts(metrics) {
  if (metrics.errorRate > thresholds.errorRate) {
    sendAlert('错误率过高');
  }
  
  if (metrics.responseTime > thresholds.responseTime) {
    sendAlert('响应时间过长');
  }
}

📋 自动化检查清单

配置检查

  • [ ] 定时任务已配置
  • [ ] 自动化规则已定义
  • [ ] 错误处理已配置
  • [ ] 监控告警已设置

运行检查

  • [ ] 脚本可执行
  • [ ] 权限正确
  • [ ] 依赖已安装
  • [ ] 日志正常

维护检查

  • [ ] 定期清理日志
  • [ ] 更新自动化规则
  • [ ] 检查执行结果
  • [ ] 优化性能

提示

从简单自动化开始,逐步扩展复杂流程!

🟢🐉 泡泡龙

Released under the MIT License.