跳到主要内容
OpenClaw 集成飞书机器人实战指南 | 极客日志
JavaScript Node.js AI
OpenClaw 集成飞书机器人实战指南 OpenClaw 集成飞书机器人实战指南涵盖应用创建、权限配置、环境搭建及插件启用流程。内容包含消息发送(文本/图片/卡片)、文档操作、多维表格管理及定时任务设置。同时提供安全实践、性能优化方案及常见问题排查指南,帮助开发者实现智能化办公自动化。
黑客 发布于 2026/4/5 更新于 2026/4/24 3 浏览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 用户)
wsl --list--verbose
wsl --update
wsl -d Ubuntu
方案 B:macOS/Linux 原生环境
node --version
npm --version
飞书应用创建与授权
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:messageTenant 必需 发送和接收群聊消息 im:message:send_as_botTenant 必需 以机器人身份发送消息 im:chatTenant 必需 创建和管理聊天会话 im:chat.members:readTenant 可选 读取群成员信息 docx:document:createUser 可选 创建飞书云文档 docx:document:readonlyUser 可选 读取飞书文档 wiki:space:readUser 可选 访问知识库空间 base:record:createUser 可选 向多维表格写入数据 calendar:calendar.event:createUser 可选 创建日程事件 contact:user.base:readonlyUser 可选 查询用户基础信息 drive:file:uploadUser 可选 上传文件到云空间
Tenant 级别权限可能需要管理员审批
User 级别权限通常由使用者自己授权即可
生产环境请遵循最小权限原则
Step 5: 发布应用并获取 access_token
方式一:测试版发布(开发阶段)
点击左侧 '发布' → '发布测试版'
选择可见范围为当前部门
发布后可在 '管理' → '密钥' 页面看到 access_token
方式二:正式版发布(生产环境)
提交代码审核
通过审核后发布正式版
正式版的 access_token 有效期更长且更稳定
Step 6: 邀请应用进群
在应用中获取机器人卡片 URL
将链接发到目标群组
群主/群成员点击加入
打开任意飞书群聊
点击右上角 "..." → "添加机器人"
搜索你的应用名称
点击加入
机器人出现在群成员列表中
可以正常@机器人并收到回复(稍后配置)
OpenClaw 环境搭建
安装方式对比 方式 适用场景 优点 缺点 全局安装 个人开发者 一次安装到处用 可能权限冲突 Docker 部署 团队协作 环境隔离干净 额外学习成本 GitHub Codespace 在线体验 零配置开箱即用 需要网络条件
方式一:全局安装(推荐)
npm install -g @openclaw/cli
openclaw --version
openclaw init
方式二:Docker 部署 # Dockerfile
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
EXPOSE 8765
CMD ["node", "dist/index.js"]
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
│ ├── client.ts
│ ├── 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
FEISHU_CONNECTION_MODE=websocket
FEISHU_LOG_LEVEL=debug
FEISHU_MESSAGE_DEBOUNCE_MS=300
FEISHU_RETRY_ATTEMPTS=3
启用飞书插件
方式一:通过 CLI 启用
openclaw plugins list
openclaw plugins enable feishu
openclaw plugins status feishu
方式二:手动编辑 config.json nano ~/.openclaw/config.json
{ "plugins" : { "entries" : { "qwen-portal-auth" : { "enabled" : true } , "feishu" : { "enabled" : true } } } }
pkill -f openclaw-gateway
openclaw gateway start
验证连接状态
openclaw gateway status | grep feishu
openclaw probe feishu
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 机器人!"
通过 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 "本周数据统计"
发送卡片消息 {
"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
追加内容到文档 <!-- 创建 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='进行中'"
[{"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 "❓"
🔄 定时任务与自动回复
创建周期性任务
0 9 * * * openclaw message --channel feishu --target oc_team_chat --template daily-summary
0 15 1 * * openclaw message --channel feishu --target oc_management --template weekly-report-reminder
openclaw cron import crontab.txt
openclaw cron list
配置自动回复规则 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 ) {
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
技能注册示例
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
📈 监控与调试
启用详细日志
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
性能指标收集 #!/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
curl -I https://api.feishu.cn/open-apis/auth/v3/version
sudo iptables -L | grep 443
sudo iptables -A OUTPUT -p tcp --dport 443 -j ACCEPT
sudo systemd-resolve --flush-caches
问题 2:认证失败 / Token 无效 Error : invalid_access_token
openclaw auth refresh --provider feishu
cat ~/.openclaw/credentials/feishu.json | jq '.app_id'
rm -rf ~/.openclaw/cache/feishu/*
openclaw cache clear
问题 3:消息发送被限流
飞书 API 有频率限制:单个账号每分钟最多 1000 次请求
批量发送时容易触发限流
const DELAY_PER_REQUEST = 100 ;
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 );
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
Error: permission_denied for doc_token =doc_xxx
openclaw auth reauthorize --provider feishu --scope docx
附录
附录 A: 完整权限对照表 Scope Type Description Read Write im:messageTenant 群聊消息 ✅ ✅ im:message.p2p_msgTenant 私聊消息 ✅ ✅ im:chatTenant 聊天会话管理 ✅ ✅ im:chat.membersTenant 群成员管理 ✅ ⚠️ docx:documentUser 云文档操作 ✅ ✅ wiki:spaceUser 知识库空间 ✅ ✅ base:recordUser 多维表格记录 ✅ ✅ calendar:calendar.eventUser 日历事件 ✅ ✅ drive:fileUser 云盘文件 ✅ ✅ contact:user.baseUser 用户基础信息 ✅ ❌
附录 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,如有变动请以官方文档为准。
相关免费在线工具 RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
Mermaid 预览与可视化编辑 基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
随机西班牙地址生成器 随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
Keycode 信息 查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
Escape 与 Native 编解码 JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
JavaScript / HTML 格式化 使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online