下载地址
https://www.zhengdianxue.com/wp-content/uploads/skills/user_1edca653--feishu-v2.zip将提示词发送给你的 AI 安装该 skills
请根据 https://skillhub.cn/install/skillhub.md,安装 @user_1edca653/feishu-v2。将生成的内容创建为飞书云文档,授予接收者编辑权限,并发送文档链接到飞书。当用户想要把内容保存到飞书文档、创建飞书云文档、或导出为飞书格式时使用此技能。
阅读全文 (展开查看完整说明)
概述
功能说明
这个技能可以将生成的内容自动创建为飞书云文档,自动授予接收者编辑/管理权限,并发送文档链接到飞书。
使用前提
在使用此技能之前,你需要:
1. 创建飞书应用
- 访问 飞书开放平台
- 创建企业自建应用
- 在「凭证与基础信息」页面获取:
APP_ID(app_id)APP_SECRET(app_secret)
2. 配置应用权限
在「权限管理」中添加以下权限:
文档权限:
docs:doc– 文档基础能力docs:doc:readonly– 查看文档drive:drive– 云文档基础能力drive:file– 文件操作drive:permission– 文档权限管理(新增,用于授予编辑权限)
消息权限(必需):
im:message– 消息基础能力im:message:send_as_bot– 以应用身份发消息
多维表格权限(如需):
bitable:app– 多维表格基础能力bitable:app:readonly– 查看多维表格
3. 获取接收消息的用户信息
需要提供以下任一信息来发送消息和授予权限:
- 飞书邮箱(推荐,最简单)
- 飞书 Open ID
- 飞书 User ID
重要: 建议使用邮箱方式,更简单可靠
4. 发布应用并获取授权
- 配置好权限后,提交应用审核
- 审核通过后发布应用
- 在飞书管理后台启用应用
使用方法
使用 HTTP API(推荐)
import requests
import json
import os
from datetime import datetime
class FeishuHTTPClient:
def __init__(self, app_id, app_secret):
self.app_id = app_id
self.app_secret = app_secret
self.base_url = "https://open.feishu.cn/open-apis"
self.tenant_access_token = None
def get_tenant_access_token(self):
"""获取 tenant_access_token"""
url = f"{self.base_url}/auth/v3/tenant_access_token/internal"
headers = {"Content-Type": "application/json"}
data = {
"app_id": self.app_id,
"app_secret": self.app_secret
}
print("🔑 正在获取访问令牌...")
response = requests.post(url, headers=headers, json=data)
result = response.json()
if result.get("code") == 0:
self.tenant_access_token = result.get("tenant_access_token")
print("✅ 访问令牌获取成功")
return self.tenant_access_token
else:
raise Exception(f"获取 token 失败: {result}")
def create_document(self, title):
"""创建文档"""
if not self.tenant_access_token:
self.get_tenant_access_token()
print(f"📝 正在创建文档: {title}")
url = f"{self.base_url}/docx/v1/documents"
headers = {
"Authorization": f"Bearer {self.tenant_access_token}",
"Content-Type": "application/json"
}
data = {
"title": title
}
response = requests.post(url, headers=headers, json=data)
result = response.json()
if result.get("code") == 0:
document = result.get("data", {}).get("document", {})
print(f"✅ 文档已创建,ID: {document.get('document_id')}")
return document.get("document_id"), document.get("title")
else:
raise Exception(f"创建文档失败: {result}")
def add_content(self, document_id, content):
"""向文档添加内容"""
if not self.tenant_access_token:
self.get_tenant_access_token()
print("📄 正在添加文档内容...")
# 构建内容块
children = []
lines = content.split('n')
for line in lines:
line = line.strip()
if not line:
continue
# 判断是否为标题
if line.startswith('### '):
children.append({
"block_type": 4, # Heading3
"heading3": {
"elements": [{"text_run": {"content": line[4:]}}]
}
})
elif line.startswith('## '):
children.append({
"block_type": 3, # Heading2
"heading2": {
"elements": [{"text_run": {"content": line[3:]}}]
}
})
elif line.startswith('# '):
children.append({
"block_type": 2, # Heading1
"heading1": {
"elements": [{"text_run": {"content": line[2:]}}]
}
})
else:
# 普通文本
children.append({
"block_type": 2, # Text
"text": {
"elements": [{"text_run": {"content": line}}]
}
})
# 批量创建 blocks
data = {
"children": children,
"index": 0
}
url = f"{self.base_url}/docx/v1/documents/{document_id}/blocks/{document_id}/children/batch_create"
headers = {
"Authorization": f"Bearer {self.tenant_access_token}",
"Content-Type": "application/json"
}
response = requests.post(url, headers=headers, json=data)
result = response.json()
if result.get("code") == 0:
print("✅ 内容添加完成")
else:
print(f"⚠️ 添加内容时出现警告: {result.get('msg')}")
return result
def grant_document_permission(self, document_token, email, perm="edit", user_open_id=None, user_id=None):
"""
授予文档权限(完整版 - 多种方法尝试)
参数:
document_token: 文档 token(即 document_id)
email: 用户邮箱
perm: 权限类型,可选值:view, edit, full_access
user_open_id: 用户Open ID(可选)
user_id: 用户ID(可选)
注意:
- 应用创建的文档属于应用,需要特殊方式授权
- 会尝试3种方法:转移所有者、更新权限设置、添加协作者
"""
if not self.tenant_access_token:
self.get_tenant_access_token()
print(f"🔐 尝试授予 '{perm}' 权限给: {email}")
headers = {
"Authorization": f"Bearer {self.tenant_access_token}",
"Content-Type": "application/json"
}
# 方法1: 转移所有者(如果有user_open_id或user_id)
if user_open_id or user_id:
print(f"n方法1: 尝试转移文档所有者...")
owner_id = user_open_id or user_id
id_type = "open_id" if user_open_id else "user_id"
transfer_endpoints = [
f"/drive/v1/files/{document_token}/transfer_owner",
f"/drive/v1/permissions/{document_token}/transfer_owner",
]
for endpoint in transfer_endpoints:
url = f"{self.base_url}{endpoint}"
data = {
"token": document_token,
"type": "file",
"new_owner_id": owner_id,
"new_owner_id_type": id_type
}
try:
response = requests.put(url, headers=headers, json=data)
result = response.json()
if result.get("code") == 0:
print(f"✅ 所有者转移成功!")
return True
except:
continue
# 方法2: 更新权限设置(设置为组织内可编辑)
print(f"n方法2: 尝试更新权限设置...")
permission_endpoints = [
f"/drive/v1/files/{document_token}/permissions",
f"/drive/v1/permissions/{document_token}",
]
for endpoint in permission_endpoints:
url = f"{self.base_url}{endpoint}"
data = {
"permission_public": {
"link_share_entity": {
"external_access": False,
"security": 2 if perm == "edit" else 1
}
}
}
try:
response = requests.patch(url, headers=headers, json=data)
result = response.json()
if result.get("code") == 0:
print(f"✅ 权限设置更新成功!")
return True
except:
continue
# 方法3: 添加协作者
print(f"n方法3: 尝试添加协作者...")
url = f"{self.base_url}/drive/v1/permissions/{document_token}/members"
attempts = [
{"member_type": "openid", "member_id_type": "email", "member_id": email, "perm": perm},
{"member_type": "openid", "member_id_type": "email", "member_id": email, "member_permission": perm},
]
for i, data in enumerate(attempts, 1):
try:
response = requests.post(url, headers=headers, json=data)
result = response.json()
if result.get("code") == 0:
print(f"✅ 协作者添加成功!")
return True
except:
continue
# 如果所有方法都失败
print(f"n⚠️ 自动权限授予失败")
print(f"💡 请按以下步骤手动授予权限:")
print(f" 1. 在飞书中打开文档")
print(f" 2. 点击右上角「分享」按钮")
print(f" 3. 选择「获取分享链接」")
print(f" 4. 设置为「组织内获得链接的人可编辑」")
print(f" 5. 复制链接发给自己")
return False
def send_message(self, email, document_url):
"""
发送纯文本消息(仅包含文档链接)
参数:
email: 接收者邮箱
document_url: 文档链接
"""
if not self.tenant_access_token:
self.get_tenant_access_token()
print(f"📬 正在发送文档链接...")
url = f"{self.base_url}/im/v1/messages?receive_id_type=email"
headers = {
"Authorization": f"Bearer {self.tenant_access_token}",
"Content-Type": "application/json"
}
# 简单的纯文本消息,只包含文档链接
text_content = document_url
data = {
"receive_id": email,
"msg_type": "text",
"content": json.dumps({"text": text_content})
}
response = requests.post(url, headers=headers, json=data)
result = response.json()
if result.get("code") == 0:
print("✅ 文档链接发送成功")
return True
else:
print(f"❌ 消息发送失败: {result.get('msg')}")
return False
def create_feishu_doc(title, content, email, perm="full_access", user_open_id=None, user_id=None):
"""
创建飞书文档的便捷函数
参数:
title: 文档标题
content: 文档内容
email: 接收者邮箱
perm: 权限类型,可选值:
- "view": 仅查看
- "edit": 可编辑
- "full_access": 可管理(默认)
user_open_id: 用户Open ID(可选,用于转移所有者)
user_id: 用户ID(可选,用于转移所有者)
"""
# 从环境变量获取配置
APP_ID = os.environ.get('FEISHU_APP_ID')
APP_SECRET = os.environ.get('FEISHU_APP_SECRET')
if not APP_ID or not APP_SECRET:
raise Exception("请设置环境变量 FEISHU_APP_ID 和 FEISHU_APP_SECRET")
# 创建客户端
client = FeishuHTTPClient(APP_ID, APP_SECRET)
try:
# 1. 创建文档
document_id, doc_title = client.create_document(title)
document_url = f"https://feishu.cn/docx/{document_id}"
# 2. 添加内容
client.add_content(document_id, content)
# 3. 授予权限(自动执行)- 尝试多种方法
client.grant_document_permission(document_id, email, perm, user_open_id, user_id)
# 4. 发送文档链接
client.send_message(email, document_url)
print("n" + "="*60)
print("🎉 文档创建成功!")
print("="*60)
print(f"📄 文档标题: {doc_title}")
print(f"🔗 文档链接: {document_url}")
print(f"📧 发送到: {email}")
print(f"✅ 已尝试授予 '{perm}' 权限")
print("="*60)
return document_url
except Exception as e:
print(f"n❌ 操作失败: {str(e)}")
raise
# 使用示例
if __name__ == "__main__":
# 配置
os.environ['FEISHU_APP_ID'] = 'your_app_id_here'
os.environ['FEISHU_APP_SECRET'] = 'your_app_secret_here'
# 文档信息
today = datetime.now().strftime("%Y年%m月%d日")
title = f"今日待办事项 - {today}"
content = f"""# {title}
## 工作任务
- 完成项目报告
- 回复客户邮件
## 个人事项
- 健身锻炼
- 阅读学习
---
创建时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}"""
# 接收者邮箱
email = "user@example.com"
# 示例1: 使用默认权限(full_access - 可管理)
create_feishu_doc(title, content, email)
# 示例2: 指定可编辑权限 + 提供Open ID(推荐)
# create_feishu_doc(title, content, email, perm="edit",
# user_open_id="ou_xxxxxxx")
# 示例3: 使用user_id
# create_feishu_doc(title, content, email, perm="full_access",
# user_id="user_id_here")配置环境变量
为了安全地使用应用凭证,建议配置环境变量:
macOS/Linux:
# 编辑 ~/.zshrc 或 ~/.bash_profile
export FEISHU_APP_ID="your_app_id_here"
export FEISHU_APP_SECRET="your_app_secret_here"
# 使配置生效
source ~/.zshrc # 或 source ~/.bash_profileWindows:
# 临时设置(当前会话有效)
$env:FEISHU_APP_ID="your_app_id_here"
$env:FEISHU_APP_SECRET="your_app_secret_here"
# 永久设置(系统环境变量)
[Environment]::SetEnvironmentVariable("FEISHU_APP_ID", "your_app_id_here", "User")
[Environment]::SetEnvironmentVariable("FEISHU_APP_SECRET", "your_app_secret_here", "User")使用场景
- 保存生成的内容:当你生成了一份报告、文档或总结时,可以直接创建为飞书文档
- 自动授权:文档创建后自动授予接收者编辑权限,无需手动设置
- 即时通知:发送纯文本文档链接到飞书,简洁高效
- 团队协作:接收者可以直接编辑文档,进行协作
调用示例
当用户说:
- "把这些内容创建为飞书文档"
- "保存到飞书云文档"
- "生成一个飞书文档"
Claude 将会:
- 生成或整理需要保存的内容
- 调用飞书 API 创建文档
- 自动授予接收者编辑权限
- 发送文档链接到飞书(纯文本)
注意事项
- 权限配置:确保应用已配置所需的权限(特别是
drive:permission和drive:file权限) - 应用发布:应用需要发布后才能正常使用
- 邮箱格式:使用邮箱方式时,确保邮箱是有效的飞书企业邮箱
- 应用文档所有权:重要!应用创建的文档所有权属于应用,存放在「应用云空间」中
- 权限自动授予:系统会尝试3种方法自动授予权限:
- 方法1:转移文档所有者(需要提供
user_open_id或user_id) - 方法2:更新权限设置为「组织内获得链接的人可编辑」
- 方法3:添加协作者权限
- 方法1:转移文档所有者(需要提供
- 手动设置权限:如果自动授权失败,需要手动在飞书中设置:
- 打开文档 → 点击右上角「分享」→ 选择「获取分享链接」
- 设置为「组织内获得链接的人可编辑」→ 复制链接发给自己
- 权限类型:默认授予
full_access(可管理)权限,可以在调用时修改为edit(可编辑)或view(仅查看) - 消息格式:发送的是纯文本链接,不包含卡片样式
常见问题
Q: 如何获取文件夹 token?
A: 在飞书云文档中打开目标文件夹,URL 中的最后一部分就是 folder_token。例如:https://feishu.cn/drive/folder/fldcnxxxxxx 中的 fldcnxxxxxx
Q: 权限授予失败怎么办?
A: 应用创建的文档需要特殊处理,请检查:
- 应用是否有
drive:permission和drive:file权限 - 是否提供了
user_open_id或user_id(推荐) - 如果自动授权失败,请手动设置:
- 在飞书中打开文档
- 点击右上角「分享」→「获取分享链接」
- 设置为「组织内获得链接的人可编辑」
- 复制链接发给自己
Q: 为什么使用邮箱而不是 open_id?
A: 邮箱方式更简单可靠,避免了 open_id 跨应用的问题。只要邮箱是有效的飞书企业邮箱,就可以正常接收消息和权限。
Q: 可以授予其他权限类型吗?
A: 可以,修改 grant_document_permission 方法中的 perm 参数:
view– 仅查看edit– 可编辑full_access– 可管理(默认)
Q: 支持哪些内容格式?
A: 支持纯文本、Markdown 格式(标题、列表等)
参考资源
官方文档:
SDK 和工具: