为什么需要插件机制

OpenClaw 的核心设计哲学是 "核心稳定 + 边缘开放"。所有可能变化的部分(业务逻辑、协议解析、第三方集成)都应该做成插件,而核心 Runtime 永远保持精简。

本文会用一个"命令行天气预报"的小插件,带你走完插件开发全流程。

插件项目结构

weather-plugin/
├── go.mod
├── main.go
└── plugin.yaml        # 插件清单文件

步骤 1:初始化 Go 模块

mkdir weather-plugin && cd weather-plugin
go mod init github.com/yourname/weather-plugin
go get github.com/opencLaw/opencLaw/sdk/plugin

步骤 2:编写插件代码

// main.go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "os"

    "github.com/opencLaw/opencLaw/sdk/plugin"
)

type WeatherPlugin struct{}

type WeatherInput struct {
    City string `json:"city"`
}

type WeatherOutput struct {
    City        string  `json:"city"`
    Temperature float64 `json:"temperature"`
    Desc        string  `json:"description"`
}

func (p *WeatherPlugin) Name() string { return "weather" }

func (p *WeatherPlugin) Execute(in []byte) ([]byte, error) {
    var input WeatherInput
    if err := json.Unmarshal(in, &input); err != nil {
        return nil, err
    }
    if input.City == "" {
        return nil, fmt.Errorf("city is required")
    }

    apiKey := os.Getenv("WEATHER_API_KEY")
    url := fmt.Sprintf("https://api.qweather.com/v7/weather/now?location=%s&key=%s", input.City, apiKey)
    resp, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    out := WeatherOutput{
        City:        input.City,
        Temperature: 23.5,
        Desc:        "晴",
    }
    return json.Marshal(out)
}

func main() {
    plugin.Serve(&WeatherPlugin{})
}

步骤 3:编写插件清单

# plugin.yaml
name: weather
version: 1.0.0
author: yourname
description: 根据城市名查询实时天气
entry: ./weather-plugin
permissions:
  - network
  - env:WEATHER_API_KEY

步骤 4:构建与安装

opencLaw plugin build
opencLaw plugin install ./weather-plugin

安装后会自动加载到 Runtime,可以通过 CLI 调用:

opencLaw exec weather --city=Beijing
# 输出: {"city":"Beijing","temperature":23.5,"description":"晴"}

步骤 5:发布到插件市场(可选)

opencLaw plugin publish \
  --name=weather \
  --version=1.0.0 \
  --token=$OC_TOKEN

发布后其他用户即可通过 opencLaw plugin install weather 一键安装。

进阶:插件版本管理与热更新

OpenClaw 支持 插件热更新

opencLaw plugin update weather --version=1.1.0
# Runtime 会平滑切换,新请求走新插件,旧请求继续在旧实例中执行

也可以通过 API 触发:

runtime.UpdatePlugin("weather", "1.1.0")

调试技巧

  • 本地热加载:开发时使用 opencLaw plugin dev,源码改动自动重新编译。
  • 日志查看opencLaw logs --plugin=weather --tail=100
  • 性能分析:插件内置 pprof,开启 --pprof 后访问 http://localhost:6060/debug/pprof/

总结

通过本教程,你已经掌握了 OpenClaw 插件的完整生命周期:开发 → 构建 → 安装 → 调用 → 发布。插件机制是 OpenClaw 生态的根基——把核心稳定下来,把变化交给社区,这就是 OpenClaw 演进的动力。

实战作业

试着开发一个 translate 插件,要求:

  1. 接收 texttarget_lang 两个参数
  2. 调用翻译 API 返回结果
  3. 支持中英日三种语言

完成后,欢迎把你的插件链接发到评论区,我们会挑选优秀作品收录到社区精选插件列表。

延伸阅读