Skip to content

Skill 开发实战:从零开发一个天气查询 Skill

手把手教你开发第一个 OpenClaw Skill

🎯 目标

开发一个天气预报 Skill,能够:

  • 查询任意城市天气
  • 返回温度、湿度、风力等信息

📁 项目结构

my-weather-skill/
├── index.js       # Skill 主文件
├── package.json  # 依赖配置
└── README.md     # 说明文档

🔧 开始开发

1. 创建项目

bash
mkdir my-weather-skill
cd my-weather-skill
npm init -y

2. 安装依赖

bash
npm install axios

3. 编写 Skill 代码

javascript
// index.js
import axios from 'axios';

export default {
  // Skill 名称
  name: 'weather',
  
  // Skill 描述
  description: '查询指定城市的天气情况',
  
  // 参数定义
  params: {
    city: {
      type: 'string',
      required: true,
      description: '城市名称,如:北京、上海'
    }
  },
  
  // 处理函数
  async handle(context, params) {
    const { city } = params;
    
    try {
      // 调用天气 API(这里以免费 API 为例)
      const response = await axios.get(
        `https://api.example.com/weather?city=${city}`
      );
      
      const data = response.data;
      
      // 返回格式化结果
      return {
        success: true,
        message: `🌤️ ${city}今日天气`,
        data: {
          temp: data.temperature,
          weather: data.condition,
          humidity: data.humidity,
          wind: data.wind_speed
        }
      };
    } catch (error) {
      return {
        success: false,
        message: `查询失败:${error.message}`
      };
    }
  }
};

🧪 测试 Skill

本地测试

bash
# 在 OpenClaw 项目中测试
openclaw test skill ./my-weather-skill

手动测试

javascript
// 测试代码
const weatherSkill = require('./index.js');

weatherSkill.handle(null, { city: '北京' })
  .then(result => console.log(result));

📦 发布 Skill

本地使用

yaml
# config.yaml
agents:
  my-agent:
    skills:
      - path: ./my-weather-skill

发布到社区

bash
# 打包
npm pack

# 提交到 Skill 市场
openclaw publish ./my-weather-skill

🎉 进阶扩展

添加更多功能

javascript
// 支持预报
params: {
  city: { type: 'string', required: true },
  days: { 
    type: 'number', 
    required: false, 
    default: 1,
    description: '预报天数,1-7'
  }
}

添加错误处理

javascript
// 输入验证
if (!city || city.length < 2) {
  return {
    success: false,
    message: '请输入有效的城市名称'
  };
}

📚 完整代码

查看完整示例:https://github.com/openclaw/openclaw/tree/main/examples/weather-skill


有问题?在 Discord 提问!

养虾俱乐部 - OpenClaw 中文社区