开发一个天气查询技能 – 完整教程

    开发一个天气查询技能 – 完整教程

    本文带你从零开始开发一个完整的天气查询技能,调用和风天气 API 获取天气数据。看完你就掌握了 OpenClaw 技能开发的完整流程。

    最终效果

    开发完成后,AI 就能回答你:”北京今天天气怎么样?”,并给出准确的天气信息。

    准备工作

    1. 注册和风天气开发者账号:https://dev.qweather.com/
    2. 获取你的 API Key(免费额度足够个人使用)
    3. 确认你已经了解 OpenClaw 技能开发的基本概念

    步骤 1: 创建技能目录

    mkdir -p ~/.openclaw/workspace/skills/weather
    cd ~/.openclaw/workspace/skills/weather

    创建两个必需文件:

    touch SKILL.md
    touch index.js

    步骤 2: 编写 SKILL.md

    # 天气查询
    
    查询指定城市的当前天气和未来天气预报。
    
    ## 可用工具
    
    ### get_current_weather(city: string)
    查询指定城市的当前天气。
    
    **参数:**
    - city: string - 城市名称,比如 "北京"、"上海"
    
    **返回:** JSON 格式的天气信息

    记住:SKILL.md 是给 AI 看的,要简洁清晰。

    步骤 3: 编写技能代码

    编辑 index.js

    const https = require('https');
    
    // 从环境变量读取 API Key
    const QWEATHER_API_KEY = process.env.QWEATHER_API_KEY;
    
    async function getCurrentWeather(city) {
      // 第一步:获取城市 ID
      const locationUrl = `https://geoapi.qweather.com/v2/city/lookup?location=${encodeURIComponent(city)}&key=${QWEATHER_API_KEY}`;
      
      return new Promise((resolve, reject) => {
        https.get(locationUrl, (res) => {
          let data = '';
          res.on('data', (chunk) => data += chunk);
          res.on('end', () => {
            try {
              const result = JSON.parse(data);
              if (result.code !== '200') {
                resolve({error: `获取城市信息失败: ${result.message}`});
                return;
              }
              
              const locationId = result.location[0].id;
              
              // 第二步:获取天气
              const weatherUrl = `https://devapi.qweather.com/v7/weather/now?location=${locationId}&key=${QWEATHER_API_KEY}`;
              
              https.get(weatherUrl, (res2) => {
                let weatherData = '';
                res2.on('data', (chunk) => weatherData += chunk);
                res2.on('end', () => {
                  try {
                    const weatherResult = JSON.parse(weatherData);
                    if (weatherResult.code !== '200') {
                      resolve({error: `获取天气失败: ${weatherResult.message}`});
                      return;
                    }
                    
                    resolve({
                      city: result.location[0].name,
                      temp: weatherResult.now.temp,
                      text: weatherResult.now.text,
                      windDir: weatherResult.now.windDir,
                      windScale: weatherResult.now.windScale,
                      humidity: weatherResult.now.humidity,
                      obsTime: weatherResult.now.obsTime
                    });
                  } catch (e) {
                    resolve({error: e.message});
                  }
                });
              });
            } catch (e) {
              resolve({error: e.message});
            }
          });
        });
      });
    }
    
    // 入口函数
    async function handleToolCall(toolName, params, context) {
      if (toolName === 'get_current_weather') {
        const result = await getCurrentWeather(params.city);
        return JSON.stringify(result, null, 2);
      }
      
      return JSON.stringify({error: `未知工具: ${toolName}`});
    }
    
    module.exports = {
      name: 'weather',
      description: '查询城市天气,支持当前天气和天气预报',
      handleToolCall
    };

    步骤 4: 配置 API Key

    在你的环境变量中添加 API Key:

    # ~/.zshrc 或 ~/.bashrc
    export QWEATHER_API_KEY="你的API Key这里"

    重启 OpenClaw 生效。

    步骤 5: 测试使用

    重启 OpenClaw 后,试试看:

    北京今天天气怎么样?

    AI 会:

    1. 识别需要使用天气技能
    2. 调用 get_current_weather 工具
    3. 获取天气数据
    4. 用自然语言告诉你结果

    扩展:添加未来天气预报

    你可以继续添加 get_forecast 工具,获取未来 3 天的天气预报,代码结构是一样的。

    代码结构总结

    文件作用
    SKILL.md技能说明,AI 阅读
    index.js代码实现,导出 handleToolCall
    handleToolCall工具调用入口,根据工具名分发

    最佳实践

    1. 错误处理:遇到错误返回 {error: "message"},AI 会正确处理
    2. API Key 安全:放在环境变量,不要写进代码里
    3. 返回 JSON:结构化数据方便 AI 解析
    4. 一个技能只做一件事:天气技能就只做天气相关,保持简洁

    总结

    恭喜你!你已经完成了一个完整的 OpenClaw 技能开发:

    • ✅ 创建了技能目录和文件
    • ✅ 编写了 SKILL.md 说明
    • ✅ 实现了工具调用逻辑
    • ✅ 调用了外部 API 获取数据
    • ✅ 配置了 API Key 并测试

    现在你可以按照这个模式开发自己需要的技能了!

    发表回复

    您的邮箱地址不会被公开。 必填项已用 * 标注