Token导航 LogoToken导航TokenDH.com
开发可写文件clawhub未标认证来源可访问clear审计提醒

openclaw-hookOpenClaw hook 测试

Agent Skill

openclaw-hook 用于补充开发相关能力,适合在 OpenClaw 中需要让 Agent 承接开发相关任务时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

10,776

周安装

449

GitHub Stars

公开资料未说明

下载量

3,592
OpenClaw

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

MIT-0

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:openclaw-hook(OpenClaw hook 测试)
来源仓库:https://github.com/cbd2020/openclaw-hook
安装命令:
openclaw skills install openclaw-hook
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 OpenClaw 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

ClawHubOpenClaw
openclaw skills install openclaw-hook

简介

创建、调试和维护 OpenClaw Gateway 内部挂钩,用于代理事件(例如引导程序),包括虚拟文件注入和 Telegram 通知修复。

SKILL.md

name
openclaw-hook
description
Create, debug, and maintain OpenClaw Gateway internal hooks. Use when: (1) creating new hooks for agent events like bootstrap, (2) debugging hook execution issues, (3) understanding hook configuration and event structure, (4) injecting virtual bootstrap files, (5) fixing issues like Telegram notifications not sending, Content-Length errors, or context access problems. Triggers on phrases like "create a hook", "fix hook", "debug hook", "hook not working", "internal hook".

OpenClaw Internal Hook 开发指南

什么是 Internal Hook?

Internal Hook 是 OpenClaw Gateway 内部的事件处理器,在 agent 生命周期事件(如 agent:bootstrap)触发时执行 JavaScript/TypeScript 代码。

用途

  • 在会话启动时注入上下文文件
  • 检查和提醒用户待处理的事项
  • 发送通知(Telegram、Webhook 等)
  • 记录日志和审计

快速开始

1. 创建 Hook 目录

~/.openclaw/hooks/
└── my-hook/
    ├── HOOK.md      # Hook 元数据(可选但推荐)
    └── handler.js   # 主要处理逻辑(必须)

2. 编写 Handler

// ~/.openclaw/hooks/my-hook/handler.js
const handler = async (event) => {
  // 检查事件类型
  if (event.type !== 'agent' || event.action !== 'bootstrap') return;
  
  // 检查上下文
  if (!event.context?.workspaceDir) return;
  
  // 跳过 sub-agent
  if (event.sessionKey?.includes(':subagent:')) return;
  
  // 注入虚拟文件
  if (Array.isArray(event.context.bootstrapFiles)) {
    event.context.bootstrapFiles.push({
      path: 'MY_CONTEXT.md',
      content: '# Hello from hook!',
      virtual: true,
    });
  }
};

module.exports = handler;
module.exports.default = handler;

3. 注册 Hook

~/.openclaw/openclaw.json 中添加:

{
  "hooks": {
    "internal": {
      "enabled": true,
      "entries": {
        "my-hook": {
          "enabled": true
        }
      },
      "load": {
        "extraDirs": ["~/.openclaw/hooks"]
      }
    }
  }
}

4. 重启 Gateway

openclaw gateway restart

事件结构

agent:bootstrap 事件

{
  type: 'agent',
  action: 'bootstrap',
  sessionKey: 'agent:main:telegram:direct:YOUR_USER_ID',
  context: {
    workspaceDir: '~/.openclaw/workspace',
    bootstrapFiles: [
      { path: 'MEMORY.md', content: '...' },
      // 可以 push 新文件到这里
    ],
    cfg: { /* 配置对象 */ },
    sessionId: 'uuid',
    agentId: 'main'
  }
}

上下文字段

字段类型说明
workspaceDirstring工作区目录路径
bootstrapFilesarray要注入的文件列表
cfgobjectGateway 配置(可能不完整)
sessionIdstring会话 UUID
agentIdstringAgent ID(如 'main', 'baixiaosheng')

HOOK.md 元数据

---
name: my-hook
description: "What this hook does"
metadata:
  openclaw:
    emoji: "📚"
    events: ["agent:bootstrap"]
    requires:
      config: ["workspace.dir"]
---
# Hook 说明
...

核心模式

1. 安全检查(必须!)

