思源笔记 API 客户端 - 完整的笔记本、文档与块管理
西元注 (思源笔记). 西元注 (思源笔记). 清真API客户端,通过当地HTTP API提供访问您的笔记.是一项面向实际任务的技能,主要用于ClawHub: https://clawhub.ai/weiwe2027/siyuan.;Install: calphub sind siyuan.Vers.。
实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;
涉及批量任务时,还应保存进度,避免中断后重复操作。该技能适合用于一次性任务,也可以接入自动化工作流,与其他技能或上层代理配合完成更完整的业务链路;在组合使用时,应明确每一步的输入输出关系,并避免不同步骤之间出现参数冲突。
一款简洁的 SiYuan Note API 客户端,通过本地 HTTP API 访问您的笔记。
ClawHub: https://clawhub.ai/weiwei2027/siyuan
安装: clawhub install siyuan
版本: 1.0.1
从 SiYuan 获取您的 API token:设置 → 关于 → API → 复制 Token
创建或编辑 ~/.openclaw/workspace/skills/siyuan/config.yaml:
siyuan: base_url: "http://127.0.0.1:6806" # 请在 SiYuan 设置中确认实际端口 token: "your-api-token-here" # 在此处粘贴您的 token timeout: 30 retry: 3
注意:SiYuan 重启后可能使用不同端口(默认为 6806,但也可能是 34669 等)。请在 SiYuan 设置中确认当前端口。
from siyuan_client import SiYuanClient
# 使用 config.yaml 中的配置
client = SiYuanClient()
# 或显式指定配置
client = SiYuanClient(
base_url="http://127.0.0.1:6806",
token="your-token"
)
# 获取系统版本
version = client.system_version()
print(f"SiYuan v{version}")
# 获取当前时间戳
timestamp = client.current_time()
# 列出所有笔记本
notebooks = client.list_notebooks()
for nb in notebooks:
print(f"{nb['name']}: {nb['id']}")
# 创建新笔记本
new_nb = client.create_notebook("我的新项目")
# 打开/关闭笔记本(加载/卸载至内存)
client.open_notebook("notebook-id")
client.close_notebook("notebook-id")
# 重命名笔记本
client.rename_notebook("notebook-id", "新名称")
# 获取/设置笔记本配置
conf = client.get_notebook_conf("notebook-id")
client.set_notebook_conf("notebook-id", {"dailyNoteSavePath": "/daily"})
# 删除笔记本
client.remove_notebook("notebook-id")
# 导出文档为 Markdown 格式
result = client.export_md_content("doc-id")
print(result['hPath']) # 人类可读路径
print(result['content']) # Markdown 内容
# 创建新文档
new_doc = client.create_doc_with_md(
notebook_id="notebook-id",
path="folder/document-name", # 支持嵌套路径
markdown="# TitlennContent here"
)
# 重命名文档
client.rename_doc("notebook-id", "/old-path", "新标题")
client.rename_doc_by_id("doc-id", "新标题")
# 获取文档路径
hpath = client.get_hpath_by_id("doc-id") # 人类可读路径
path_info = client.get_path_by_id("doc-id") # 存储路径
ids = client.get_ids_by_hpath("notebook-id", "/人类可读路径")
# 按 ID 移动文档
client.move_docs_by_id(
doc_ids=["doc-id-1", "doc-id-2"],
to_id="target-notebook-or-doc-id"
)
# 按路径移动文档
client.move_docs(
from_paths=["/path/to/doc1.sy", "/path/to/doc2.sy"],
to_notebook="target-notebook-id",
to_path="/subfolder"
)
# 按笔记本和路径删除文档
client.remove_doc("notebook-id", "/path/to/doc.sy")
# 按 ID 删除文档
client.remove_doc_by_id("doc-id")
# 在指定位置插入块
blocks = client.insert_block(
data_type="markdown",
data="## New SectionnnSome content",
parent_id="doc-id", # 可选:父块/文档 ID
previous_id="block-id", # 可选:插入到该块之后
next_id="block-id" # 可选:插入到该块之前
)
# 在文档开头前置块
blocks = client.prepend_block(
data_type="markdown",
data="# Titlen",
parent_id="doc-id"
)
# 在文档末尾追加块
blocks = client.append_block(
data_type="markdown",
data="n---nFooter here",
parent_id="doc-id"
)
# 更新块内容
client.update_block(
data_type="markdown",
data="Updated content",
block_id="block-id"
)
# 删除块
client.delete_block("block-id")
# 移动块
client.move_block(
block_id="block-id",
previous_id="target-block-id", # 可选:插入到该块之后
parent_id="parent-block-id" # 可选:设置父块(至少需提供一项)
)
# 折叠/展开(收起/展开)块
client.fold_block("block-id")
client.unfold_block("block-id")
# 转移块引用
client.transfer_block_ref(
from_id="source-block-id",
to_id="target-block-id",
ref_ids=["ref-1", "ref-2"] # 可选:指定要转移的引用
)
# 获取块的 Kramdown 格式内容
kramdown = client.get_block_kramdown("block-id")
# 获取子块列表
children = client.get_child_blocks("container-block-id")
for child in children:
print(f"{child['type']}: {child['content'][:50]}")
# 为块设置自定义属性
client.set_block_attrs("block-id", {
"custom-key": "value",
"custom-priority": "high",
"custom-status": "done"
})
# 获取块的所有属性
attrs = client.get_block_attrs("block-id")
print(attrs.get("custom-key"))
# 上传资源文件
result = client.upload_asset(
file_paths=["/path/to/image.png", "/path/to/doc.pdf"],
assets_dir_path="/assets/"
)
print(result['succMap']) # 成功上传的文件
print(result['errFiles']) # 上传失败的文件
# 执行 SQL 查询
results = client.query_sql("""
SELECT * FROM blocks
WHERE type = 'd'
ORDER BY updated DESC
LIMIT 10
""")
# 将 SQLite 事务刷新至磁盘
client.flush_transaction()
# 渲染模板文件
result = client.render_template(
doc_id="doc-id",
template_path="/data/templates/daily.md"
)
print(result['content'])
# 渲染 Sprig 模板字符串
output = client.render_sprig('/daily note/{{now | date "2006/01"}}/{{now | date "2006-01-02"}}')
# 读取文件内容
content = client.get_file("/data/20210808180117-6v0mkxr/20200923234011-ieuun1p.sy")
# 创建目录
client.put_file("/data/new-folder", is_dir=True)
# 上传文件
with open("local-file.txt", "rb") as f:
client.put_file("/data/new-folder/file.txt", file_content=f.read())
# 列出目录内容
files = client.read_dir("/data/20210808180117-6v0mkxr")
for f in files:
print(f"{'[DIR]' if f['isDir'] else '[FILE]'} {f['name']}")
# 重命名/移动文件
client.rename_file("/data/old-name.sy", "/data/new-name.sy")
# 删除文件
client.remove_file("/data/unwanted-file.sy")
# 导出文档为 Markdown 格式
result = client.export_md_content("doc-id")
print(result['hPath']) # 人类可读路径
print(result['content']) # Markdown 内容
# 将多个文件/文件夹打包导出为 zip
zip_path = client.export_resources(
paths=["/conf/appearance/boot", "/conf/appearance/langs"],
name="my-export"
)
print(f"导出至:{zip_path}")
# 执行 Pandoc 转换
# 1. 上传输入文件
client.put_file("/temp/convert/pandoc/mydir/input.epub", file_content=epub_bytes)
# 2. 运行转换命令
work_dir = client.pandoc("mydir", ["--to", "markdown_strict", "input.epub", "-o", "output.md"])
# 3. 获取输出文件
output = client.get_file("/temp/convert/pandoc/mydir/output.md")
# 向 SiYuan UI 推送消息
msg_id = client.push_msg("Hello from API!")
# 推送错误消息
err_id = client.push_err_msg("Something went wrong!", timeout=10000)
# 通过 SiYuan 代理转发 HTTP 请求
response = client.forward_proxy(
url="https://api.example.com/data",
method="GET",
headers=[{"Authorization": "Bearer token"}]
)
print(response['body'])
print(response['status'])
# 获取启动进度
progress = client.boot_progress()
print(f"启动:{progress['progress']}% - {progress['details']}")
# 获取系统版本
version = client.system_version()
print(f"SiYuan v{version}")
# 获取当前时间(毫秒级时间戳)
timestamp = client.current_time()
# 执行 SQL 查询(建议仅用于只读操作)
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]}...")
所有工具均位于 tools/ 目录下,并依赖 siyuan_client.py。
# 列出所有笔记本 python3 tools/list.py --notebooks # 列出某笔记本中的文档 python3 tools/list.py --docs "notebook-id" # 以 JSON 格式输出 python3 tools/list.py -n -j
# 读取文档内容 python3 tools/read.py 20240602141622-l7ou7t7 # 保存至本地文件 python3 tools/read.py 20240602141622-l7ou7t7 -o ~/doc.md # 显示文档元信息 python3 tools/read.py 20240602141622-l7ou7t7 --info
# 按关键词搜索 python3 tools/search.py "keyword" # 限制结果数量 python3 tools/search.py "keyword" -l 50 # 执行原始 SQL 查询 python3 tools/search.py "SELECT * FROM blocks WHERE type='d' LIMIT 10" --sql
# 导出全部笔记本 python3 tools/export.py -o ~/backup/ # 导出指定笔记本 python3 tools/export.py -n "工作" -o ~/backup/ # 导出单个文档 python3 tools/export.py -d 20240602141622-l7ou7t7 -o ~/doc.md
# 创建笔记本 python3 tools/create.py --notebook "New Project" # 创建文档 python3 tools/create.py --doc notebook-id /readme "# HellonnWorld" # 创建嵌套路径下的文档 python3 tools/create.py --doc notebook-id /folder/doc "## TitlenContent"
# 删除笔记本 python3 tools/delete.py --notebook notebook-id # 删除文档 python3 tools/delete.py --doc doc-id # 删除块 python3 tools/delete.py --block block-id # 跳过确认提示 python3 tools/delete.py --doc doc-id --yes
# 移动单个文档 python3 tools/move.py --doc doc-id --to-notebook target-nb-id # 移动多个文档 python3 tools/move.py --docs id1 id2 id3 --to-notebook target-nb-id # 按路径移动文档 python3 tools/move.py --from-paths /doc1.sy /doc2.sy --to-nb target-nb --to-path /folder/
# 更新块内容 python3 tools/update.py --block block-id --markdown "New content" # 向文档末尾追加内容 python3 tools/update.py --append doc-id --markdown "nnFooter" # 向文档开头前置内容 python3 tools/update.py --prepend doc-id --markdown "# Headern" # 插入新块 python3 tools/update.py --insert "New paragraph" --parent doc-id
SiYuan 重启后可能使用不同端口。可通过以下命令查看当前端口:
ss -tlnp | grep SiYuan
然后相应更新 config.yaml。
API.md(从官方仓库下载)相关专题
热门下载
相关下载
精品课程
共6课时 | 54.7万人学习
共89课时 | 134.1万人学习
共49课时 | 82.6万人学习