思源笔记自动化中枢 · 块级精准操控
简介
思源笔记官方API客户端,支持完整的笔记本/文档/块级管理,提供Python SDK与8款CLI工具,实现本地知识库自动化操作。
原始描述
SiYuan Note (思源笔记) API client - Complete notebook, document and block management
通过你的 Agent 添加
安装目录:siyuan-note/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。
点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。
或者手动安装
包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可;
目录名不用换,也不要把包直接解压到 skills 根目录。
技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。
中文使用说明 来自收录源
核心用法
SiYuan Note API Client 是思源笔记的官方HTTP API封装库,提供两类使用方式:
Python SDK:通过 SiYuanClient 类以编程方式管理知识库,支持:
- 系统操作(版本查询、时间戳获取)
- 笔记本全生命周期管理(创建/打开/重命名/删除)
- 文档操作(Markdown导入导出、路径转换、批量移动)
- 块级精细化编辑(插入/追加/前置/更新/删除/移动)
- 高级功能(SQL查询、模板渲染、Pandoc格式转换、资源上传)
CLI工具集(8款独立脚本):list.py/read.py/search.py/create.py/delete.py/move.py/update.py/export.py,覆盖日常运维场景。
显著优点
- 功能完整:覆盖思源笔记95%以上的API端点,块级操作精度达到单个段落
- 工程化设计:自动重试(指数退避)、连接健康检查、操作日志记录
- 双模式友好:既满足开发者SDK集成需求,也提供运维友好的命令行工具
- 格式互通:原生支持Markdown/Kramdown/SQL,内置Pandoc桥接实现多格式转换
潜在局限
- 本地依赖:必须运行思源笔记桌面端/服务端,无法独立使用
- 端口动态性:SiYuan重启后端口可能变化(6806→34669等),需手动维护配置
- Token管理:API token需从GUI手动获取,暂无OAuth等自动化授权流程
- 网络隔离:仅支持localhost/内网访问,无外网API托管选项
适合人群
- 思源笔记重度用户,需批量处理笔记数据
- 个人知识管理(PKM)自动化爱好者
- 需要将思源笔记接入Obsidian/Notion等生态的桥接开发者
- 学术研究者的文献笔记批量处理场景
常规风险
- 误操作风险:
delete_block/remove_doc等操作不可逆,CLI工具提供--yes跳过确认开关需谨慎使用 - SQL注入:
query_sql方法虽为只读查询,但直接拼接SQL存在理论风险 - 端口暴露:若将SiYuan API绑定到0.0.0.0,局域网内无token校验的暴露风险
技能正文
name: "SiYuan Note" description: SiYuan Note (思源笔记) API client - Complete notebook, document and block management homepage: https://github.com/siyuan-note/siyuan api_docs: https://www.siyuan-note.club/apis version: "1.0.2" author: "weiwei" metadata: { "openclaw": { "emoji": "🧠", "requires": { "bins": ["python3"] }, "install": [{ "kind": "none", "label": "No external deps required" }], }, }
SiYuan Note (思源笔记)
A clean API client for SiYuan Note, providing access to your notes via the local HTTP API.
ClawHub: https://clawhub.ai/weiwei2027/siyuan
Install: clawhub install siyuan
Version: 1.0.1
Prerequisites
- SiYuan running with API enabled (Settings → About → API)
- API token from SiYuan settings
Configuration
-
Get your API token from SiYuan: Settings → About → API → Copy Token
-
Create/edit
~/.openclaw/workspace/skills/siyuan/config.yaml:
siyuan:
base_url: "http://127.0.0.1:6806" # Check SiYuan settings for actual port
token: "your-api-token-here" # Paste your token here
timeout: 30
retry: 3
Note: SiYuan may use different ports on restart (default 6806, but could be 34669, etc.). Check the current port in SiYuan settings.
Python Client API
Initialize Client
from siyuan_client import SiYuanClient
# Use config.yaml settings
client = SiYuanClient()
# Or explicit configuration
client = SiYuanClient(
base_url="http://127.0.0.1:6806",
token="your-token"
)
System Operations
# Get system version
version = client.system_version()
print(f"SiYuan v{version}")
# Get current time
timestamp = client.current_time()
Notebook Operations
# List all notebooks
notebooks = client.list_notebooks()
for nb in notebooks:
print(f"{nb['name']}: {nb['id']}")
# Create new notebook
new_nb = client.create_notebook("我的新项目")
# Open/close notebook (load/unload from memory)
client.open_notebook("notebook-id")
client.close_notebook("notebook-id")
# Rename notebook
client.rename_notebook("notebook-id", "新名称")
# Get/set notebook configuration
conf = client.get_notebook_conf("notebook-id")
client.set_notebook_conf("notebook-id", {"dailyNoteSavePath": "/daily"})
# Remove notebook
client.remove_notebook("notebook-id")
Document Operations
# Export document as Markdown
result = client.export_md_content("doc-id")
print(result['hPath']) # Human-readable path
print(result['content']) # Markdown content
# Create new document
new_doc = client.create_doc_with_md(
notebook_id="notebook-id",
path="folder/document-name", # Supports nested paths
markdown="# Title\n\nContent here"
)
# Rename document
client.rename_doc("notebook-id", "/old-path", "新标题")
client.rename_doc_by_id("doc-id", "新标题")
# Get document paths
hpath = client.get_hpath_by_id("doc-id") # Human-readable path
path_info = client.get_path_by_id("doc-id") # Storage path
ids = client.get_ids_by_hpath("notebook-id", "/人类可读路径")
# Move documents by ID
client.move_docs_by_id(
doc_ids=["doc-id-1", "doc-id-2"],
to_id="target-notebook-or-doc-id"
)
# Move documents by path
client.move_docs(
from_paths=["/path/to/doc1.sy", "/path/to/doc2.sy"],
to_notebook="target-notebook-id",
to_path="/subfolder"
)
# Remove document by notebook and path
client.remove_doc("notebook-id", "/path/to/doc.sy")
# Remove document by ID
client.remove_doc_by_id("doc-id")
Block Operations
# Insert blocks at specific position
blocks = client.insert_block(
data_type="markdown",
data="## New Section\n\nSome content",
parent_id="doc-id", # Optional: parent block/document
previous_id="block-id", # Optional: insert after this block
next_id="block-id" # Optional: insert before this block
)
# Prepend to beginning of document
blocks = client.prepend_block(
data_type="markdown",
data="# Title\n",
parent_id="doc-id"
)
# Append to end of document
blocks = client.append_block(
data_type="markdown",
data="\n---\nFooter here",
parent_id="doc-id"
)
# Update block content
client.update_block(
data_type="markdown",
data="Updated content",
block_id="block-id"
)
# Delete block
client.delete_block("block-id")
# Move block
client.move_block(
block_id="block-id",
previous_id="target-block-id", # Optional: insert after this block
parent_id="parent-block-id" # Optional: set parent (at least one required)
)
# Fold/unfold (collapse/expand) blocks
client.fold_block("block-id")
client.unfold_block("block-id")
# Transfer block references
client.transfer_block_ref(
from_id="source-block-id",
to_id="target-block-id",
ref_ids=["ref-1", "ref-2"] # Optional: specific refs to transfer
)
# Get block in Kramdown format
kramdown = client.get_block_kramdown("block-id")
# Get child blocks
children = client.get_child_blocks("container-block-id")
for child in children:
print(f"{child['type']}: {child['content'][:50]}")
Block Attributes
# Set custom attributes on a block
client.set_block_attrs("block-id", {
"custom-key": "value",
"custom-priority": "high",
"custom-status": "done"
})
# Get all attributes of a block
attrs = client.get_block_attrs("block-id")
print(attrs.get("custom-key"))
Assets
# Upload asset files
result = client.upload_asset(
file_paths=["/path/to/image.png", "/path/to/doc.pdf"],
assets_dir_path="/assets/"
)
print(result['succMap']) # Successfully uploaded files
print(result['errFiles']) # Failed uploads
SQL Operations
# Execute SQL query
results = client.query_sql("""
SELECT * FROM blocks
WHERE type = 'd'
ORDER BY updated DESC
LIMIT 10
""")
# Flush SQLite transaction to disk
client.flush_transaction()
Templates
# Render a template file
result = client.render_template(
doc_id="doc-id",
template_path="/data/templates/daily.md"
)
print(result['content'])
# Render Sprig template string
output = client.render_sprig('/daily note/{{now | date "2006/01"}}/{{now | date "2006-01-02"}}')
File Operations
# Read file content
content = client.get_file("/data/20210808180117-6v0mkxr/20200923234011-ieuun1p.sy")
# Create directory
client.put_file("/data/new-folder", is_dir=True)
# Upload file
with open("local-file.txt", "rb") as f:
client.put_file("/data/new-folder/file.txt", file_content=f.read())
# List directory
files = client.read_dir("/data/20210808180117-6v0mkxr")
for f in files:
print(f"{'[DIR]' if f['isDir'] else '[FILE]'} {f['name']}")
# Rename/move file
client.rename_file("/data/old-name.sy", "/data/new-name.sy")
# Remove file
client.remove_file("/data/unwanted-file.sy")
Export
# Export document as Markdown
result = client.export_md_content("doc-id")
print(result['hPath']) # Human-readable path
print(result['content']) # Markdown content
# Export multiple files/folders as zip
zip_path = client.export_resources(
paths=["/conf/appearance/boot", "/conf/appearance/langs"],
name="my-export"
)
print(f"Exported to: {zip_path}")
Conversion
# Run Pandoc conversion
# 1. Put input file
client.put_file("/temp/convert/pandoc/mydir/input.epub", file_content=epub_bytes)
# 2. Run conversion
work_dir = client.pandoc("mydir", ["--to", "markdown_strict", "input.epub", "-o", "output.md"])
# 3. Get output file
output = client.get_file("/temp/convert/pandoc/mydir/output.md")
Notifications
# Push message to SiYuan UI
msg_id = client.push_msg("Hello from API!")
# Push error message
err_id = client.push_err_msg("Something went wrong!", timeout=10000)
Network
# Forward HTTP request through SiYuan proxy
response = client.forward_proxy(
url="https://api.example.com/data",
method="GET",
headers=[{"Authorization": "Bearer token"}]
)
print(response['body'])
print(response['status'])
System
# Get boot progress
progress = client.boot_progress()
print(f"Boot: {progress['progress']}% - {progress['details']}")
# Get system version
version = client.system_version()
print(f"SiYuan v{version}")
# Get current time (milliseconds)
timestamp = client.current_time()
SQL Query
# Execute SQL query (read-only recommended)
results = client.query_sql("""
SELECT * FROM blocks
WHERE content LIKE '%关键词%'
ORDER BY updated DESC
LIMIT 10
""")
for block in results:
print(f"{block['content'][:100]}...")
CLI Tools
All tools are located in tools/ directory and depend on siyuan_client.py.
List
# List all notebooks
python3 tools/list.py --notebooks
# List documents in a notebook
python3 tools/list.py --docs "notebook-id"
# Output as JSON
python3 tools/list.py -n -j
Read
# Read document content
python3 tools/read.py 20240602141622-l7ou7t7
# Save to file
python3 tools/read.py 20240602141622-l7ou7t7 -o ~/doc.md
# Show document metadata
python3 tools/read.py 20240602141622-l7ou7t7 --info
Search
# Search by keyword
python3 tools/search.py "keyword"
# Limit results
python3 tools/search.py "keyword" -l 50
# Raw SQL query
python3 tools/search.py "SELECT * FROM blocks WHERE type='d' LIMIT 10" --sql
Export
# Export all notebooks
python3 tools/export.py -o ~/backup/
# Export specific notebook
python3 tools/export.py -n "工作" -o ~/backup/
# Export single document
python3 tools/export.py -d 20240602141622-l7ou7t7 -o ~/doc.md
Create
# Create notebook
python3 tools/create.py --notebook "New Project"
# Create document
python3 tools/create.py --doc notebook-id /readme "# Hello\n\nWorld"
# Create with nested path
python3 tools/create.py --doc notebook-id /folder/doc "## Title\nContent"
Delete
# Delete notebook
python3 tools/delete.py --notebook notebook-id
# Delete document
python3 tools/delete.py --doc doc-id
# Delete block
python3 tools/delete.py --block block-id
# Skip confirmation
python3 tools/delete.py --doc doc-id --yes
Move
# Move single document
python3 tools/move.py --doc doc-id --to-notebook target-nb-id
# Move multiple documents
python3 tools/move.py --docs id1 id2 id3 --to-notebook target-nb-id
# Move by path
python3 tools/move.py --from-paths /doc1.sy /doc2.sy --to-nb target-nb --to-path /folder/
Update
# Update a block
python3 tools/update.py --block block-id --markdown "New content"
# Append to document
python3 tools/update.py --append doc-id --markdown "\n\nFooter"
# Prepend to document
python3 tools/update.py --prepend doc-id --markdown "# Header\n"
# Insert block
python3 tools/update.py --insert "New paragraph" --parent doc-id
Safety Features
- ✅ All write operations are logged
- ✅ Automatic retry with exponential backoff
- ✅ Connection health checks
- ✅ Comprehensive error handling
- ✅ Read-only by default for queries
Troubleshooting
Connection Refused
- Check if SiYuan is running
- Verify API is enabled in Settings → About → API
- Check the correct port in config.yaml
Authentication Failed
- Get fresh token from SiYuan: Settings → About → API
- Update config.yaml with new token
Port Changes
SiYuan may use different ports on restart. Check current port:
ss -tlnp | grep SiYuan
Then update config.yaml accordingly.
API Reference
- Local API Documentation: See
API.mdin this directory (downloaded from official repo) - Online API Docs: https://www.siyuan-note.club/apis
- Official Repository: https://github.com/siyuan-note/siyuan
Changelog
v1.0.0 (2026-03-20)
- Added complete API client with automatic retry
- Added 8 CLI tools for all common operations
- Added bilingual documentation (Chinese/English)
- Added configuration file support
- Production-ready with comprehensive error handling
v0.5.0 (2026-03-18)
- Initial release
正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。