Skip to main content
xbot
切换暗/亮/自动模式 切换暗/亮/自动模式 切换暗/亮/自动模式 返回首页

本文档的英文版本包含完整的代码示例和 API 参考。请参阅 English version 获取完整内容。

本文档提供 插件存储 的中文概览。详细的 API 参考和代码示例请参阅英文版本。

Every plugin gets a private key-value storage for persisting state across sessions.

Overview

Storage is file-based, using a JSON file per plugin:

~/.xbot/plugins/<plugin-id>/data/storage.json

The storage is loaded on plugin activation and persisted on every write using atomic write (tmp + rename).

API

Storage is accessed via PluginContext (requires storage permission):

type StorageAccessor interface {
    Get(key string) (string, bool)
    Set(key, value string) error
    Delete(key string) error
    Keys() []string
    Clear() error
}

Typed Helpers

PluginContext provides typed convenience methods:

// Integer storage
count, ok := ctx.StorageInt("counter")  // (int64, bool)

// Boolean storage
enabled, ok := ctx.StorageBool("enabled")  // (bool, bool)

// JSON storage (marshal/unmarshal)
ctx.StorageJSON("config", map[string]any{"theme": "dark"})

// JSON retrieval
var cfg map[string]any
ctx.StorageGetJSON("config", &cfg)

Usage Example

func (p *MyPlugin) Activate(ctx plugin.PluginContext) error {
    // Read a counter
    count, _ := ctx.StorageInt("call_count")
    count++
    
    // Store it back
    ctx.Storage().Set("call_count", strconv.FormatInt(count, 10))
    
    // Store structured data
    ctx.StorageJSON("last_run", map[string]any{
        "timestamp": time.Now().Unix(),
        "workDir":   ctx.WorkingDir(),
    })
    
    return nil
}

Implementation Details

  • File location: ~/.xbot/plugins/<id>/data/storage.json
  • File permissions: 0600 (owner read/write only)
  • Atomic writes: Uses tmp file + os.Rename for crash safety
  • Thread-safe: Protected by sync.RWMutex
  • Auto-load: Storage is loaded from disk on plugin activation
  • Failed parse: If the storage file is corrupted, the plugin starts fresh with an empty map

Storage vs Configuration

FeatureStorageConfiguration
Who writesPlugin codeUser (via settings UI)
MutabilityRead/write at runtimeRead-only at runtime
Locationdata/storage.jsonconfig.json
PermissionstorageNone (read-only)
Use casePlugin state, cachesUser preferences

See Also