Назад

07. OpenClaw Skills: разработка навыков — создаём первый навык

Пошаговое руководство по созданию первого навыка OpenClaw. От разбора структуры SKILL.md до полного примера: определение навыка, проектирование триггеров, интеграция инструментов, тестирование и публикация — всё для расширения возможностей AI-ассистента.

Для OpenClaw v2026.2 | Предполагается знание базового Markdown и командной строки для создания кастомных навыков.

TL;DR: Для создания Skill достаточно одного файла SKILL.md. Основные поля: name, version, triggers (триггеры), 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: Краткое описание
triggers:
  - trigger-1
  - trigger-2
dependencies: []
tools: []
---

# Заголовок навыка

Подробное описание...

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

Поля Frontmatter

Поле Обязательно Описание
name Уникальный идентификатор навыка, строчные буквы и дефисы
version Семантическая версия
author Имя автора или организации
description Краткое описание (одна фраза)
triggers Список триггеров
dependencies ⚠️ Зависимости от других навыков
tools ⚠️ Список предоставляемых инструментов

Проектирование триггеров

Триггеры — ключ к распознаванию навыка агентом:

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-day forecast 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_search и read, их использование можно описать прямо в 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 // 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

Рекомендации

Стандарты документации

Требование Описание
Понятное описание Кратко опишите назначение навыка
Достаточно примеров Покройте основные сценарии
Описание конфигурации Подробно опишите шаги настройки
Обработка ошибок Перечислите типичные ошибки и решения
Обновления версий Ведите 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

Навигация по серии: