数据存储
插件常见的持久化需求包括用户偏好、会话状态、缓存、导出文件、模型文件和日志。当前主要通过两种方式实现:
plugin.store— KV 存储,适合结构化小型数据plugin.get_plugin_data_dir()— 插件专属数据目录,适合文件型数据
TIP
plugin.get_plugin_path() 是旧接口,保留作兼容用途。新插件开发请使用 plugin.get_plugin_data_dir()。
存储方式选择
| 需求 | 推荐方式 |
|---|---|
| 用户偏好、会话状态、小型配置 | plugin.store |
| 文件、缓存、日志、导出物、模型文件 | plugin.get_plugin_data_dir() |
判断原则:需要保存的是"字段"时用 plugin.store,需要保存的是"文件"时用 plugin.get_plugin_data_dir()。
plugin.store
底层为 KV 存储,支持按会话、用户或插件全局三个维度隔离数据。
基本示例
python
import json
user_prefs = {"theme": "dark", "notifications": True}
await plugin.store.set(
user_key=_ctx.from_user_id,
store_key="preferences",
value=json.dumps(user_prefs, ensure_ascii=False),
)
prefs_str = await plugin.store.get(
user_key=_ctx.from_user_id,
store_key="preferences",
)
if prefs_str:
prefs = json.loads(prefs_str)三种常见作用域
chat_key=...:会话级数据user_key=...:用户级数据- 不传
chat_key/user_key:插件全局数据
TIP
复杂对象序列化为 JSON 后再存入 KV,不要直接存入大文件或二进制数据。
plugin.get_plugin_data_dir()
返回插件专属的数据目录(Path 对象),由插件自行管理子目录结构。常见子目录约定:
cache/— 临时缓存logs/— 日志文件exports/— 导出产物models/— 模型文件
示例:写入缓存文件
python
import json
data_dir = plugin.get_plugin_data_dir()
cache_dir = data_dir / "cache"
cache_dir.mkdir(parents=True, exist_ok=True)
cache_file = cache_dir / "summary.json"
cache_file.write_text(
json.dumps({"ok": True, "source": "demo"}, ensure_ascii=False, indent=2),
encoding="utf-8",
)示例:写入导出结果
python
exports_dir = plugin.get_plugin_data_dir() / "exports"
exports_dir.mkdir(parents=True, exist_ok=True)
report_file = exports_dir / "daily_report.md"
report_file.write_text("# 今日报告\n\n任务执行完成。", encoding="utf-8")与文件交互的关系
插件数据目录解决「插件自己把文件存在哪里」。文件交互 解决「文件如何在插件与 AI 沙盒之间流转」。两者职责不同,通常配合使用。
