Phase 5 / Ep 25: 开发你的第一个 Plugin —— \"消息计数器\"

⏱ 预计阅读 4 分钟 更新于 2026/4/13

🎯 学习目标:从零开发一个 Plugin 并注册到 Gateway。

1. 目标:消息计数器

开发一个 message-counter Plugin,统计每个用户的消息数量,并通过 /stats 命令查看。

2. 目录结构

~/.openclaw/plugins/message-counter/
├── manifest.json       # Plugin 元数据
├── index.js            # 主入口
├── data/
│   └── counts.json     # 持久化数据
└── README.md

3. manifest.json

{
  "name": "message-counter",
  "version": "1.0.0",
  "description": "统计每个用户的消息发送数量",
  "author": "your-name",
  "main": "index.js",
  "hooks": ["onMessage"],
  "commands": ["/stats"]
}

4. 核心逻辑 (index.js)

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

const DATA_FILE = path.join(__dirname, 'data', 'counts.json');

function loadCounts() {
  if (fs.existsSync(DATA_FILE)) {
    return JSON.parse(fs.readFileSync(DATA_FILE, 'utf8'));
  }
  return {};
}

function saveCounts(counts) {
  fs.writeFileSync(DATA_FILE, JSON.stringify(counts, null, 2));
}

// Hook: 每条消息到达时触发
exports.onMessage = function(message, next) {
  const counts = loadCounts();
  const userId = message.userId;
  counts[userId] = (counts[userId] || 0) + 1;
  saveCounts(counts);
  next(); // 继续传递给下一个 Plugin
};

// Command: /stats
exports.commands = {
  '/stats': function(message) {
    const counts = loadCounts();
    const total = Object.values(counts).reduce((a, b) => a + b, 0);
    return `📊 消息统计\n总计: ${total} 条\n你的消息: ${counts[message.userId] || 0} 条`;
  }
};

5. 注册到 Gateway

// openclaw.json
{
  "plugins": {
    "pipeline": ["message-counter"]
  }
}
openclaw gateway restart

6. 测试

# 发几条消息
openclaw chat "测试消息 1"
openclaw chat "测试消息 2"

# 查看统计(通过 Telegram)
# 发送 /stats

下节预告: Ep 26,实战 Plugin——开发一个 "Notion 同步器",自动将对话摘要同步到 Notion。