返回

07. OpenClaw Skills 开发入门:打造你的第一个技能

本文手把手教你开发第一个 OpenClaw Skill。从 SKILL.md 结构解析到完整示例,涵盖技能定义、触发词设计、工具集成、测试发布全流程,帮助你为 AI 助手添加自定义能力。

适用于 OpenClaw v2026.2 | 本文假设你熟悉基本 Markdown 和命令行,想创建自定义技能。

TL;DR: 创建 Skill 只需一个 SKILL.md 文件。核心字段:nameversiontriggers(触发词)、tools(工具列表)。放在 ~/.openclaw/workspace/skills/<name>/SKILL.md。触发词要具体避免冲突。发布到 ClawHub:openclaw skill publish <name>。包含安全扫描和权限控制。

开发环境准备

前置要求

要求 说明
OpenClaw 已安装并运行
文本编辑器 VS Code 或任意编辑器
基础 Markdown SKILL.md 使用 Markdown 格式
API 文档 如需集成外部服务,准备 API 文档

创建技能目录

# 创建技能目录
mkdir -p ~/.openclaw/workspace/skills/weather-api

# 进入目录
cd ~/.openclaw/workspace/skills/weather-api

# 创建基本文件
touch SKILL.md
touch README.md
touch config.json.example

目录结构

weather-api/
├── SKILL.md              # 技能定义(必需)
├── README.md             # 说明文档(推荐)
├── config.json.example   # 配置示例(可选)
├── src/                  # 源代码(可选)
│   └── index.js
└── package.json          # 依赖声明(可选)

SKILL.md 结构详解

基本结构

---
# Frontmatter:元数据
name: skill-name
version: 1.0.0
author: your-name
description: Brief description
triggers:
  - trigger-1
  - trigger-2
dependencies: []
tools: []
---

# Skill Title

Detailed description...

## Features
## Setup
## Usage Examples
## Configuration
## Notes

Frontmatter 字段

字段 必需 说明
name 技能唯一标识,小写字母和连字符
version 语义化版本号
author 作者名称或组织
description 简短描述(一句话)
triggers 触发词列表
dependencies ⚠️ 依赖的其他技能
tools ⚠️ 提供的工具列表

触发词设计

触发词是 Agent 识别技能的关键:

triggers:
  - weather
  - 天气
  - forecast
  - 气温
  - temperature
  - rain
  - 下雨
  - umbrella
  - 雨伞

设计原则

原则 说明 示例
具体性 避免过于通用的词 gmail-sendsend
多语言 支持中英文 weather 天气
场景化 包含使用场景 check-weather weather-tomorrow
无冲突 检查与现有技能冲突 openclaw skill search weather

实战:开发天气查询技能

需求分析

我们要开发一个天气查询技能,功能包括:

  1. 查询当前天气
  2. 查询未来几天预报
  3. 支持中英文城市名
  4. 提供穿衣建议

完整 SKILL.md

---
name: weather-api
version: 1.0.0
author: your-name
description: Query weather information from OpenWeatherMap API
triggers:
  - weather
  - 天气
  - forecast
  - 预报
  - temperature
  - 气温
  - rain
  - 下雨
  - umbrella
  - 雨伞
dependencies: []
tools:
  - weather_current
  - weather_forecast
---

# Weather API Skill

Query weather information for any city worldwide. Provides current weather and forecasts with practical suggestions.

## Features

- **Current Weather**: Get real-time weather conditions
- **Forecast**: 5-day weather forecast
- **Multi-language**: Support for city names in multiple languages
- **Smart Suggestions**: Clothing and activity recommendations

## Setup

### 1. Get API Key

1. Visit [OpenWeatherMap](https://openweathermap.org/api)
2. Sign up for a free account
3. Generate an API key

### 2. Configure the Skill

Set the environment variable:

\`\`\`bash
export OPENWEATHER_API_KEY="your-api-key-here"
\`\`\`

Or add to your OpenClaw config:

\`\`\`json
{
  "skills": {
    "weather-api": {
      "apiKey": "your-api-key-here",
      "units": "metric",
      "lang": "zh_cn"
    }
  }
}
\`\`\`

## Usage Examples

### Current Weather

User: "北京今天天气怎么样"
User: "What's the weather in Tokyo"
User: "Check weather for Shanghai"

Action:
1. Parse city name from user message
2. Call weather_current tool with city parameter
3. Format and return weather information

### Weather Forecast

User: "明天会下雨吗"
User: "3天天气预报 for New York"
User: "周末天气怎么样"

Action:
1. Parse city name and days from user message
2. Call weather_forecast tool
3. Format forecast data into readable summary

### Smart Suggestions

User: "今天需要带伞吗"
User: "穿什么衣服合适"
User: "适合户外运动吗"

Action:
1. Get current weather
2. Analyze conditions (rain, temperature, UV)
3. Provide practical suggestions

## Tools

### weather_current

Get current weather for a city.

**Parameters:**
- `city` (string, required): City name, can be in any language
- `units` (string, optional): "metric", "imperial", or "kelvin". Default: "metric"
- `lang` (string, optional): Language code. Default: "zh_cn"

**Returns:**
\`\`\`json
{
  "city": "Beijing",
  "country": "CN",
  "temperature": 25,
  "feels_like": 27,
  "humidity": 65,
  "wind_speed": 12,
  "condition": "Partly cloudy",
  "icon": "02d",
  "suggestion": "Light jacket recommended, no rain expected"
}
\`\`\`

### weather_forecast

Get weather forecast for up to 5 days.

**Parameters:**
- `city` (string, required): City name
- `days` (number, optional): Number of days (1-5). Default: 3
- `units` (string, optional): Temperature units

**Returns:**
\`\`\`json
{
  "city": "Beijing",
  "forecast": [
    {
      "date": "2026-02-27",
      "temp_high": 28,
      "temp_low": 18,
      "condition": "Sunny",
      "rain_chance": 0
    },
    ...
  ]
}
\`\`\`

## Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | string | - | OpenWeatherMap API key |
| `units` | string | "metric" | Temperature units |
| `lang` | string | "zh_cn" | Language for descriptions |
| `cache_ttl` | number | 600 | Cache duration in seconds |

## Error Handling

The skill handles common errors:

- **City not found**: Suggests similar city names
- **API key invalid**: Prompts user to check configuration
- **Rate limit**: Queues request and retries
- **Network error**: Falls back to cached data if available

## Notes

- Free tier allows 1000 requests/day
- City names support Chinese: "北京", "上海", "广州"
- Results are cached for 10 minutes by default
- Consider upgrading to paid tier for more frequent updates

工具实现(可选)

如果你的技能需要执行具体操作,可以添加工具实现。

简单方式:使用内置工具

OpenClaw 内置了 web_searchread 工具,可以直接在 SKILL.md 中描述如何使用:

## Implementation Notes

To get weather data:

1. Use `web_search` tool to find weather API
2. Use `read` tool to fetch JSON response
3. Parse and format the data

Example search query: "weather API Beijing current temperature"

高级方式:自定义工具脚本

创建 src/index.js

// src/index.js
const axios = require('axios');

const OPENWEATHER_BASE_URL = 'https://api.openweathermap.org/data/2.5';

async function weather_current({ city, units = 'metric', lang = 'zh_cn' }, config) {
  const apiKey = config.apiKey || process.env.OPENWEATHER_API_KEY;
  
  if (!apiKey) {
    throw new Error('OpenWeatherMap API key not configured');
  }

  try {
    const response = await axios.get(`${OPENWEATHER_BASE_URL}/weather`, {
      params: {
        q: city,
        appid: apiKey,
        units,
        lang
      }
    });

    const data = response.data;
    
    // Generate suggestion based on conditions
    let suggestion = '';
    if (data.rain || data.weather[0].main === 'Rain') {
      suggestion = 'Bring an umbrella, rain expected';
    } else if (data.main.temp < 15) {
      suggestion = 'Wear warm clothing, temperature is low';
    } else if (data.main.temp > 30) {
      suggestion = 'Stay hydrated, high temperature';
    } else {
      suggestion = 'Pleasant weather, enjoy your day';
    }

    return {
      city: data.name,
      country: data.sys.country,
      temperature: data.main.temp,
      feels_like: data.main.feels_like,
      humidity: data.main.humidity,
      wind_speed: data.wind.speed,
      condition: data.weather[0].description,
      icon: data.weather[0].icon,
      suggestion
    };
  } catch (error) {
    if (error.response?.status === 404) {
      throw new Error(`City "${city}" not found. Please check the spelling.`);
    }
    throw error;
  }
}

async function weather_forecast({ city, days = 3, units = 'metric' }, config) {
  const apiKey = config.apiKey || process.env.OPENWEATHER_API_KEY;
  
  if (!apiKey) {
    throw new Error('OpenWeatherMap API key not configured');
  }

  try {
    const response = await axios.get(`${OPENWEATHER_BASE_URL}/forecast`, {
      params: {
        q: city,
        appid: apiKey,
        units,
        cnt: days * 8 // 8 forecasts per day (every 3 hours)
      }
    });

    const data = response.data;
    
    // Group by day and get daily summary
    const dailyForecasts = {};
    data.list.forEach(item => {
      const date = item.dt_txt.split(' ')[0];
      if (!dailyForecasts[date]) {
        dailyForecasts[date] = {
          temp_high: item.main.temp_max,
          temp_low: item.main.temp_min,
          conditions: [item.weather[0].main],
          rain_chance: item.pop * 100
        };
      } else {
        dailyForecasts[date].temp_high = Math.max(dailyForecasts[date].temp_high, item.main.temp_max);
        dailyForecasts[date].temp_low = Math.min(dailyForecasts[date].temp_low, item.main.temp_min);
        if (!dailyForecasts[date].conditions.includes(item.weather[0].main)) {
          dailyForecasts[date].conditions.push(item.weather[0].main);
        }
        dailyForecasts[date].rain_chance = Math.max(dailyForecasts[date].rain_chance, item.pop * 100);
      }
    });

    return {
      city: data.city.name,
      forecast: Object.entries(dailyForecasts)
        .slice(0, days)
        .map(([date, info]) => ({
          date,
          temp_high: Math.round(info.temp_high),
          temp_low: Math.round(info.temp_low),
          condition: info.conditions.join('/'),
          rain_chance: Math.round(info.rain_chance)
        }))
    };
  } catch (error) {
    if (error.response?.status === 404) {
      throw new Error(`City "${city}" not found. Please check the spelling.`);
    }
    throw error;
  }
}

module.exports = {
  weather_current,
  weather_forecast
};

package.json

{
  "name": "weather-api",
  "version": "1.0.0",
  "description": "Weather API skill for OpenClaw",
  "main": "src/index.js",
  "dependencies": {
    "axios": "^1.6.0"
  },
  "openclaw": {
    "skill": "weather-api",
    "tools": ["weather_current", "weather_forecast"]
  }
}

测试技能

本地测试

# 验证 SKILL.md 语法
openclaw skill validate weather-api

# 输出示例:
# ✅ Frontmatter valid
# ✅ Triggers defined
# ✅ Description present
# ✅ Tools documented

# 加载技能
openclaw skill load weather-api

# 测试技能
openclaw agent --message "北京今天天气怎么样"

# 应该看到天气信息

调试模式

# 启用调试日志
openclaw gateway --verbose --filter skill:weather-api

# 查看技能加载日志
openclaw logs --skill weather-api

测试场景

测试场景 输入 预期输出
中文城市 “北京天气” 北京天气信息
英文城市 “Weather in Tokyo” 东京天气信息
预报查询 “明天会下雨吗” 明天天气预报
穿衣建议 “今天穿什么” 基于天气的建议
错误处理 “xxx天气” 城市未找到提示

发布技能

准备发布

  1. 完善文档:确保 README.md 完整
  2. 添加示例:提供使用示例
  3. 测试充分:覆盖各种边界情况
  4. 清理敏感信息:移除 API Key 等

发布到 GitHub

# 初始化 Git
git init
git add .
git commit -m "Initial release of weather-api skill"

# 推送到 GitHub
git remote add origin https://github.com/your-username/weather-api.git
git push -u origin main

# 创建发布标签
git tag v1.0.0
git push origin v1.0.0

提交到 ClawHub

# 发布到 ClawHub
openclaw skill publish weather-api

# 输出示例:
# Validating skill...
# ✅ Validation passed
# Publishing to ClawHub...
# ✅ Published successfully!
# 
# Your skill is now available at:
# https://clawhub.com/skills/weather-api

README.md 模板

# Weather API Skill for OpenClaw

Query weather information from OpenWeatherMap API.

## Features

- Current weather conditions
- 5-day weather forecast
- Multi-language city support
- Smart clothing suggestions

## Installation

\`\`\`bash
openclaw skill install weather-api
\`\`\`

## Configuration

Set your OpenWeatherMap API key:

\`\`\`bash
export OPENWEATHER_API_KEY="your-api-key"
\`\`\`

Or in OpenClaw config:

\`\`\`json
{
  "skills": {
    "weather-api": {
      "apiKey": "your-api-key"
    }
  }
}
\`\`\`

## Usage

Just ask about the weather:

- "北京今天天气怎么样"
- "What's the weather in Tokyo"
- "明天会下雨吗"
- "今天需要带伞吗"

## Requirements

- OpenWeatherMap API key (free tier: 1000 requests/day)
- Internet connection

## License

MIT

高级技巧

条件触发

根据上下文决定是否触发:

## Advanced Triggers

This skill is triggered when:
1. User mentions weather-related keywords
2. User asks about temperature or conditions
3. User needs outdoor activity suggestions

Not triggered when:
- Weather is mentioned metaphorically ("I'm under the weather")
- User is asking about CPU temperature or other technical metrics

上下文记忆

在 SKILL.md 中添加上下文处理:

## Context Handling

When user asks "What about tomorrow?" after a weather query:
1. Check previous context for city name
2. Use the same city for forecast query

When user asks "And in Shanghai?" after querying another city:
1. Parse the new city name
2. Compare weather between both cities

链式技能

与其他技能协作:

## Skill Integration

This skill works well with:
- **calendar**: Suggest events based on weather
- **travel**: Provide weather for travel destinations
- **clothing**: Recommend outfits based on temperature

Example workflow:
User: "Planning a trip to Tokyo next week"
1. Travel skill: Parse destination and dates
2. Weather skill: Get Tokyo forecast
3. Calendar skill: Check existing events
4. Combined response: Trip summary with weather

错误恢复

优雅处理错误:

## Error Recovery

When API fails:
1. Check cache for recent data
2. Inform user about the issue
3. Offer alternatives:
   - "I couldn't get live weather data. Want me to try again?"
   - "The weather service is temporarily unavailable. Would you like a general forecast?"

When city not found:
1. Suggest similar city names
2. Ask for clarification
3. Use geolocation if available

最佳实践

文档规范

要求 说明
描述清晰 一句话说明技能功能
示例充分 覆盖主要使用场景
配置说明 详细说明配置步骤
错误处理 列出常见错误和解决方案
版本更新 维护 CHANGELOG

安全考虑

## Security Notes

- Never hardcode API keys in SKILL.md
- Use environment variables or config files
- Validate and sanitize user input
- Rate limit API calls
- Log errors without exposing sensitive data

性能优化

## Performance Tips

- Cache API responses (10-minute default)
- Use async operations for multiple requests
- Minimize tool calls by batching
- Use compressed responses when available

小结

Skills 开发的核心是:

  • SKILL.md 是灵魂:定义清晰、描述准确、示例充分
  • 触发词是关键:设计合理、避免冲突、覆盖场景
  • 工具是能力:实现完整、错误处理、性能优化
  • 文档是桥梁:帮助用户理解和使用你的技能

通过本篇的学习,你已经掌握了 Skills 开发的基础知识,可以开始为 OpenClaw 创建自定义技能了。


本篇小结

  • 理解了 SKILL.md 的结构和字段
  • 学会了触发词设计原则
  • 掌握了工具实现方法
  • 了解了测试和发布流程
  • 学习了高级技巧和最佳实践

更新记录

  • 2026-02-26:初版发布,基于 OpenClaw v2026.2

系列导航