OpenClaw 实战案例完全指南
发布日期: 2026-03-24
分类: OpenClaw 教程
标签: OpenClaw, AI, 教程, 实战案例
简介
理论不如实践。本文通过 10 个真实世界的 OpenClaw 实战案例,展示如何利用 AI 代理自动化日常工作流,提升效率 10 倍以上。
每个案例都包含完整的代码示例和配置说明,你可以直接复用或修改适配自己的需求。
案例 1:自动日报生成
场景: 每天自动收集工作数据,生成结构化日报
实现步骤:
1. 创建数据收集脚本
bash
#!/bin/bash
# collect-daily-data.sh
# 收集 Git 提交
git log --since="24 hours ago" --pretty=format:"- %s" > /tmp/commits.txt
# 收集完成的任务
cat ~/.openclaw/workspace/memory/$(date +%Y-%m-%d).md >> /tmp/tasks.txt
# 收集邮件(如果有)
fetchmail -a 2>/dev/null | head -20 >> /tmp/emails.txt2. 配置定时任务
javascript
await cron({
action: "add",
job: {
name: "每日数据收集",
schedule: {
kind: "cron",
expr: "0 18 * * *" // 每天 18:00
},
payload: {
kind: "systemEvent",
text: "收集今日工作数据"
},
sessionTarget: "main"
}
});3. 生成日报
javascript
// 在心跳任务中生成
const commits = await exec("cat /tmp/commits.txt");
const tasks = await read("memory/" + today + ".md");
const report = `
# 日报 - ${today}
## 代码提交
${commits}
## 完成任务
${tasks}
## 明日计划
- [ ]
`;
await write(`memory/daily-report-${today}.md`, report);案例 2:智能邮件分类
场景: 自动分类 incoming 邮件,标记优先级
实现:
javascript
async function classifyEmail(email) {
const subject = email.subject.toLowerCase();
const from = email.from;
// 规则分类
if (subject.includes('urgent') || subject.includes('asap')) {
return { priority: 'high', category: '紧急' };
}
if (from.includes('boss@') || from.includes('client@')) {
return { priority: 'high', category: '重要' };
}
if (subject.includes('newsletter') || subject.includes('promo')) {
return { priority: 'low', category: '订阅' };
}
// AI 辅助分类
const aiResult = await sessions_spawn({
task: `分类这封邮件:${subject}`,
runtime: "subagent",
timeoutSeconds: 30
});
return aiResult;
}
// 定期检查邮箱
await cron({
action: "add",
job: {
name: "邮件分类",
schedule: { kind: "every", everyMs: 3600000 }, // 每小时
payload: { kind: "systemEvent", text: "检查新邮件" },
sessionTarget: "isolated"
}
});案例 3:代码审查助手
场景: 自动审查 Git PR,提供改进建议
实现:
javascript
async function reviewPR(prNumber) {
// 获取变更文件
const changedFiles = await exec(
`git diff --name-only HEAD~${prNumber}`
);
const reviews = [];
for (const file of changedFiles.split('\n')) {
if (!file.endsWith('.js') && !file.endsWith('.py')) {
continue;
}
// 读取文件内容
const content = await read(file);
// 使用子代理审查
const review = await sessions_spawn({
task: `审查代码文件 ${file},找出:
1. 潜在 bug
2. 性能问题
3. 代码风格问题
4. 安全漏洞
文件内容:
${content}`,
runtime: "subagent",
timeoutSeconds: 120
});
reviews.push({ file, review });
}
// 生成审查报告
const report = reviews.map(r =>
`## ${r.file}\n${r.review}`
).join('\n');
await write(`reviews/pr-${prNumber}.md`, report);
return report;
}案例 4:网站内容监控
场景: 监控竞争对手网站变化,自动通知
实现:
javascript
async function monitorWebsite(url, lastContent) {
const currentContent = await web_fetch({ url });
if (currentContent !== lastContent) {
// 内容发生变化
const diff = await exec(
`diff <(echo "${lastContent}") <(echo "${currentContent}")`
);
// 发送通知
await message({
action: "send",
target: "user:ou_xxx",
message: `🚨 网站更新提醒\n\n${url}\n\n变化:\n${diff}`
});
// 保存新版本
await write(
`monitors/${url.replace(/\//g, '_')}.txt`,
currentContent
);
}
}
// 每 30 分钟检查一次
await cron({
action: "add",
job: {
name: "网站监控",
schedule: { kind: "every", everyMs: 1800000 },
payload: { kind: "systemEvent", text: "检查网站更新" },
sessionTarget: "isolated"
}
});案例 5:自动化测试报告
场景: 运行测试套件,生成可视化报告
实现:
javascript
async function generateTestReport() {
// 运行测试
const testResult = await exec(
"npm test -- --reporter=json",
{ timeout: 300 }
);
const results = JSON.parse(testResult);
// 分析结果
const summary = {
total: results.tests.length,
passed: results.tests.filter(t => t.status === 'passed').length,
failed: results.tests.filter(t => t.status === 'failed').length,
skipped: results.tests.filter(t => t.status === 'skipped').length
};
// 生成报告
const report = `
# 测试报告 - ${new Date().toISOString()}
## 概览
- ✅ 通过:${summary.passed}
- ❌ 失败:${summary.failed}
- ⏭️ 跳过:${summary.skipped}
- 📊 总计:${summary.total}
## 失败用例
${results.tests.filter(t => t.status === 'failed').map(t => `
### ${t.title}
- 错误:${t.error}
- 文件:${t.file}
`).join('\n')}
## 建议
${summary.failed === 0 ? '🎉 所有测试通过!' : '⚠️ 请修复失败的测试用例'}
`;
await write(`reports/test-${Date.now()}.md`, report);
// 如果有失败,发送通知
if (summary.failed > 0) {
await sessions_send({
label: "dev-team",
message: `❌ ${summary.failed} 个测试失败,请查看报告`
});
}
}案例 6:智能文档整理
场景: 自动分类整理下载的文件
实现:
javascript
async function organizeDownloads() {
const files = await exec("ls ~/Downloads/");
for (const file of files.split('\n')) {
if (!file) continue;
const ext = file.split('.').pop().toLowerCase();
let targetDir;
// 根据扩展名分类
switch(ext) {
case 'pdf': targetDir = 'Documents/PDFs'; break;
case 'jpg': case 'png': targetDir = 'Pictures'; break;
case 'mp3': case 'wav': targetDir = 'Music'; break;
case 'mp4': case 'avi': targetDir = 'Videos'; break;
case 'zip': case 'tar': targetDir = 'Archives'; break;
default: targetDir = 'Documents/Misc';
}
// 移动文件
await exec(`mkdir -p ~/ ${targetDir}`);
await exec(`mv ~/Downloads/${file} ~/${targetDir}/`);
// 记录日志
await append('memory/file-organize.log',
`${new Date().toISOString()} Moved ${file} to ${targetDir}\n`
);
}
}案例 7:社交媒体自动发布
场景: 定时发布内容到多个平台
实现:
javascript
async function schedulePost(content, platforms, scheduleTime) {
await cron({
action: "add",
job: {
name: `发布到 ${platforms.join(',')}`,
schedule: {
kind: "at",
at: scheduleTime.toISOString()
},
payload: {
kind: "agentTurn",
message: `发布内容到 ${platforms.join(',')}:\n\n${content}`
},
sessionTarget: "isolated"
}
});
return `已安排发布:${scheduleTime}`;
}
// 使用示例
await schedulePost(
"🚀 新教程发布:OpenClaw 实战指南\n\nhttps://aitimes.net/guide/...",
['twitter', 'linkedin', 'feishu'],
new Date('2026-03-25T09:00:00+08:00')
);案例 8:系统健康检查
场景: 定期检查系统状态,预警潜在问题
实现:
javascript
async function healthCheck() {
const checks = {};
// CPU 使用率
checks.cpu = await exec("top -bn1 | grep 'Cpu(s)'");
// 内存使用率
checks.memory = await exec("free -h");
// 磁盘空间
checks.disk = await exec("df -h /");
// 服务状态
checks.services = await exec("systemctl is-active openclaw nginx");
// 分析结果
const alerts = [];
if (checks.cpu.includes('90')) {
alerts.push('⚠️ CPU 使用率过高');
}
if (checks.disk.split('\n')[1].split(/\s+/)[4].replace('%', '') > 90) {
alerts.push('⚠️ 磁盘空间不足');
}
// 生成报告
const report = `
# 系统健康检查 - ${new Date().toISOString()}
${alerts.length > 0 ? '## 警告\n' + alerts.join('\n') : '✅ 一切正常'}
## 详情
\`\`\`
CPU: ${checks.cpu}
内存:${checks.memory}
磁盘:${checks.disk}
服务:${checks.services}
\`\`\`
`;
await write(`health/check-${Date.now()}.md`, report);
// 有警告时发送通知
if (alerts.length > 0) {
await message({
action: "send",
message: report
});
}
}案例 9:知识库自动更新
场景: 从多个来源抓取内容,更新知识库
实现:
javascript
async function updateKnowledgeBase() {
const sources = [
'https://news.ycombinator.com/',
'https://www.reddit.com/r/MachineLearning/',
'https://openclaw.ai/blog/'
];
for (const source of sources) {
const content = await web_fetch({ url: source });
// 提取关键信息
const summary = await sessions_spawn({
task: `从以下内容中提取 3-5 个重要信息点:\n\n${content}`,
runtime: "subagent",
timeoutSeconds: 60
});
// 添加到知识库
await append('knowledge-base/daily-updates.md', `
## ${new Date().toISOString()} - ${source}
${summary}
`);
}
}案例 10:智能待办管理
场景: 自动从对话中提取待办事项,跟踪完成情况
实现:
javascript
async function extractTodos(message) {
// 检测待办事项
const todoPattern = /(记得 | 需要 | 要 | 待办 |TODO|todo)[::]\s*(.+)/g;
const matches = [...message.matchAll(todoPattern)];
for (const match of matches) {
const todo = {
id: Date.now(),
content: match[2],
created: new Date().toISOString(),
status: 'pending'
};
// 添加到待办列表
await append('todos.md',
`- [ ] ${todo.content} #${todo.id}\n`
);
// 设置提醒
await cron({
action: "add",
job: {
name: `提醒:${todo.content}`,
schedule: {
kind: "every",
everyMs: 86400000 // 24 小时后
},
payload: {
kind: "systemEvent",
text: `提醒待办:${todo.content}`
},
sessionTarget: "main"
}
});
}
}最佳实践总结
1. 任务分解
- 大任务拆分为子代理执行
- 每个子任务设置合理超时
2. 错误处理
- 捕获异常并记录日志
- 失败时发送通知
3. 资源管理
- 定期清理临时文件
- 限制并发子代理数量
4. 安全考虑
- 敏感操作需要审批
- 凭证加密存储
相关资源
总结
通过这 10 个实战案例,你可以看到 OpenClaw 在自动化工作流中的强大能力。关键要点:
- ✅ 识别重复性任务,用自动化替代
- ✅ 合理使用子代理处理复杂任务
- ✅ 设置监控和通知机制
- ✅ 持续优化和改进工作流
开始构建你自己的自动化工作流吧!