网宝
新闻中心 / / 正文

OpenClaw API 接口使用教程与开发示例

2026-03-04 10:19
技术部
← 返回

OpenClaw(前身为Clawdbot/Moltbot)核心是一个自托管的消息网关 + AI代理运行时,它的“API”主要体现在两个层面:

  1. Gateway暴露的WebSocket / HTTP API:用于外部程序/自定义客户端与OpenClaw通信(发送消息、接收回复、控制Agent等)。
  2. 插件/Channel/SDK开发接口:用于开发自定义渠道(Custom Channel)、Skills(技能)、Tools(工具)或扩展MCP多Agent协作。

官方文档(https://docs.openclaw.ai/)中,API部分主要集中在**Gateway API(端口默认18789)和插件开发SDK**。本文基于官方仓库(github.com/openclaw/openclaw)、docs.openclaw.ai及社区实践,提供最实用的API使用教程与代码示例。

一、OpenClaw Gateway API 概述

Gateway默认监听 **http://localhost:18789**(可通过`openclaw gateway --port xxxx`修改),暴露以下主要接口:

接口类型 路径/方式 主要功能 认证方式
WebSocket ws://localhost:18789/ws 实时双向通信(发送用户消息、接收Agent回复、状态推送) Bearer Token 或 Session ID
HTTP POST /api/v1/messages 发送单条消息(类似REST方式触发Agent) API Key 或 Bearer Token
HTTP GET /api/v1/status 查看Gateway/Agent运行状态 无(或配置后需Token)
HTTP POST /api/v1/agents/{agentId}/invoke 直接调用指定Agent(绕过聊天渠道) Bearer Token
HTTP GET /api/v1/channels 列出已配置渠道及状态 Bearer Token
 
 

获取API访问凭证(Token) 大多数接口需要认证。启动Gateway后,在终端运行:

Bash
 
openclaw token create --name "my-dev-client" --expires-in 30d
 
 

会输出类似:

text
 
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
 
 

保存这个Token,后续请求都带在Header:Authorization: Bearer <token>

二、基础使用:通过WebSocket与OpenClaw对话(推荐实时应用)

Node.js 示例(使用ws库)

JavaScript
 
// npm install ws
const WebSocket = require('ws');

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';  // 你的Bearer Token
const ws = new WebSocket('ws://localhost:18789/ws', {
  headers: { Authorization: `Bearer ${token}` }
});

ws.on('open', () => {
  console.log('已连接到OpenClaw Gateway');

  // 发送消息给默认Agent(或指定sessionId/agentId)
  ws.send(JSON.stringify({
    type: 'message',
    content: '帮我写一个Python函数计算斐波那契数列第n项(使用记忆化)',
    channel: 'api',           // 或你的自定义channel id
    metadata: { userId: 'dev-user-001' }
  }));
});

ws.on('message', (data) => {
  const msg = JSON.parse(data);
  console.log('收到回复:', msg.content);

  // msg 结构示例:
  // {
  //   type: 'response' | 'tool_call' | 'status' | 'error',
  //   content: string,
  //   agentId: string,
  //   sessionId: string,
  //   timestamp: number
  // }
});

ws.on('close', () => console.log('连接断开'));
ws.on('error', (err) => console.error('WebSocket错误:', err));
 
 

Python 示例(使用websocket-client)

Python
 
# pip install websocket-client
import websocket
import json

token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
ws = websocket.WebSocketApp(
    "ws://localhost:18789/ws",
    header=[f"Authorization: Bearer {token}"],
    on_message=lambda ws, msg: print("收到:", json.loads(msg)["content"]),
    on_open=lambda ws: ws.send(json.dumps({
        "type": "message",
        "content": "给我分析一下今天的Hacker News前5条热门",
        "channel": "api"
    }))
)

ws.run_forever()
 
 

三、REST方式触发Agent(适合Serverless / 定时任务)

cURL 示例

Bash
 
curl -X POST http://localhost:18789/api/v1/messages \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json" \
  -d '{
    "content": "自动在~/projects/my-repo创建新分支feature/api-integration,写一个Express中间件记录请求日志,然后commit并push",
    "agentId": "dev-coder",           // 可选,指定Agent
    "sessionId": "cron-job-20260306"  // 可选,自定义会话追踪
  }'
 
 

返回示例(同步等待完成时):

JSON
 
{
  "status": "completed",
  "finalReply": "已完成:分支创建、代码写入、commit & push成功。PR链接:https://github.com/xxx/pull/123",
  "toolCalls": [...],
  "durationMs": 28450
}
 
 

四、开发自定义Channel(最强大扩展方式)

OpenClaw所有聊天渠道(Telegram/WhatsApp等)都是基于插件SDK实现的。你可以开发自己的Channel来接入企业微信、钉钉、自定义WebHook、甚至你的App内聊天框。

步骤概要(详见 https://docs.openclaw.ai/plugins/channel-sdk 或 github.com/openclaw/openclaw/tree/main/packages/plugin-sdk):

  1. 创建插件项目:

    Bash
     
    npx create-openclaw-plugin my-custom-channel
     
     
  2. 实现核心接口(src/index.ts):

    TypeScript
     
    import { ChannelPlugin, Message } from '@openclaw/plugin-sdk';
    
    export default class MyCustomChannel implements ChannelPlugin {
      async sendMessage(to: string, msg: Message): Promise<void> {
        // 实现发送逻辑,例如调用你的API
        await fetch('https://your-app/api/send', {
          method: 'POST',
          body: JSON.stringify({ to, text: msg.content })
        });
      }
    
      // 接收外部消息 → 调用 onMessage 推给Gateway
      // 通常在构造函数中启动WebHook / 长轮询
    }
     
     
  3. 打包 & 安装:

    Bash
     
    npm run build
    openclaw channels install ./dist/my-custom-channel.plugin
     
     
  4. 在onboarding或config中启用你的channel。

五、开发自定义Skill / Tool(给Agent增加能力)

Skill本质是预设的Prompt模板 + Tool定义,Tool是可执行函数。

快速创建Skill示例(JSON格式,放在~/openclaw/skills/):

JSON
 
{
  "slug": "auto-deploy-vercel",
  "name": "一键Vercel部署",
  "description": "自动部署当前项目到Vercel预览环境",
  "prompt": "你现在是Vercel部署专家。步骤:1. 确认git状态 2. push main 3. 用Vercel CLI创建preview部署 4. 返回预览链接",
  "tools": [
    {
      "name": "run_vercel_deploy",
      "description": "执行vercel deploy --prebuilt",
      "parameters": { "type": "object", "properties": {} }
    }
  ]
}
 
 

然后在聊天中直接调用:@auto-deploy-vercel 部署我的Next.js项目

六、安全与最佳实践

  • 永远不要把主API Key放在Memory.md或普通会话中(2026.3+版本已加强沙箱,但仍需谨慎)
  • 使用专用Token给外部客户端,设置短过期时间
  • 生产环境建议反向代理(Nginx/Caddy)+ HTTPS + IP白名单
  • 高危操作开启PIN验证(config中security.requirePinFor: ["shell", "file_write"])
  • 监控日志:openclaw logs --level debug

七、总结:API让OpenClaw成为“可编程的AI中枢”

通过Gateway的WebSocket/REST API,你可以:

  • 把OpenClaw嵌入你的App / 网站 / 企业内部系统
  • 实现定时任务、Webhook触发、批量自动化
  • 开发专属渠道(企业微信、飞书内嵌、Slack私有命令)
  • 与其他系统深度集成(CI/CD、监控告警自动修复)

更多细节参考:

 

 

QQ客服 提交工单