const handler = async (event) => {
  // 检查事件对象
  if (!event || typeof event !== 'object') return;
  
  // 只处理 bootstrap 事件
  if (event.type !== 'agent' || event.action !== 'bootstrap') return;
  
  // 检查上下文
  if (!event.context || typeof event.context !== 'object') return;
  
  // 跳过 sub-agent
  if (event.sessionKey?.includes(':subagent:')) return;
  
  // 检查工作区
  const workspaceDir = event.context?.workspaceDir;
  if (!workspaceDir) return;
  
  // 继续处理...
};

2. 注入虚拟文件

if (Array.isArray(event.context.bootstrapFiles)) {
  event.context.bootstrapFiles.push({
    path: 'REMINDER.md',
    content: '# Reminder\
Do something!',
    virtual: true,
  });
}

3. 读取工作区文件

const fs = require('fs');
const path = require('path');

const memoryDir = path.join(workspaceDir, 'memory');
if (fs.existsSync(memoryDir)) {
  const files = fs.readdirSync(memoryDir).filter(f => f.endsWith('.md'));
  // 处理文件...
}

4. 发送 HTTP 请求(如 Telegram)

const https = require('https');

async function sendNotification(botToken, chatId, message) {
  const data = JSON.stringify({
    chat_id: chatId,
    text: message,
  });
  
  return new Promise((resolve) => {
    const options = {
      hostname: 'api.telegram.org',
      port: 443,
      path: `/bot${botToken}/sendMessage`,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // ⚠️ 关键:使用 Buffer.byteLength
        'Content-Length': Buffer.byteLength(data),
      },
    };
    
    const req = https.request(options, (res) => {
      let body = '';
      res.on('data', (chunk) => body += chunk);
      res.on('end', () => resolve(res.statusCode === 200));
    });
    
    req.on('error', (e) => {
      console.error('[hook] Error:', e.message);
      resolve(false);
    });
    
    req.write(data);
    req.end();
  });
}

5. 获取配置(从文件读取更可靠)

const fs = require('fs');

function getBotToken(accountName) {
  try {
    const configPath = path.join(os.homedir(), '.openclaw/openclaw.json');
    const content = fs.readFileSync(configPath, 'utf-8');
    const match = content.match(
      new RegExp(`"${accountName}"[\\s\\S]*?"botToken"\\s*:\\s*"([^"]+)"`)
    );
    return match?.[1] || null;
  } catch (e) {
    console.error('[hook] Config read error:', e.message);
    return null;
  }
}

调试方法

1. 添加日志

console.error('[my-hook] Debug:', JSON.stringify({
  sessionKey: event.sessionKey,
  workspaceDir: event.context?.workspaceDir,
}));

2. 查看日志

# 实时查看
tail -f ~/.openclaw/logs/gateway.err.log

# 搜索特定 hook
grep -i "my-hook" ~/.openclaw/logs/gateway.err.log | tail -20

3. 独立测试发送逻辑

node -e "
const https = require('https');
const data = JSON.stringify({
  chat_id: 'YOUR_CHAT_ID',
  text: 'Test message'
});
console.log('Byte length:', Buffer.byteLength(data));
// ... 发送逻辑
"

4. 测试 Hook 执行

发送 /new 命令触发 bootstrap 事件,然后检查日志。

常见陷阱

1. Content-Length 字节计算

问题:发送中文时 Telegram 返回 message text is empty

原因data.length 是字符数,不是字节数。中文字符在 UTF-8 中占 3 字节。

// ❌ 错误
'Content-Length': data.length

// ✅ 正确
'Content-Length': Buffer.byteLength(data)

2. Markdown 解析问题

Telegram Markdown 解析很严格,特殊字符会导致失败。

解决方案:不使用 parse_mode,发送纯文本。

3. cfg 对象不完整

event.context.cfg 可能不包含完整配置。

解决方案:直接从配置文件读取。

4. 忘记导出 handler

// 必须导出
module.exports = handler;
module.exports.default = handler;

5. 忘记重启 Gateway

修改 hook 后必须重启:

openclaw gateway restart

完整示例

参见 references/complete-example.js 获取包含所有功能的完整 hook 示例。

适合场景

01

OpenClaw 用户查找和安装 Skill 时

02

用户想查找某类 Agent Skill 时

03

需要根据任务场景推荐可安装能力包时

04

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

OpenClaw

98.89%
按下载量换算3,552

安全审计

VirusTotal

可疑

ClawScan

通过

Static analysis

通过

权限和风险

可写文件

该 Skill 可能写入或修改本地文件,使用前需要确认目标目录和修改范围。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills