OpenClaw 集成飞书机器人实战指南
什么是 OpenClaw
OpenClaw 是一个开源的智能代理框架,支持以下核心能力:
- 本地部署 AI 能力:无需依赖云端服务,保护隐私
- 多通道消息支持:同时接入微信、Telegram、Discord、飞书等多个平台
- 智能任务编排:通过自然语言驱动复杂工作流程
- 可扩展的技能系统:自定义插件扩展功能边界
- 持久化记忆机制:让 AI 真正记住你的偏好和历史
核心架构
┌─────────────────────────────────────────────────────┐
│ OpenClaw Framework │
├─────────────────────────────────────────────────────┤
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Chat │ │ Email │ │ Calendar │ ... │
│ │ Plugin │ │ Plugin │ │ Plugin │ │
│ └──────────┘ └──────────┘ └──────────┘ │
├─────────────────────────────────────────────────────┤
│ Skill Marketplace │
│ (Feishu Docs, Drive, Wiki, Bitable, etc.) │
├─────────────────────────────────────────────────────┤
│ Memory & Context Management │
├─────────────────────────────────────────────────────┤
│ Model Providers Layer │
│ (Qwen, DeepSeek, Local LLMs via Ollama) │
└─────────────────────────────────────────────────────┘
特性对比
| 特性 | OpenClaw | 传统 bot 框架 |
|---|---|---|
| AI 原生设计 | ✅ | ❌ |
| 跨平台统一接口 | ✅ | ❌ |
| 本地模型支持 | ✅ | ⚠️ 部分支持 |
| 持久化上下文 | ✅ | ⚠️ 需手动实现 |
| 可视化技能市场 | ✅ | ❌ |
前期准备
硬件要求
- CPU:双核以上(建议使用四核)
- 内存:≥ 4GB RAM(AI 推理场景建议 8GB+)
- 磁盘:至少 10GB 可用空间
- 网络:稳定互联网连接(如需使用云端 API)
软件环境
方案 A:使用 WSL2(推荐 Windows 用户)
# 1. 确保 WSL2 已安装
wsl --list--verbose
# 2. 更新到最新内核
wsl --update
# 3. 启动 Ubuntu
wsl -d Ubuntu
方案 B:macOS/Linux 原生环境
# 确认 Node.js 版本 >= 20
node --version
# v22.22.0 ✓
# 确认 npm 版本 >= 10
npm --version
# 10.9.0 ✓
飞书应用创建与授权
Step 1: 登录飞书开发者平台
访问 飞书开放平台 → 点击 '企业自建应用' → '创建应用'。
Step 2: 填写应用基本信息
应用名称:OpenClaw Bot
图标:选择或上传一个 1024x1024 PNG
描述:我的智能 AI 助手,帮助你高效工作
可见范围:选择相应的部门或个人
Step 3: 获取关键凭证
创建成功后,进入应用详情页复制以下信息:
基本信息页
App ID: cli_xxxxxxxxxxxxxx
App Secret: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
⚠️ 安全提醒:App Secret 是敏感信息,请妥善保管,不要提交到公开的代码仓库!
保存方式(任选其一):
# 方式一:保存到环境变量文件
echo "FEISHU_APP_ID=cli_xxx" >> ~/.env.openclaw
echo "FEISHU_APP_SECRET=xxx-xxxx-xxxx-xxxx-xxxxxx" >> ~/.env.openclaw
chmod 600 ~/.env.openclaw
# 方式二:通过命令临时设置
export FEISHU_APP_ID=cli_xxx
export FEISHU_APP_SECRET=xxx-xxxx-xxxx-xxxx-xxxxxx
Step 4: 配置权限范围
在飞书应用后台左侧菜单找到 '管理' → '权限和应用' → '添加权限范围'。
| 权限标识 | 类型 | 必要度 | 用途说明 |
|---|---|---|---|
im:message | Tenant | 必需 | 发送和接收群聊消息 |
im:message:send_as_bot | Tenant | 必需 | 以机器人身份发送消息 |
im:chat | Tenant | 必需 | 创建和管理聊天会话 |
im:chat.members:read | Tenant | 可选 | 读取群成员信息 |
docx:document:create | User | 可选 | 创建飞书云文档 |
docx:document:readonly | User | 可选 | 读取飞书文档 |
wiki:space:read | User | 可选 | 访问知识库空间 |
base:record:create | User | 可选 | 向多维表格写入数据 |
calendar:calendar.event:create | User | 可选 | 创建日程事件 |
contact:user.base:readonly | User | 可选 | 查询用户基础信息 |
drive:file:upload | User | 可选 | 上传文件到云空间 |
注意:
- Tenant 级别权限可能需要管理员审批
- User 级别权限通常由使用者自己授权即可
- 生产环境请遵循最小权限原则
Step 5: 发布应用并获取 access_token
方式一:测试版发布(开发阶段)
- 点击左侧 '发布' → '发布测试版'
- 选择可见范围为当前部门
- 发布后可在 '管理' → '密钥' 页面看到
access_token
方式二:正式版发布(生产环境)
- 提交代码审核
- 通过审核后发布正式版
- 正式版的 access_token 有效期更长且更稳定
Step 6: 邀请应用进群
方法 A:通过链接邀请
- 在应用中获取机器人卡片 URL
- 将链接发到目标群组
- 群主/群成员点击加入
方法 B:直接拉群
- 打开任意飞书群聊
- 点击右上角 "..." → "添加机器人"
- 搜索你的应用名称
- 点击加入
验证成功标志:
- 机器人出现在群成员列表中
- 可以正常@机器人并收到回复(稍后配置)
OpenClaw 环境搭建
安装方式对比
| 方式 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
| 全局安装 | 个人开发者 | 一次安装到处用 | 可能权限冲突 |
| Docker 部署 | 团队协作 | 环境隔离干净 | 额外学习成本 |
| GitHub Codespace | 在线体验 | 零配置开箱即用 | 需要网络条件 |
方式一:全局安装(推荐)
# 1. 安装 OpenClaw CLI
npm install -g @openclaw/cli
# 2. 验证安装
openclaw --version
# 输出:2026.3.2
# 3. 初始化配置
openclaw init
方式二:Docker 部署
# Dockerfile
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
EXPOSE 8765
CMD ["node", "dist/index.js"]
# docker-compose.yml
version: '3.8'
services:
openclaw:
build: .
ports:
- "8765:8765"
environment:
- NODE_ENV=production
- FEISHU_APP_ID=${FEISHU_APP_ID}
- FEISHU_APP_SECRET=${FEISHU_APP_SECRET}
volumes:
- ./workspace:/app/workspace
- ./memory:/app/memory
# 启动服务
docker-compose up -d
# 查看日志
docker-compose logs -f openclaw
配置文件详解
生成后的 /root/.openclaw/config.json 核心字段说明:
{
"gateway": {
"port": 18789,
"mode": "local",
"bind": "loopback",
"auth": { "mode": "token", "token": "自动生成" }
},
"agents": {
"defaults": {
"model": { "primary": "deepseek/deepseek-chat" },
"workspace": "/root/.openclaw/workspace"
}
},
"plugins": {
"entries": { "feishu": { "enabled": true } }
}
}
飞书插件配置详解
插件架构解析
/root/.openclaw/extensions/feishu/
├── index.ts # 插件入口文件
├── src/
│ ├── channel.ts # 消息通道处理
│ ├── monitor.ts # WebSocket 监听
│ ├── client.ts # SDK 客户端封装
│ ├── send.ts # 发送消息逻辑
│ ├── reactions.ts # 表情回复功能
│ ├── mention.ts # @提及解析
│ ├── bitable/ # 多维表格相关
│ ├── docx/ # 文档操作
│ ├── drive/ # 云盘操作
│ └── wiki/ # 知识库操作
├── skills/ # 预置技能集
│ ├── feishu-doc/
│ ├── feishu-drive/
│ ├── feishu-perm/
│ └── feishu-wiki/
└── package.json
核心配置文件
创建 .env.openclaw 或使用以下方式配置:
# === 飞书基础配置 ===
FEISHU_APP_ID=cli_xxxxxxxxxxxxxx
FEISHU_APP_SECRET=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
# === 连接模式(二选一)===
# WebSocket 模式(实时双向通信)
FEISHU_CONNECTION_MODE=websocket
# Webhook 模式(需要公网回调地址)
# FEISHU_CONNECTION_MODE=webhook
# FEISHU_WEBHOOK_URL=https://your-domain.com/api/webhook/feishu
# === 高级选项 ===
FEISHU_LOG_LEVEL=debug # debug/info/warn/error
FEISHU_MESSAGE_DEBOUNCE_MS=300 # 消息防抖间隔
FEISHU_RETRY_ATTEMPTS=3 # 失败重试次数
启用飞书插件
方式一:通过 CLI 启用
# 列出所有可用插件
openclaw plugins list
# 启用飞书插件
openclaw plugins enable feishu
# 查看插件状态
openclaw plugins status feishu
# 输出:✅ enabled (v2.1.0)
方式二:手动编辑 config.json
nano ~/.openclaw/config.json
添加以下内容到 plugins.entries:
{"plugins":{"entries":{"qwen-portal-auth":{"enabled":true},"feishu":{"enabled":true}}}}
重启服务使配置生效:
pkill -f openclaw-gateway
openclaw gateway start
验证连接状态
# 检查插件是否正常加载
openclaw gateway status | grep feishu
# Expected: [Plugin loaded] feishu -> OK
# 测试飞书连通性
openclaw probe feishu
# Expected: Connection successful, bot_id=oc_xxx
# 查看最近的消息记录
openclaw messages --channel feishu --limit 10
如果看到如下输出,说明一切正常:
[INFO] Feishu plugin initialized
[INFO] Connected to IM Cloud Server
[INFO] Bot info: id=oc_f91fe..., name=OpenClaw Bot
[INFO] Listening for incoming messages...
核心功能实战
📤 发送文本消息
基础用法
# 单条消息发送
openclaw message \
--channel feishu \
--target oc_group_chat_id_here \
--message "你好,我是 OpenClaw 机器人!"
# 响应输出:
# {
# "messageId": "om_x100b543...",
# "chatId": "oc_f91fe152...",
# "timestamp": 1710072345
# }
通过 Python 脚本调用
import subprocess
import json
def send_feishu_message(chat_id, content):
result = subprocess.run(
['openclaw', 'message', '--channel', 'feishu', '--target', chat_id, '--message', content, '--output', 'json'],
capture_output=True, text=True
)
return json.loads(result.stdout)
# 使用示例
response = send_feishu_message("oc_abc123xyz", "今天的日报已完成,请及时查收!📊")
print(f"消息已发送:{response['messageId']}")
🖼️ 发送富媒体消息
发送图片
# 发送本地图片
openclaw message \
--channel feishu \
--target oc_target_id \
--media /path/to/image.png \
--caption "项目架构图"
# 发送网络图片
openclaw message \
--channel feishu \
--target oc_target_id \
--media "https://example.com/chart.png" \
--caption "本周数据统计"
发送卡片消息
创建 card.json 文件:
{
"type": "text card",
"header": { "title": "📅 会议提醒", "subtitle": "重要项目评审会" },
"hero": { "type": "image", "sub_type": "cover", "url": "https://cdn.example.com/meeting.jpg" },
"content": [{ "section": { "text": { "content": "时间:今天 14:00-16:00\n地点:会议室 A\n参会人:产品部全体" } } }]
}
# 发送卡片
openclaw message \
--channel feishu \
--target oc_target_id \
--card-file card.json
🎯 @提及与回复功能
@特定人员
# 在群聊中@某人
openclaw message \
--channel feishu \
--target oc_group_id \
--message "这个问题需要跟进一下" \
--mention-user ou_user_open_id
@所有人(仅群主可用)
openclaw message \
--channel feishu \
--target oc_group_id \
--message "紧急通知:服务器维护将于今晚 0 点开始" \
--mention-all
回复指定消息
openclaw message \
--channel feishu \
--target oc_group_id \
--reply-to om_original_message_id \
--message "@user 好的,这个需求我已经理解了"
📑 文档与知识库操作
创建云文档
# 新建空白文档
openclaw doc create \
--channel feishu \
--title "2026 年 Q1 工作计划" \
--folder-token folder_token_optional
读取文档内容
# 获取文档全文
openclaw doc read \
--channel feishu \
--token doc_token_from_url
# 结果示例
# Document: 2026 年 Q1 工作计划
# Blocks: 15
# Content:
# ## 一、季度目标
# - 完成产品 V3.0 上线
# - 用户数突破 100 万
# ...
追加内容到文档
<!-- 创建 update.txt -->
## 新增模块
- [x] 数据分析看板
- [ ] 报表导出功能
- [ ] 第三方集成
openclaw doc append \
--channel feishu \
--token doc_xxx \
--file update.txt
知识库节点管理
# 查看所有知识库空间
openclaw wiki spaces --channel feishu
# 创建新页面
openclaw wiki create \
--channel feishu \
--space-id space_xxx \
--title "技术选型指南" \
--content-type docx
📊 多维表格(Bitable)操作
查询数据
# 列出所有记录
openclaw bitable query \
--channel feishu \
--app-token app_xxx \
--table-id table_xxx \
--filter "Status='进行中'"
# 输出格式:JSON
[{"id":"rec_abc", "Name":"用户中心重构", "Priority":"高", "Assignee":["张三", "李四"]}]
写入数据
openclaw bitable insert \
--channel feishu \
--app-token app_xxx \
--table-id table_xxx \
--fields '{"Task":"编写技术文档","Owner":"王五","DueDate":"2026-03-20"}'
🎭 表情回复功能
# 给消息点赞
openclaw reaction add \
--channel feishu \
--message-id om_msg_id \
--emoji "👍"
# 取消表情
openclaw reaction remove \
--channel feishu \
--message-id om_msg_id \
--emoji "😄"
# 批量操作
openclaw reaction batch \
--channel feishu \
--message-id om_msg_id \
--add "👍,🎉" \
--remove "❓"
🔄 定时任务与自动回复
创建周期性任务
创建 crontab.txt:
# 每天早上 9 点发送昨日总结
0 9 * * * openclaw message --channel feishu --target oc_team_chat --template daily-summary
# 每周一下午 3 点提醒周报
0 15 1 * * openclaw message --channel feishu --target oc_management --template weekly-report-reminder
# 导入定时任务
openclaw cron import crontab.txt
# 查看任务列表
openclaw cron list
配置自动回复规则
创建 rules.yaml:
rules:
- trigger: "@me 天气"
response: "正在查询今日天气...{{weather(city)}}"
- trigger: "帮我定个会议"
action: calendar.create
fields:
title: "团队例会"
duration: 60
- trigger: "周报"
response_template: |
📊 **本周工作总结**
已完成: {{tasks.completed}}
进行中: {{tasks.in_progress}}
# 启用规则引擎
openclaw rules load rules.yaml
进阶技巧与最佳实践
🔒 安全最佳实践
1. 凭证管理
# ❌ 错误做法:硬编码在代码中
const appId = "cli_xxx"; // DANGER!
# ✅ 正确做法:环境变量 + 加密存储
npm install -g keytar
# 加密存储敏感信息
keytar.setPassword("openclaw", "feishu_secret", "xxx-xxxx-xxxx");
# 使用时读取
const secret = keytar.getPasswordSync("openclaw", "feishu_secret");
2. API 速率限制
// 使用指数退避策略
async function sendWithRetry(message, maxAttempts = 5) {
let attempt = 0;
while (attempt < maxAttempts) {
try {
await sendMessage(message);
return { success: true };
} catch (error) {
if (error.code === 'RATE_LIMITED') {
const delay = Math.pow(2, attempt) * 1000;
console.log(`Rate limited, retrying in ${delay}ms`);
await sleep(delay);
attempt++;
} else {
throw error;
}
}
}
return { success: false, error: 'Max retries exceeded' };
}
3. 权限最小化
始终遵循原则:
- 只申请必要的权限范围
- 定期审查并撤销不再使用的权限
- 生产环境与测试环境分离
🚀 性能优化
1. 消息批处理
from openclaw import FeishuClient
client = FeishuClient()
# ❌ 低效:逐个发送
for member in members:
client.send_message(member.chat_id, "通知内容")
# ✅ 高效:批量发送
client.batch_send({
'messages': [
{'chat_id': m.id, 'content': '通知内容'}
for m in members
]
})
2. 缓存策略
// 缓存常用数据避免重复请求
class CacheManager {
constructor(ttl = 300000) { // 5 分钟
this.cache = new Map();
this.ttl = ttl;
}
get(key) {
const entry = this.cache.get(key);
if (!entry || Date.now() > entry.expiry) {
this.cache.delete(key);
return null;
}
return entry.value;
}
set(key, value) {
this.cache.set(key, { value, expiry: Date.now() + this.ttl });
}
}
// 使用示例
const cache = new CacheManager();
let groupInfo = cache.get('group_' + chatId);
if (!groupInfo) {
groupInfo = await client.getChatInfo(chatId);
cache.set('group_' + chatId, groupInfo);
}
📱 消息模板设计
通用模板结构
interface MessageTemplate {
type: 'text' | 'card' | 'image' | 'file';
priority: 'normal' | 'urgent';
fallback?: string;
render(context: Record<string, any>): Promise<MessageContent>;
}
// 示例:每日待办提醒模板
export class DailyTodoTemplate implements MessageTemplate {
async render(ctx) {
const today = formatDate(new Date());
const tasks = await fetchTasksForUser(ctx.userId, today);
if (tasks.length === 0) {
return {
type: 'text',
content: '✨ 今日无待办事项,享受惬意的一天吧!☕️'
};
}
return {
type: 'card',
data: {
header: { title: `📅 ${today} 的待办` },
sections: tasks.map(t => ({ content: `[${t.priority}] ${t.title}` }))
}
};
}
}
🧩 自定义技能开发
技能目录结构
skills/my-custom-skill/
├── SKILL.md # 技能说明文档
├── handler.js # 主处理逻辑
├── tools/
│ ├── helper.js # 辅助函数
│ └── formatter.js # 格式化工具
└── tests/
└── handler.test.js # 单元测试
技能注册示例
// handler.js
module.exports = {
name: 'meeting-organizer',
description: '智能会议组织者',
triggers: ['安排会议', '开会', 'schedule meeting'],
async execute(message, context) {
const { time, participants, topic } = parseMeetingIntent(message);
// 查找空闲时间段
const availableSlots = await findAvailableSlots(participants, time.range);
// 创建会议邀请
const meeting = await scheduleMeeting({
topic,
startTime: availableSlots[0],
attendees: participants,
agenda: message.rawText
});
return formatSuccessMessage(meeting);
}
};
注册到新技能:
openclaw skill link ./skills/my-custom-skill
openclaw skill list
# 显示:✅ meeting-organizer (active)
📈 监控与调试
启用详细日志
# 设置日志级别
export OPENCLAW_LOG_LEVEL=debug
# 定向开启某模块日志
export LOGGING_MODULES="feishu,monitor,sender"
常见日志分析
# ✅ 正常运行
[INFO] [feishu] Message received from oc_xxx
[DEBUG] [parser] Extracted intent: check_status
[INFO] [executor] Running task: status_report
[INFO] [sender] Response sent successfully
# ⚠️ 警告信息
[WARN] [rate-limit] Approaching quota limit (85%)
[WARN] [cache] Cache miss rate high: 45%
# ❌ 错误信息
[ERROR] [auth] Access token expired, refreshing...
[ERROR] [network] Request timeout after 30s
性能指标收集
创建监控脚本 monitor.sh:
#!/bin/bash
echo "=== OpenClaw Feishu Monitor ==="
echo "Timestamp: $(date)"
# 消息统计
openclaw stats --channel feishu --since "24h ago"
# 响应时间
ping -c 5 api.feishu.cn
# 资源使用
ps aux | grep openclaw | awk '{print $3, $4}'
# 队列长度
openclaw queue status
运行监控:
chmod +x monitor.sh
./monitor.sh > logs/health-check-$(date +%Y%m%d).log
常见问题排查
问题 1:无法连接到飞书服务器
症状:
Error: Connection refused at api.feishu.cn:443
解决方案:
# 1. 检查网络连接
curl -I https://api.feishu.cn/open-apis/auth/v3/version
# 预期返回 HTTP/2 200
# 2. 检查防火墙
sudo iptables -L | grep 443
# 如有拦截,放行端口
sudo iptables -A OUTPUT -p tcp --dport 443 -j ACCEPT
# 3. 重置 DNS 缓存
sudo systemd-resolve --flush-caches
问题 2:认证失败 / Token 无效
症状:
Error: invalid_access_token
解决步骤:
# 1. 重新获取 token
openclaw auth refresh --provider feishu
# 2. 检查凭证是否正确
cat ~/.openclaw/credentials/feishu.json | jq '.app_id'
# 3. 清除过期缓存
rm -rf ~/.openclaw/cache/feishu/*
openclaw cache clear
问题 3:消息发送被限流
原因分析:
- 飞书 API 有频率限制:单个账号每分钟最多 1000 次请求
- 批量发送时容易触发限流
缓解策略:
// 添加请求间隔
const DELAY_PER_REQUEST = 100; // ms
async function sendMessageBatch(messages) {
for (const msg of messages) {
await sendSingleMessage(msg);
await sleep(DELAY_PER_REQUEST);
}
}
// 或使用并发控制
const pLimit = require('p-limit');
const limit = pLimit(5); // 最多 5 个并发
Promise.all(messages.map(msg => limit(() => sendSingleMessage(msg))));
问题 4:@提及无法触发响应
排查清单:
[ ] 确认机器人已在群内
[ ] 确认权限包含 im:message.group_at_msg:readonly
[ ] 检查 webhook 是否配置正确
[ ] 查看日志中是否有 mention 事件捕获
# 调试@提及
openclaw debug mention-test \
--chat-id oc_target \
--trigger-pattern "@me (.*)"
问题 5:WebSocket 连接频繁断开
根本原因: 网络不稳定或心跳超时
优化配置:
{"plugins":{"feishu":{"websocket":{"heartbeat_interval_ms":30000,"reconnect_delay_base_ms":5000,"max_reconnect_attempts":10}}}}
问题 6:无法读取/写入文档
权限检查:
# 查看当前应用的权限范围
openclaw scope list --provider feishu
# 应该包含 ✅ docx:document:readonly
# ✅ docx:document:write_only
常见错误修复:
Error: permission_denied for doc_token=doc_xxx
# 解决方法:
# 1. 确认机器人已被授予文档访问权
# 2. 在文档中设置共享权限
# 3. 刷新 OAuth 授权
openclaw auth reauthorize --provider feishu --scope docx
附录
附录 A: 完整权限对照表
| Scope | Type | Description | Read | Write |
|---|---|---|---|---|
im:message | Tenant | 群聊消息 | ✅ | ✅ |
im:message.p2p_msg | Tenant | 私聊消息 | ✅ | ✅ |
im:chat | Tenant | 聊天会话管理 | ✅ | ✅ |
im:chat.members | Tenant | 群成员管理 | ✅ | ⚠️ |
docx:document | User | 云文档操作 | ✅ | ✅ |
wiki:space | User | 知识库空间 | ✅ | ✅ |
base:record | User | 多维表格记录 | ✅ | ✅ |
calendar:calendar.event | User | 日历事件 | ✅ | ✅ |
drive:file | User | 云盘文件 | ✅ | ✅ |
contact:user.base | User | 用户基础信息 | ✅ | ❌ |
附录 B: 常用命令速查手册
# ========== 认证与配置 ==========
openclaw init # 初始化配置
openclaw auth login --provider feishu # 登录飞书
openclaw config show # 查看当前配置
# ========== 消息管理 ==========
openclaw message --help # 查看消息命令帮助
openclaw message send --to @all "Hello world"
openclaw message reply --id msg_xxx "Got it"
openclaw message history --count 50 # 查看历史消息
# ========== 文档操作 ==========
openclaw doc create --title "New Doc"
openclaw doc read --token doc_xxx
openclaw doc update --token doc_xxx --content "Updates..."
openclaw doc delete --token doc_xxx
# ========== 插件管理 ==========
openclaw plugins list # 列出所有插件
openclaw plugins enable feishu # 启用飞书插件
openclaw plugins disable feishu # 禁用飞书插件
openclaw plugins update # 更新插件到最新版本
# ========== 诊断工具 ==========
openclaw debug probe # 检测服务连通性
openclaw debug dump # 导出调试信息
openclaw version # 查看版本信息
本文最后更新于 2026-03-11,如有变动请以官方文档为准。
参考资源:
