前のページ

07. OpenClaw Skills 開発入門:最初のスキルを作ろう

本稿では最初の OpenClaw Skill の開発をステップバイステップで解説します。SKILL.md の構造解析から完全な例まで、スキル定義、トリガーワード設計、ツール統合、テスト・公開の全フローをカバーし、AI アシスタントにカスタム能力を追加する方法を学びます。

OpenClaw v2026.2 対応 | 本稿は基本的な Markdown とコマンドラインに精通しており、カスタムスキルを作成したい方を対象としています。

TL;DR: Skill の作成には SKILL.md ファイル1つで十分です。コアフィールド: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 簡潔な説明(1文)
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": "ja"
    }
  }
}
\`\`\`

## 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;
    
    // 条件に基づいてアドバイスを生成
    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 // 1日あたり8回の予報(3時間ごと)
      }
    });

    const data = response.data;
    
    // 日別にグループ化して日次サマリーを取得
    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

ベストプラクティス

ドキュメント規範

要件 説明
明確な説明 1文でスキルの機能を説明
十分な例 主要な使用シナリオをカバー
設定説明 設定手順を詳しく説明
エラー処理 よくあるエラーと解決策を列挙
バージョン更新 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 ベース

シリーズナビゲーション