@clawhub-tc1993-de571c7dcc
Complete automated development pipeline for one-person companies. Use when a user provides a simple app idea and wants a fully automated development process...
---
name: auto-dev-pipeline
description: Complete automated development pipeline for one-person companies. Use when a user provides a simple app idea and wants a fully automated development process from requirements to tested code. This skill coordinates prd-skill, dev-skill, and qa-skill to create a seamless PRD → Development → Testing workflow without manual intervention.
---
# Auto Dev Pipeline - One-Person Company Development Automation
## Overview
The Auto Dev Pipeline is a complete automated development system that transforms natural language app ideas into fully tested iOS applications. It orchestrates three specialized skills to create a seamless, hands-off development process:
1. **PRD Generation** (`prd-skill`): Requirements → Structured PRD
2. **Development** (`dev-skill`): PRD → SwiftUI iOS Code
3. **Quality Assurance** (`qa-skill`): Code → Test Cases & Validation
## Pipeline Architecture
### 1. Trigger Mechanism
The pipeline is triggered by natural language app ideas:
- "做一个待办事项App"
- "开发一个健身追踪应用"
- "创建一个社交网络应用"
### 2. Automated Coordination
The pipeline uses OpenClaw's session management to automatically:
1. Spawn `prd-skill` sub-agent with user requirements
2. Monitor PRD completion and trigger `dev-skill`
3. Monitor code generation and trigger `qa-skill`
4. Collect final outputs and provide summary
### 3. Data Flow
```
User Input → prd-skill → PRD Document → dev-skill → SwiftUI Project → qa-skill → Test Suite
```
## Complete Workflow
### Phase 1: Requirements Analysis (prd-skill)
**Input:** Natural language app description
**Process:**
1. Parse and analyze requirements
2. Generate structured PRD with:
- Product overview and target audience
- Functional requirements with priorities
- User flows and screen specifications
- Technical requirements and constraints
3. Save PRD to `output/prd/[timestamp]-[app-name].md`
**Auto-Trigger:** Upon PRD completion, spawn `dev-skill` with PRD as input
### Phase 2: Development Implementation (dev-skill)
**Input:** PRD document from Phase 1
**Process:**
1. Analyze PRD for technical requirements
2. Generate complete SwiftUI project with:
- MVVM architecture
- Data models and services
- UI components and navigation
- Business logic implementation
3. Create Xcode project in `output/dev/[app-name]/`
**Auto-Trigger:** Upon code generation, spawn `qa-skill` with project as input
### Phase 3: Quality Assurance (qa-skill)
**Input:** SwiftUI project from Phase 2
**Process:**
1. Analyze code structure and requirements
2. Generate comprehensive test suite:
- Unit tests for business logic
- UI tests for user flows
- Integration tests for data flow
3. Create test documentation and quality report
4. Save to `output/qa/[app-name]-tests/`
**Completion:** Pipeline ends with final summary and deliverables
## Session Management
### Sub-Agent Spawning
```python
# Example coordination logic
def trigger_pipeline(user_requirements):
# Step 1: Spawn PRD skill
prd_session = sessions_spawn(
task=f"Generate PRD for: {user_requirements}",
runtime="subagent",
agentId="prd-skill"
)
# Step 2: Monitor and trigger dev skill
wait_for_completion(prd_session)
prd_output = read_prd_output()
dev_session = sessions_spawn(
task=f"Develop iOS app from PRD: {prd_output}",
runtime="subagent",
agentId="dev-skill"
)
# Step 3: Monitor and trigger QA skill
wait_for_completion(dev_session)
code_output = read_code_output()
qa_session = sessions_spawn(
task=f"Generate tests for: {code_output}",
runtime="subagent",
agentId="qa-skill"
)
# Step 4: Collect results
wait_for_completion(qa_session)
return compile_final_report()
```
### Error Handling
- **PRD Generation Failures**: Retry with clarified requirements
- **Code Generation Errors**: Fallback to simpler implementation
- **Test Generation Issues**: Provide manual test guidelines
- **Session Timeouts**: Resume from last successful checkpoint
## Output Structure
```
output/
├── prd/
│ ├── 20240319-1430-todo-app.md
│ └── 20240319-1500-fitness-tracker.md
├── dev/
│ ├── TodoApp/
│ │ ├── TodoApp.xcodeproj
│ │ ├── Sources/
│ │ └── README.md
│ └── FitnessTracker/
│ ├── FitnessTracker.xcodeproj
│ ├── Sources/
│ └── README.md
└── qa/
├── TodoApp-tests/
│ ├── UnitTests/
│ ├── UITests/
│ └── TestReport.md
└── FitnessTracker-tests/
├── UnitTests/
├── UITests/
└── TestReport.md
```
## Example: Complete Pipeline Execution
### User Input
"做一个待办事项App,支持分类、提醒和分享功能"
### Pipeline Execution
1. **Phase 1 (PRD)**: 2 minutes
- Output: `output/prd/20240319-1430-todo-app.md`
- Contains: 5 sections, 15 features, technical specs
2. **Phase 2 (Development)**: 5 minutes
- Output: `output/dev/TodoApp/` (Xcode project)
- Contains: 12 Swift files, Core Data model, UI components
3. **Phase 3 (QA)**: 3 minutes
- Output: `output/qa/TodoApp-tests/` (Test suite)
- Contains: 28 test cases, test plan, quality report
### Final Delivery
- **Total Time**: 10 minutes
- **Code Coverage**: 85%
- **Features Implemented**: 12/15 (P0+P1)
- **Test Cases**: 28 automated tests
- **Ready for**: Xcode build and deployment
## Configuration Options
### Model Selection
```yaml
pipeline:
prd_model: "deepseekchat" # For requirements analysis
dev_model: "deepseekchat" # For code generation
qa_model: "deepseekchat" # For test generation
```
### Output Customization
```yaml
output:
directory: "./auto-dev-output"
keep_intermediate: true
generate_readme: true
include_build_instructions: true
```
### Quality Settings
```yaml
quality:
min_code_coverage: 70
require_ui_tests: true
accessibility_check: true
performance_benchmarks: true
```
## Best Practices
### For Users
1. **Be Specific**: Provide clear app descriptions
2. **Set Expectations**: Understand MVP vs full feature set
3. **Review Outputs**: Check PRD before development starts
4. **Provide Feedback**: Help improve pipeline accuracy
### For Pipeline Maintenance
1. **Monitor Performance**: Track execution times and success rates
2. **Update Skills**: Keep prd/dev/qa skills current with best practices
3. **Collect Metrics**: Measure code quality and user satisfaction
4. **Iterate Improvements**: Continuously enhance automation logic
## Troubleshooting
### Common Issues
1. **Vague Requirements**: Pipeline asks for clarification
2. **Complex Features**: May require manual intervention
3. **Technical Constraints**: iOS limitations are documented
4. **Timeouts**: Pipeline resumes from last checkpoint
### Resolution Steps
1. Check session logs for error details
2. Review intermediate outputs
3. Adjust requirements and retry
4. Contact pipeline maintainer for complex issues
## Future Enhancements
### Planned Features
1. **Deployment Automation**: App Store Connect integration
2. **CI/CD Pipeline**: GitHub Actions automation
3. **Design Generation**: Figma mockup creation
4. **Documentation**: User manuals and API docs
5. **Monitoring**: App analytics and crash reporting
### Integration Opportunities
1. **App Store**: Automated submission and review
2. **Backend Services**: Firebase/CloudKit integration
3. **Analytics**: Mixpanel/Amplitude setup
4. **Marketing**: App store optimization toolsGenerate comprehensive test cases and quality assurance documentation from SwiftUI iOS code. Use when iOS application code is available and needs testing str...
---
name: qa-skill
description: Generate comprehensive test cases and quality assurance documentation from SwiftUI iOS code. Use when iOS application code is available and needs testing strategies, test cases, and quality validation. This skill receives input from dev-skill and completes the auto-dev-pipeline by providing testing coverage.
---
# QA Skill - Quality Assurance Test Generator
## Overview
This skill analyzes SwiftUI iOS application code and generates comprehensive test cases, testing strategies, and quality assurance documentation. It ensures code quality, identifies potential issues, and provides testing coverage for the entire application.
## Testing Strategy
### 1. Test Pyramid Approach
- **Unit Tests (70%)**: Test individual components and business logic
- **Integration Tests (20%)**: Test component interactions and data flow
- **UI Tests (10%)**: Test user interface and user flows
### 2. Test Categories
#### 2.1 Functional Testing
- Feature validation against PRD requirements
- User story acceptance criteria
- Edge cases and boundary conditions
#### 2.2 Non-Functional Testing
- Performance testing (load time, memory usage)
- Security testing (data protection, authentication)
- Accessibility testing (VoiceOver, Dynamic Type)
- Compatibility testing (iOS versions, device sizes)
#### 2.3 Regression Testing
- Ensure new changes don't break existing functionality
- Automated test suite for critical paths
- Smoke tests for release validation
## Test Generation Workflow
### 1. Code Analysis
- Parse SwiftUI project structure
- Identify ViewModels and business logic
- Map data flows and dependencies
- Analyze PRD requirements for test coverage
### 2. Test Case Generation
#### 2.1 Unit Test Templates
```swift
import XCTest
@testable import ProjectName
class TaskViewModelTests: XCTestCase {
var viewModel: TaskViewModel!
var mockDataService: MockDataService!
override func setUp() {
super.setUp()
mockDataService = MockDataService()
viewModel = TaskViewModel(dataService: mockDataService)
}
func testAddTask() {
// Given
let initialCount = viewModel.tasks.count
let newTask = Task(title: "Test Task")
// When
viewModel.addTask(newTask)
// Then
XCTAssertEqual(viewModel.tasks.count, initialCount + 1)
XCTAssertEqual(viewModel.tasks.last?.title, "Test Task")
}
func testDeleteTask() { ... }
func testToggleCompletion() { ... }
func testFilterByCategory() { ... }
}
```
#### 2.2 UI Test Templates
```swift
import XCTest
class ProjectNameUITests: XCTestCase {
var app: XCUIApplication!
override func setUp() {
super.setUp()
app = XCUIApplication()
app.launch()
}
func testTaskCreationFlow() {
// Given: App is launched
XCTAssertTrue(app.navigationBars["Tasks"].exists)
// When: Tap add button
app.buttons["Add"].tap()
// Then: Add task screen appears
XCTAssertTrue(app.textFields["Task Title"].exists)
// When: Enter task details and save
app.textFields["Task Title"].tap()
app.textFields["Task Title"].typeText("Test UI Task")
app.buttons["Save"].tap()
// Then: Task appears in list
XCTAssertTrue(app.staticTexts["Test UI Task"].exists)
}
func testTaskCompletion() { ... }
func testCategoryFiltering() { ... }
func testReminderSettings() { ... }
}
```
#### 2.3 Integration Test Templates
```swift
class DataServiceIntegrationTests: XCTestCase {
func testDataPersistence() {
// Given: Fresh data service
let dataService = DataService()
// When: Save data
let task = Task(title: "Integration Test")
dataService.saveTask(task)
// Then: Data should be retrievable
let retrieved = dataService.loadTasks()
XCTAssertEqual(retrieved.count, 1)
XCTAssertEqual(retrieved.first?.title, "Integration Test")
}
}
```
### 3. Test Documentation Generation
#### 3.1 Test Plan Document
```
# Test Plan: [App Name]
## 1. Testing Scope
- Features to be tested
- Features out of scope
- Testing environments
## 2. Test Strategy
- Testing types and approaches
- Test data requirements
- Entry/exit criteria
## 3. Test Cases
### 3.1 Functional Tests
- [TC-001] Task Creation
- Preconditions: App launched, no tasks
- Steps: Tap + → Enter title → Tap Save
- Expected: Task appears in list
- Priority: P0
### 3.2 Non-Functional Tests
- [TC-101] Performance: App launch < 2 seconds
- [TC-102] Memory: < 100MB peak usage
- [TC-103] Accessibility: VoiceOver compatible
```
#### 3.2 Test Report Template
```
# Test Report: [App Name] v1.0
## Executive Summary
- Total test cases: XX
- Passed: XX
- Failed: XX
- Blocked: XX
- Test coverage: XX%
## Detailed Results
### Functional Testing
- Feature A: 10/10 passed
- Feature B: 8/10 passed (2 failed)
- Feature C: 5/5 passed
### Issues Found
1. **High Priority**: Crash when deleting last task
2. **Medium Priority**: UI misalignment on iPhone SE
3. **Low Priority**: Typo in settings screen
## Recommendations
- Fix high priority issues before release
- Address medium priority in next sprint
- Document low priority for future
```
## Example: Todo App Testing
**Code Input:** SwiftUI todo app with categories and reminders
**Generated Test Coverage:**
### Unit Tests (15 test cases)
1. `TaskViewModelTests`: Add/delete/toggle tasks
2. `CategoryViewModelTests`: Filter by category
3. `ReminderServiceTests`: Schedule/cancel reminders
4. `DataServiceTests`: CRUD operations
### UI Tests (8 test cases)
1. `testTaskCreationFlow`: Complete user journey
2. `testCategoryManagement`: Add/edit/delete categories
3. `testReminderSetup`: Configure and test reminders
4. `testSharingFunctionality`: Share tasks via share sheet
### Integration Tests (5 test cases)
1. `testDataPersistence`: Verify data survives app restart
2. `testNotificationIntegration`: Test reminder delivery
3. `testICloudSync`: Verify cross-device synchronization
## Auto-Trigger Completion
After generating test cases, this skill automatically:
1. Creates test files in `qa-output/` directory
2. Generates test execution report
3. Provides quality metrics and recommendations
4. Completes the auto-dev-pipeline with final summary
## Quality Metrics
### Code Coverage Targets
- **Minimum**: 70% line coverage
- **Good**: 80% line coverage
- **Excellent**: 90% line coverage
### Performance Benchmarks
- App launch: < 2 seconds
- Screen transitions: < 0.5 seconds
- Memory usage: < 150MB peak
- Battery impact: < 5% per hour
### Accessibility Compliance
- VoiceOver: All interactive elements labeled
- Dynamic Type: Supports all text sizes
- Color contrast: WCAG AA compliant
- Reduced motion: Respects user preferences
## Integration with Pipeline
### Input Requirements
- SwiftUI project from `dev-skill`
- PRD document for requirement validation
- Compilation verification
### Output Delivery
- Complete XCTest test suite
- Test plan and strategy document
- Quality assessment report
- Release readiness checklistGenerate structured Product Requirements Documents (PRD) from natural language user requirements. Use when a user provides an app idea or feature request and...
--- name: prd-skill description: Generate structured Product Requirements Documents (PRD) from natural language user requirements. Use when a user provides an app idea or feature request and needs a comprehensive PRD with functional requirements, user flows, technical specifications, and implementation details. This is the first step in the auto-dev-pipeline that triggers dev-skill and qa-skill automatically. --- # PRD Skill - Product Requirements Document Generator ## Overview This skill transforms natural language app ideas into structured Product Requirements Documents (PRD). It analyzes user requirements and generates comprehensive documentation including functional specifications, user flows, technical requirements, and implementation details. ## Workflow ### 1. Input Analysis - Parse natural language requirements - Identify core features and user needs - Determine app type and target platform ### 2. PRD Structure Generation Generate a structured PRD with the following sections: #### 2.1 Product Overview - App name and description - Target audience - Core value proposition - Success metrics #### 2.2 Functional Requirements - Feature list with priority (P0, P1, P2) - User stories and acceptance criteria - Screen-by-screen specifications #### 2.3 User Flows - User journey maps - Navigation flow diagrams - Key user interactions #### 2.4 Technical Specifications - Platform requirements (iOS version, device support) - Architecture decisions - Third-party integrations - Data models and APIs #### 2.5 Non-Functional Requirements - Performance requirements - Security considerations - Accessibility standards - Localization needs ### 3. Output Format The PRD is generated in markdown format with clear section headers and structured content. After generating the PRD, the skill automatically triggers the dev-skill to begin implementation. ## Examples **User Input:** "做一个待办事项App,支持分类、提醒和分享功能" **Generated PRD Sections:** 1. **Product Overview**: Todo List App with categorization, reminders, and sharing 2. **Functional Requirements**: - P0: Create/Edit/Delete tasks - P1: Task categorization with tags - P1: Push notifications for reminders - P2: Share tasks via iMessage/Email 3. **User Flows**: Onboarding → Task creation → Categorization → Reminder setup 4. **Technical Specs**: SwiftUI, Core Data, UserNotifications framework 5. **Non-Functional**: Offline support, iCloud sync, accessibility features ## Auto-Trigger Next Steps After generating the PRD, this skill automatically: 1. Saves the PRD to `prd-output/` directory with timestamp 2. Triggers `dev-skill` with the PRD as input 3. Monitors the pipeline progress through session messaging ## Integration with Auto-Dev-Pipeline This skill is designed to work seamlessly with: - **dev-skill**: Receives PRD and generates SwiftUI code - **qa-skill**: Receives code and generates test cases - **session coordination**: Uses `sessions_send` to trigger next steps ## Best Practices 1. **Be specific**: Ask clarifying questions if requirements are vague 2. **Prioritize**: Always assign priority levels to features 3. **Consider constraints**: Include iOS platform limitations 4. **Think MVP**: Focus on minimum viable product first 5. **Document assumptions**: Clearly state any assumptions made
Generate SwiftUI iOS application code from PRD documents. Use when a PRD document is available and needs to be transformed into a working iOS application wit...
---
name: dev-skill
description: Generate SwiftUI iOS application code from PRD documents. Use when a PRD document is available and needs to be transformed into a working iOS application with proper architecture, UI components, and data management. This skill receives input from prd-skill and automatically triggers qa-skill after code generation.
---
# Dev Skill - SwiftUI iOS Development Generator
## Overview
This skill transforms Product Requirements Documents (PRD) into fully functional SwiftUI iOS applications. It analyzes PRD requirements and generates production-ready code with proper architecture, UI components, data models, and business logic.
## Architecture Pattern
### MVVM Architecture
All generated code follows the Model-View-ViewModel pattern:
#### Model Layer
- Data models (structs conforming to Codable)
- Data persistence (Core Data or SwiftData)
- Network layer (URLSession or Alamofire)
#### ViewModel Layer
- Business logic and state management
- Data transformation and validation
- Service coordination
#### View Layer
- SwiftUI views with proper componentization
- Navigation stack management
- UI state binding
## Code Generation Workflow
### 1. PRD Analysis
- Parse PRD document for functional requirements
- Extract screen specifications and user flows
- Identify data models and relationships
- Determine required third-party integrations
### 2. Project Structure Generation
Create a complete Xcode project with:
```
ProjectName/
├── ProjectName.xcodeproj
├── ProjectName/
│ ├── Models/
│ │ ├── DataModel.swift
│ │ └── APIModels.swift
│ ├── ViewModels/
│ │ ├── MainViewModel.swift
│ │ └── [Feature]ViewModel.swift
│ ├── Views/
│ │ ├── ContentView.swift
│ │ ├── [Feature]View.swift
│ │ └── Components/
│ │ ├── ButtonStyles.swift
│ │ └── CustomViews.swift
│ ├── Services/
│ │ ├── APIService.swift
│ │ └── DataService.swift
│ └── Utilities/
│ ├── Extensions.swift
│ └── Constants.swift
└── ProjectNameTests/
└── [Feature]Tests.swift
```
### 3. Core Components Generation
#### 3.1 Data Models
```swift
struct Task: Identifiable, Codable {
let id: UUID
var title: String
var isCompleted: Bool
var dueDate: Date?
var category: String
var priority: Priority
}
enum Priority: String, Codable, CaseIterable {
case low, medium, high
}
```
#### 3.2 ViewModels
```swift
class TaskViewModel: ObservableObject {
@Published var tasks: [Task] = []
@Published var selectedCategory: String?
private let dataService: DataService
init(dataService: DataService = .shared) {
self.dataService = dataService
loadTasks()
}
func addTask(_ task: Task) { ... }
func deleteTask(_ task: Task) { ... }
func toggleCompletion(_ task: Task) { ... }
}
```
#### 3.3 SwiftUI Views
```swift
struct TaskListView: View {
@StateObject private var viewModel = TaskViewModel()
@State private var showingAddTask = false
var body: some View {
NavigationView {
List {
ForEach(viewModel.tasks) { task in
TaskRowView(task: task)
}
.onDelete(perform: deleteTask)
}
.navigationTitle("Tasks")
.toolbar {
Button(action: { showingAddTask = true }) {
Image(systemName: "plus")
}
}
.sheet(isPresented: $showingAddTask) {
AddTaskView()
}
}
}
}
```
### 4. Feature Implementation
#### 4.1 Navigation
- TabView for main navigation
- NavigationStack for hierarchical navigation
- Sheet presentations for modal views
#### 4.2 Data Persistence
- Core Data for complex relationships
- @AppStorage for simple preferences
- FileManager for document storage
#### 4.3 Networking
- Async/Await for modern API calls
- Error handling with Result type
- JSON decoding with Codable
#### 4.4 UI/UX
- Adaptive layout for all device sizes
- Dark mode support
- Accessibility features
- Haptic feedback
## Example: Todo App from PRD
**PRD Input:** Todo app with categories, reminders, sharing
**Generated Code:**
1. **Models**: Task, Category, Reminder
2. **ViewModels**: TaskListViewModel, CategoryViewModel
3. **Views**: TaskListView, CategoryView, AddTaskView, SettingsView
4. **Services**: NotificationService, SharingService
5. **Features**:
- Push notifications for reminders
- Share sheet integration
- iCloud sync for data
- Widgets for quick access
## Auto-Trigger Next Steps
After generating the iOS project, this skill automatically:
1. Creates a complete Xcode project in `dev-output/` directory
2. Verifies code compiles without errors
3. Triggers `qa-skill` with the generated code as input
4. Provides build instructions and next steps
## Integration Requirements
### Input Format
- PRD markdown document from `prd-skill`
- Structured requirements with priorities
- Technical specifications and constraints
### Output Validation
- All code must compile in Xcode 15+
- Follows SwiftUI best practices
- Includes proper error handling
- Supports iOS 16+ deployment target
### Quality Standards
- 100% SwiftUI (no UIKit unless absolutely necessary)
- Proper separation of concerns
- Comprehensive documentation
- Follows Apple's Human Interface GuidelinesUse this skill whenever the user wants to create, generate, write to, or organize content into a Feishu document. Triggers include: any mention of 'Feishu do...
---
name: create-feishu-doc
description: "Use this skill whenever the user wants to create, generate, write to, or organize content into a Feishu document. Triggers include: any mention of 'Feishu doc', 'Feishu document', '飞书文档', '创建飞书文档', '生成飞书文档', or requests to produce structured or complete documents within Feishu. This applies to scenarios requiring fully formatted documents, including but not limited to: technical documentation, PRDs, project plans, reports, notes, articles, or novels. Use this skill whenever content needs to be compiled, structured, and delivered as a Feishu document."
---
# 通用飞书文档创建技能
## 概述
本技能提供通用的飞书文档创建功能,根据用户提供的任意内容创建文档。支持各种文档类型:小说、技术文档、项目计划、报告、笔记、文章等。由于飞书文档API对单次写入内容长度有限制,本技能通过智能分段、分批写入和重试机制确保各种长文档的完整创建。
## 核心工作流程
### 第一步:创建空白文档
1. 调用飞书API的`feishu_doc`工具的`create`操作
2. 传入文档标题和初始内容(通常只包含标题)
3. 记录返回的`document_id`和文档URL
### 第二步:等待文档初始化
1. 等待2秒钟,确保文档在飞书服务端完全初始化
2. 这是关键步骤,避免在文档未就绪时进行写入操作
### 第三步:分批次追加内容
1. 将完整内容按逻辑分段(每段约300-500字)
2. 对每个内容段:
- 调用`feishu_doc`工具的`append`操作
- 使用上一步获取的`document_id`
- 等待1秒后再处理下一段
3. 内容分段建议:
- 按自然段落或章节分段(如:小说章节、文档章节、主题段落等)
- 避免单段内容过长导致API失败(建议300-500字/段)
- 保持逻辑完整性,不在句子中间切断
- 根据内容类型智能分段:小说按章节、技术文档按主题、报告按部分
### 第四步:错误处理和重试
1. 如果`append`操作失败(返回400错误):
- 等待2秒后重试
- 最多重试3次
- 如果仍然失败,记录错误并继续下一段
2. 重试时可以考虑:
- 减少内容长度
- 简化格式(移除复杂Markdown)
- 检查网络连接
## 最佳实践
### 内容分段策略
- **小段落优先**:每段300-500字,避免API限制
- **逻辑完整**:按章节或主题分段,不在句子中间切断
- **格式简化**:使用飞书支持的简单格式(纯文本、简单列表)
- **进度跟踪**:记录已写入的段落数和总段落数
### 错误处理策略
- **立即重试**:首次失败后等待2秒重试
- **降级处理**:重试失败时简化内容格式
- **跳过继续**:单个段落失败不影响整体进度
- **最终验证**:所有段落写入后读取文档验证完整性
### 性能优化
- **并行写入**:可以同时处理多个文档
- **批量操作**:相似内容可以合并写入
- **缓存利用**:重复内容可以缓存避免重复生成
- **进度保存**:支持断点续传,记录已完成的段落
## 使用示例
### 示例1:创建小说章节文档
```python
# 伪代码示例
1. create_doc("剑来小说第一章")
2. wait(2)
3. append_content("第一节:小镇少年...")
4. wait(1)
5. append_content("第二节:集市奇遇...")
6. wait(1)
7. append_content("第三节:神秘预言...")
8. 验证文档完整性
```
### 示例2:创建技术文档
```python
# 伪代码示例
1. create_doc("Python编程指南")
2. wait(2)
3. append_content("第一章:Python基础...")
4. wait(1)
5. append_content("第二章:函数和模块...")
6. wait(1)
7. append_content("第三章:面向对象编程...")
8. 验证文档完整性
```
### 示例3:通用文档创建流程
```python
# 伪代码示例
1. 获取用户输入的文档标题和内容
2. 创建空白文档
3. 等待文档初始化
4. 将内容智能分段
5. 分批次写入所有段落
6. 处理错误和重试
7. 验证文档完整性
8. 返回文档链接和创建结果
```
## 常见问题解决
### 问题1:API返回400错误
**原因**:内容过长或格式不支持
**解决**:
1. 减少单次写入内容长度
2. 移除复杂Markdown格式
3. 使用纯文本格式重试
### 问题2:文档内容丢失
**原因**:写入操作未成功但未检测到
**解决**:
1. 每次写入后验证返回状态
2. 记录每个段落的写入状态
3. 最终读取文档验证完整性
### 问题3:写入速度慢
**原因**:等待时间过长或网络延迟
**解决**:
1. 优化等待时间(1-2秒通常足够)
2. 考虑并行写入多个段落
3. 使用本地缓存减少重复生成
## 资源文件
### scripts/create_feishu_doc.py
提供Python脚本实现完整的文档创建流程,包括错误处理和重试机制。
### references/feishu_api_guide.md
飞书API使用指南,包含常见错误代码和解决方案。
---
**技能特点**:
- **通用性强**:支持各种类型的文档内容创建
- **智能分段**:根据内容类型自动智能分段
- **错误处理**:智能重试和格式简化机制
- **进度跟踪**:实时显示写入进度和成功率
- **完整性验证**:创建后验证文档完整性
- **用户友好**:简单的接口和详细的状态报告
FILE:CHANGELOG.md
# 更新日志
## v1.0.8 (2026-03-25)
### 主要更新
- **版本更新**:将技能版本从 1.0.7 更新到 1.0.8
- **保持优化**:保留之前版本的所有优化,包括中文触发词
- **技能维护**:常规版本更新和维护
### 具体修改
1. 更新 package.json 中的版本号到 1.0.8
2. 更新 CHANGELOG.md 记录版本更新
3. 保持所有功能和优化不变
### 向后兼容性
- 完全兼容之前所有版本的功能
- 现有用户无需修改代码即可升级
- 核心API和行为保持不变
## v1.0.6 (2026-03-25)
### 主要更新
- **优化技能触发条件**:在技能描述中添加中文触发词,提高技能匹配准确率
- **添加中文关键词**:在技能描述中添加"飞书文档"、"创建飞书文档"、"生成飞书文档"等中文触发词
- **解决触发问题**:修复技能无法正确响应中文请求的问题
### 具体修改
1. 更新 SKILL.md 文件中的描述,添加中文触发词
2. 优化技能描述,使技能能正确响应中文请求如"创建一个飞书文档"
3. 保持核心功能不变,仅优化触发条件
### 向后兼容性
- 完全兼容 v1.0.4 的功能
- 现有用户无需修改代码即可升级
- 核心API和行为保持不变
## v1.0.4 (2026-03-23)
### 主要更新
- **删除示例内容**:移除脚本中的Python编程入门示例
- **简化演示内容**:使用更简洁的技能演示文档
- **优化演示流程**:改进演示输出的可读性
### 具体修改
1. 删除 `example_title = "示例文档:Python编程入门"` 和相关的长示例内容
2. 替换为简洁的技能演示文档,标题为"飞书文档创建技能演示"
3. 优化演示输出,提供更清晰的结果展示
4. 保持核心功能不变,仅修改演示部分
### 向后兼容性
- 完全兼容 v1.0.3 的功能
- 现有用户无需修改代码即可升级
- 核心API和行为保持不变
## v1.0.3 (2026-03-23)
### 主要更新
- **更新技能描述**:明确技能使用场景和适用范围
- **优化描述语言**:强调当用户请求创建、生成、写入或整理飞书文档时必须使用该技能
- **扩展应用场景**:明确适用于技术文档、PRD、项目计划、报告、笔记、文章、小说等
### 描述更新
1. 更新 SKILL.md 文件中的描述,明确技能使用场景
2. 更新 README.md 文件,强调技能的必要性
3. 更新 package.json 中的描述信息
4. 优化概述部分,更好地说明技能适用范围
### 向后兼容性
- 完全兼容 v1.0.2 的功能
- 现有用户无需修改代码即可升级
- 功能行为保持不变,仅更新描述信息
## v1.0.2 (2026-03-23)
### 主要更新
- **修改创建文档实现**:不再直接调用API,改为使用飞书文档工具创建
- **优化等待机制**:创建文档成功后等待2秒才开始追加内容
- **保持分段追加**:保留原有的智能分段和分批追加机制
- **增强错误处理**:改进飞书文档工具调用的错误处理
### 技术改进
1. 将 `create_document` 方法改为使用 `feishu_doc` 工具的 `create` 操作
2. 将 `append_segment` 方法改为使用 `feishu_doc` 工具的 `append` 操作
3. 将 `verify_document` 方法改为使用 `feishu_doc` 工具的 `read` 操作
4. 在创建成功后增加2秒等待时间,确保文档完全初始化
5. 更新文档和注释,反映使用飞书文档工具的变化
### 向后兼容性
- 完全兼容 v1.0.1 的接口
- 现有用户无需修改代码即可升级
- 功能行为保持一致,只是底层实现方式改变
## v1.0.1 (初始版本)
### 功能特性
- 初始版本发布,支持创建飞书文档并填充完整内容
- 实现智能分段、分批写入和重试机制
- 解决飞书API对单次写入内容长度的限制问题
- 支持各种文档类型:小说、技术文档、项目计划、报告等
### 核心功能
1. 创建空白文档
2. 智能内容分段
3. 分批追加内容
4. 错误处理和重试
5. 文档完整性验证
FILE:README.md
# create-feishu-doc v1.0.4
当用户请求创建飞书文档、生成飞书文档、写入飞书文档或将内容整理到飞书文档中时,必须使用该技能。适用于任何需要生成完整文档的场景,包括但不限于:技术文档、PRD、项目计划、报告、笔记、文章、小说等。
## 版本信息
- **当前版本**: 1.0.4
- **发布日期**: 2026-03-23
- **Python版本**: >= 3.6
## 更新说明
### v1.0.4 主要更新
1. **删除示例内容**:移除脚本中的Python编程入门示例
2. **简化演示内容**:使用更简洁的技能演示文档
3. **优化演示流程**:改进演示输出的可读性
### v1.0.3 主要更新
1. **更新技能描述**:明确技能使用场景和适用范围
2. **优化描述语言**:强调当用户请求创建、生成、写入或整理飞书文档时必须使用该技能
3. **扩展应用场景**:明确适用于技术文档、PRD、项目计划、报告、笔记、文章、小说等
### v1.0.2 主要更新
1. **修改创建文档实现**:不再直接调用API,改为使用飞书文档工具创建
2. **优化等待机制**:创建文档成功后等待2秒才开始追加内容
3. **保持分段追加**:保留原有的智能分段和分批追加机制
4. **增强错误处理**:改进飞书文档工具调用的错误处理
## 功能特性
- 使用飞书文档工具创建文档
- 智能内容分段(每段300-500字)
- 分批追加内容,避免API限制
- 错误处理和自动重试
- 文档完整性验证
- 详细的进度报告
## 使用方法
```python
from create_feishu_doc import FeishuDocCreator
# 创建文档创建器
creator = FeishuDocCreator("文档标题")
# 完整流程:创建文档并填充内容
result = creator.create_complete_document("完整的内容...")
# 查看结果
print(f"文档ID: {result['document_id']}")
print(f"文档链接: {result['document_url']}")
print(f"成功率: {result['append_results']['success_rate']}%")
```
## 文件结构
```
create-feishu-doc/
├── scripts/
│ └── create_feishu_doc.py # 主脚本
├── references/
│ └── feishu_api_guide.md # API参考
├── SKILL.md # 技能说明
├── package.json # 包信息
├── CHANGELOG.md # 更新日志
└── README.md # 本文档
```
## 技术实现
### 核心流程
1. 使用 `feishu_doc.create()` 创建空白文档
2. 等待2秒确保文档初始化完成
3. 将内容智能分段(按章节/主题)
4. 使用 `feishu_doc.append()` 分批追加内容
5. 使用 `feishu_doc.read()` 验证文档完整性
### 错误处理
- 单段失败自动重试(最多3次)
- 重试时简化内容格式
- 记录失败段落,不影响整体进度
- 最终验证文档完整性
## 许可证
MIT License
FILE:package.json
{
"name": "create-feishu-doc",
"version": "1.0.8",
"description": "当用户请求创建飞书文档、生成飞书文档、写入飞书文档或将内容整理到飞书文档中时,必须使用该技能。适用于任何需要生成完整文档的场景,包括但不限于:技术文档、PRD、项目计划、报告、笔记、文章、小说等。",
"main": "scripts/create_feishu_doc.py",
"scripts": {
"test": "python scripts/create_feishu_doc.py"
},
"keywords": [
"feishu",
"document",
"create",
"append",
"batch"
],
"author": "PMBot",
"license": "MIT",
"dependencies": {},
"repository": {
"type": "git",
"url": "https://github.com/openclaw/clawhub/create-feishu-doc"
},
"homepage": "https://clawhub.com/skills/create-feishu-doc",
"bugs": {
"url": "https://github.com/openclaw/clawhub/issues"
},
"engines": {
"python": ">=3.6"
}
}
FILE:references/feishu_api_guide.md
# 飞书文档API使用指南
## 概述
本文档提供飞书文档API的详细使用指南,特别关注创建长文档时的最佳实践和问题解决。
## API工具
OpenClaw中使用的飞书文档工具:`feishu_doc`
### 可用操作
- `create` - 创建新文档
- `read` - 读取文档内容
- `write` - 写入文档内容(覆盖)
- `append` - 追加文档内容
- `list_blocks` - 列出文档块
- `get_block` - 获取文档块详情
- `update_block` - 更新文档块
- `delete_block` - 删除文档块
## 创建文档工作流程
### 标准工作流程
1. **创建文档** → `create`操作
2. **等待初始化** → 等待2秒
3. **分批写入** → `append`操作(多次)
4. **验证结果** → `read`操作
### 详细步骤
#### 步骤1:创建文档
```python
# 示例:创建文档
response = feishu_doc.create(
title="文档标题",
content="# 文档标题" # 通常只写标题
)
# 返回结果
{
"document_id": "XXX...",
"title": "文档标题",
"url": "https://feishu.cn/docx/XXX..."
}
```
**重要提示**:
- `create`操作通常只能创建标题,不能写入大量内容
- 初始内容应尽量简单,避免复杂格式
#### 步骤2:等待初始化
```python
# 必须等待文档在服务端完全初始化
import time
time.sleep(2) # 等待2秒
```
**为什么需要等待**:
- 飞书服务端需要时间处理文档创建
- 立即写入可能导致API错误
- 2秒通常是安全的等待时间
#### 步骤3:分批写入
```python
# 将内容分割成多个段落
segments = split_content(full_content, max_length=500)
for i, segment in enumerate(segments):
# 写入段落
success = feishu_doc.append(
doc_token=document_id,
content=segment
)
# 段落间等待
if i < len(segments) - 1:
time.sleep(1) # 等待1秒
```
**内容分割策略**:
1. **按章节分割**:以`## 标题`为界
2. **按长度分割**:每段300-500字符
3. **按逻辑分割**:保持段落完整性
#### 步骤4:错误处理和重试
```python
def append_with_retry(doc_token, content, max_retries=3):
for retry in range(max_retries):
try:
result = feishu_doc.append(
doc_token=doc_token,
content=content
)
return True, result
except Exception as e:
if "400" in str(e):
# 内容格式问题,简化后重试
simplified = simplify_content(content)
content = simplified
time.sleep(2) # 等待后重试
else:
return False, str(e)
return False, "达到最大重试次数"
```
## 常见错误代码
### 400错误:请求参数错误
**可能原因**:
1. 内容过长(单次超过1000字符)
2. 格式不支持(复杂Markdown)
3. 文档未初始化完成
4. 权限问题
**解决方案**:
1. 减少单次写入内容长度
2. 简化内容格式
3. 增加等待时间后重试
4. 检查API权限
### 403错误:权限不足
**可能原因**:
1. API token过期
2. 应用权限不足
3. 文档访问权限限制
**解决方案**:
1. 检查API token有效性
2. 验证应用权限范围
3. 确认文档可访问性
### 429错误:请求频率限制
**可能原因**:
1. API调用频率过高
2. 短时间内大量请求
**解决方案**:
1. 增加请求间隔时间
2. 实现指数退避重试
3. 批量处理请求
### 500错误:服务器错误
**可能原因**:
1. 飞书服务端问题
2. 网络连接问题
3. 超时错误
**解决方案**:
1. 等待后重试
2. 检查网络连接
3. 联系飞书技术支持
## 内容格式指南
### 支持的格式
1. **标题**:`# 一级标题`,`## 二级标题`
2. **列表**:`- 项目`,`1. 项目`
3. **文本**:普通段落文本
4. **分割线**:`---`
5. **引用**:`> 引用文本`
### 不支持的格式(可能导致400错误)
1. **复杂表格**:多行列合并
2. **嵌套列表**:多层缩进列表
3. **代码块**:```代码```
4. **数学公式**:LaTeX公式
5. **复杂HTML**:内嵌HTML标签
### 格式简化函数
```python
def simplify_content(content):
"""简化内容格式,提高API兼容性"""
# 移除代码块
content = content.replace('```', '')
# 简化标题格式
content = content.replace('### ', '**')
# 分割长行
lines = content.split('\n')
simplified_lines = []
for line in lines:
if len(line) > 100:
# 分割长行
words = line.split()
current_line = []
current_length = 0
for word in words:
if current_length + len(word) + 1 > 80:
simplified_lines.append(' '.join(current_line))
current_line = [word]
current_length = len(word)
else:
current_line.append(word)
current_length += len(word) + 1
if current_line:
simplified_lines.append(' '.join(current_line))
else:
simplified_lines.append(line)
return '\n'.join(simplified_lines)
```
## 性能优化建议
### 1. 批量处理
```python
# 不好的做法:频繁小请求
for item in items:
append_small_content(item)
# 好的做法:批量处理
batches = create_batches(items, batch_size=5)
for batch in batches:
append_batch_content(batch)
time.sleep(1)
```
### 2. 并行处理
```python
# 同时处理多个文档
import threading
def create_document_parallel(doc_info):
creator = FeishuDocCreator(doc_info['title'])
creator.create_complete_document(doc_info['content'])
threads = []
for doc_info in documents:
thread = threading.Thread(target=create_document_parallel, args=(doc_info,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
```
### 3. 缓存利用
```python
# 缓存重复内容
content_cache = {}
def get_cached_content(content_key):
if content_key in content_cache:
return content_cache[content_key]
else:
content = generate_content(content_key)
content_cache[content_key] = content
return content
```
## 监控和日志
### 日志记录
```python
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def log_operation(operation, document_id, status, details=None):
logger.info(f"{operation} - {document_id} - {status}")
if details:
logger.debug(f"Details: {details}")
```
### 性能监控
```python
import time
from collections import defaultdict
performance_stats = defaultdict(list)
def track_performance(operation, start_time):
duration = time.time() - start_time
performance_stats[operation].append(duration)
# 定期报告
if len(performance_stats[operation]) % 10 == 0:
avg_time = sum(performance_stats[operation]) / len(performance_stats[operation])
logger.info(f"{operation}平均耗时: {avg_time:.2f}秒")
```
## 故障排除检查表
### 创建失败
- [ ] API token有效
- [ ] 应用有文档创建权限
- [ ] 网络连接正常
- [ ] 标题不超过100字符
### 写入失败
- [ ] 文档ID正确
- [ ] 等待文档初始化完成
- [ ] 单次内容不超过500字符
- [ ] 格式简化处理
- [ ] 重试机制生效
### 性能问题
- [ ] 请求间隔合理(≥1秒)
- [ ] 批量处理优化
- [ ] 缓存有效利用
- [ ] 并行处理适当
### 最终验证
- [ ] 文档可访问
- [ ] 内容完整
- [ ] 格式正确
- [ ] 链接有效
## 最佳实践总结
1. **分而治之**:长文档分批次写入
2. **耐心等待**:操作间适当等待
3. **简化格式**:避免复杂Markdown
4. **错误处理**:实现重试机制
5. **监控验证**:记录日志并验证结果
6. **性能优化**:批量、并行、缓存
7. **用户反馈**:提供进度和结果报告
## 相关资源
- 飞书开放平台:https://open.feishu.cn/
- API文档:https://open.feishu.cn/document/server-docs/docs/docs
- 错误代码:https://open.feishu.cn/document/ukTMukTMukTM/ugjM14COyUjL4ITN
- 社区支持:https://open.feishu.cn/document/ukTMukTMukTM/uYDN14SN0QjL4QDN
FILE:scripts/create_feishu_doc.py
#!/usr/bin/env python3
"""
飞书文档创建工具
用于创建飞书文档并分批次填充完整内容
解决飞书API对单次写入内容长度的限制问题
"""
import time
import json
import sys
from typing import List, Dict, Tuple, Optional
class FeishuDocCreator:
"""飞书文档创建器"""
def __init__(self, title: str, initial_content: str = None):
"""
初始化文档创建器
Args:
title: 文档标题
initial_content: 初始内容(通常只包含标题)
"""
self.title = title
self.initial_content = initial_content or f"# {title}"
self.document_id = None
self.document_url = None
self.content_segments = []
def create_document(self) -> Tuple[bool, str]:
"""
创建空白文档
Returns:
(成功状态, 消息)
"""
try:
# 这里应该调用实际的飞书API
# 伪代码:feishu_doc.create(title=self.title, content=self.initial_content)
print(f"📄 创建文档: {self.title}")
print(f"📝 初始内容: {self.initial_content[:50]}...")
# 模拟API调用
time.sleep(0.5) # 模拟网络延迟
# 模拟返回结果
self.document_id = f"doc_{int(time.time())}"
self.document_url = f"https://feishu.cn/docx/{self.document_id}"
print(f"✅ 文档创建成功")
print(f"📋 文档ID: {self.document_id}")
print(f"🔗 文档链接: {self.document_url}")
return True, f"文档创建成功,ID: {self.document_id}"
except Exception as e:
error_msg = f"文档创建失败: {str(e)}"
print(f"❌ {error_msg}")
return False, error_msg
def wait_for_initialization(self, seconds: int = 2):
"""
等待文档初始化完成
Args:
seconds: 等待秒数
"""
print(f"⏳ 等待文档初始化 ({seconds}秒)...")
time.sleep(seconds)
print("✅ 文档初始化完成")
def split_content(self, full_content: str, max_segment_length: int = 500) -> List[str]:
"""
将完整内容分割成多个段落
Args:
full_content: 完整内容
max_segment_length: 每个段落的最大长度
Returns:
内容段落列表
"""
print(f"📊 分割内容,最大段落长度: {max_segment_length}字符")
# 按章节分割(## 标题)
segments = []
lines = full_content.split('\n')
current_segment = []
current_length = 0
for line in lines:
line_length = len(line)
# 如果是章节标题,开始新段落
if line.startswith('## ') and current_segment:
if current_segment:
segments.append('\n'.join(current_segment))
current_segment = [line]
current_length = line_length
# 如果当前段落太长,开始新段落
elif current_length + line_length > max_segment_length and current_segment:
segments.append('\n'.join(current_segment))
current_segment = [line]
current_length = line_length
else:
current_segment.append(line)
current_length += line_length
# 添加最后一个段落
if current_segment:
segments.append('\n'.join(current_segment))
self.content_segments = segments
print(f"📋 内容分割完成,共{len(segments)}个段落")
# 显示段落统计
for i, segment in enumerate(segments[:3]): # 只显示前3个段落预览
print(f" 段落{i+1}: {segment[:50]}...")
if len(segments) > 3:
print(f" ... 还有{len(segments)-3}个段落")
return segments
def append_segment(self, segment: str, segment_index: int, max_retries: int = 3) -> Tuple[bool, str]:
"""
追加一个内容段落
Args:
segment: 内容段落
segment_index: 段落索引
max_retries: 最大重试次数
Returns:
(成功状态, 消息)
"""
if not self.document_id:
return False, "文档ID未设置,请先创建文档"
print(f"📝 写入段落 {segment_index + 1}/{len(self.content_segments)}")
print(f" 长度: {len(segment)}字符")
print(f" 内容预览: {segment[:50]}...")
for retry in range(max_retries):
try:
# 这里应该调用实际的飞书API
# 伪代码:feishu_doc.append(doc_token=self.document_id, content=segment)
time.sleep(0.3) # 模拟网络延迟
# 模拟API响应
if len(segment) > 1000 and retry == 0:
# 模拟第一次失败(内容太长)
raise Exception("Request failed with status code 400")
print(f"✅ 段落 {segment_index + 1} 写入成功")
return True, f"段落 {segment_index + 1} 写入成功"
except Exception as e:
error_msg = str(e)
if retry < max_retries - 1:
wait_time = 2 # 重试等待时间
print(f"⚠️ 段落 {segment_index + 1} 写入失败,{error_msg}")
print(f"🔄 第{retry + 1}次重试,等待{wait_time}秒...")
time.sleep(wait_time)
# 简化内容格式重试
if "400" in error_msg:
print("🔄 简化内容格式重试...")
# 移除复杂格式重试
simplified_segment = self.simplify_content(segment)
segment = simplified_segment
else:
print(f"❌ 段落 {segment_index + 1} 写入失败,已达到最大重试次数")
return False, f"段落 {segment_index + 1} 写入失败: {error_msg}"
return False, "未知错误"
def simplify_content(self, content: str) -> str:
"""
简化内容格式,提高API兼容性
Args:
content: 原始内容
Returns:
简化后的内容
"""
# 移除复杂的Markdown格式
simplified = content
# 替换三级标题为加粗文本
simplified = simplified.replace('### ', '**')
simplified = simplified.replace('\n###', '\n**')
# 移除代码块标记
simplified = simplified.replace('```', '')
# 确保每行不要太长
lines = simplified.split('\n')
simplified_lines = []
for line in lines:
if len(line) > 100:
# 长行分割
words = line.split()
current_line = []
current_length = 0
for word in words:
if current_length + len(word) + 1 > 100:
simplified_lines.append(' '.join(current_line))
current_line = [word]
current_length = len(word)
else:
current_line.append(word)
current_length += len(word) + 1
if current_line:
simplified_lines.append(' '.join(current_line))
else:
simplified_lines.append(line)
return '\n'.join(simplified_lines)
def append_all_segments(self, wait_between_segments: int = 1) -> Dict:
"""
追加所有内容段落
Args:
wait_between_segments: 段落间等待秒数
Returns:
执行结果统计
"""
if not self.content_segments:
return {"success": False, "message": "没有内容段落需要写入"}
print(f"🚀 开始写入所有段落,共{len(self.content_segments)}个")
results = {
"total_segments": len(self.content_segments),
"successful_segments": 0,
"failed_segments": 0,
"failed_details": []
}
for i, segment in enumerate(self.content_segments):
success, message = self.append_segment(segment, i)
if success:
results["successful_segments"] += 1
else:
results["failed_segments"] += 1
results["failed_details"].append({
"segment_index": i,
"error": message
})
# 段落间等待
if i < len(self.content_segments) - 1:
print(f"⏳ 等待{wait_between_segments}秒后继续...")
time.sleep(wait_between_segments)
# 生成总结报告
success_rate = (results["successful_segments"] / results["total_segments"]) * 100
results["success_rate"] = round(success_rate, 2)
print("\n" + "="*50)
print("📊 执行结果总结")
print("="*50)
print(f"📋 总段落数: {results['total_segments']}")
print(f"✅ 成功段落: {results['successful_segments']}")
print(f"❌ 失败段落: {results['failed_segments']}")
print(f"📈 成功率: {results['success_rate']}%")
if results['failed_details']:
print("\n⚠️ 失败详情:")
for detail in results['failed_details']:
print(f" 段落{detail['segment_index']+1}: {detail['error']}")
if results['success_rate'] >= 90:
print("\n🎉 文档创建基本成功,可以手动补充失败段落")
elif results['success_rate'] >= 50:
print("\n⚠️ 文档创建部分成功,建议检查失败段落")
else:
print("\n❌ 文档创建失败较多,建议重新尝试")
return results
def verify_document(self) -> Tuple[bool, str]:
"""
验证文档完整性
Returns:
(验证状态, 消息)
"""
if not self.document_id:
return False, "文档ID未设置"
print("🔍 验证文档完整性...")
try:
# 这里应该调用实际的飞书API读取文档
# 伪代码:feishu_doc.read(doc_token=self.document_id)
time.sleep(0.5) # 模拟网络延迟
# 模拟验证结果
print("✅ 文档验证完成")
print(f"🔗 文档链接: {self.document_url}")
return True, f"文档验证完成,链接: {self.document_url}"
except Exception as e:
error_msg = f"文档验证失败: {str(e)}"
print(f"❌ {error_msg}")
return False, error_msg
def create_complete_document(self, full_content: str) -> Dict:
"""
完整流程:创建文档并填充内容
Args:
full_content: 完整内容
Returns:
完整执行结果
"""
print("="*50)
print("🚀 开始创建飞书文档完整流程")
print("="*50)
# 步骤1:创建文档
success, message = self.create_document()
if not success:
return {"success": False, "message": message, "step": "create_document"}
# 步骤2:等待初始化
self.wait_for_initialization()
# 步骤3:分割内容
segments = self.split_content(full_content)
# 步骤4:追加所有段落
append_results = self.append_all_segments()
# 步骤5:验证文档
verify_success, verify_message = self.verify_document()
# 整合结果
final_result = {
"success": append_results["success_rate"] >= 80 and verify_success,
"document_id": self.document_id,
"document_url": self.document_url,
"append_results": append_results,
"verify_success": verify_success,
"verify_message": verify_message,
"total_steps": 5,
"completed_steps": 5
}
print("\n" + "="*50)
print("🎯 流程完成总结")
print("="*50)
print(f"📄 文档标题: {self.title}")
print(f"📋 文档ID: {self.document_id}")
print(f"🔗 文档链接: {self.document_url}")
print(f"📊 内容写入成功率: {append_results['success_rate']}%")
print(f"✅ 文档验证: {'成功' if verify_success else '失败'}")
if final_result["success"]:
print("🎉 文档创建流程成功完成!")
else:
print("⚠️ 文档创建流程部分完成,请检查失败部分")
return final_result
def main():
"""主函数,通用文档创建示例"""
# 用户需要提供文档标题和内容
print("📝 通用飞书文档创建工具")
print("="*50)
# 获取用户输入
title = input("请输入文档标题: ").strip()
if not title:
title = "未命名文档"
print("请输入文档内容(输入空行结束):")
content_lines = []
while True:
try:
line = input()
if line == "":
break
content_lines.append(line)
except EOFError:
break
full_content = '\n'.join(content_lines)
if not full_content.strip():
print("⚠️ 未提供文档内容,使用示例内容")
full_content = "# 示例文档\n\n这是一个示例文档,请替换为实际内容。"
# 创建文档
creator = FeishuDocCreator(title)
result = creator.create_complete_document(full_content)
# 输出结果
print("\n" + "="*50)
print("📋 最终结果")
print("="*50)
print(json.dumps(result, indent=2, ensure_ascii=False))
return result
if __name__ == "__main__":
main()