安装 Node.js(v14+

openclaw openclaw官方 1

OpenClaw 是一个开源的多平台推送通知服务,支持 Android、iOS、Web 等平台,以下是一份完整的 OpenClaw 推送通知配置教程:

安装 Node.js(v14+-第1张图片-OpenClaw开源下载|官方OpenClaw下载

准备工作

1 环境要求

# 安装 Redis(消息队列)
redis-server --version
# 安装 MongoDB(存储设备信息和消息记录)
mongod --version

2 获取 OpenClaw

# 克隆仓库
git clone https://github.com/openclaw/openclaw.git
cd openclaw
# 安装依赖
npm install

服务端配置

1 配置文件设置

// config/config.js
module.exports = {
  server: {
    port: 3000,
    host: '0.0.0.0'
  },
  redis: {
    host: 'localhost',
    port: 6379,
    password: ''
  },
  mongodb: {
    url: 'mongodb://localhost:27017/openclaw',
    options: {
      useNewUrlParser: true,
      useUnifiedTopology: true
    }
  },
  // APNS (iOS) 配置
  apns: {
    key: '/path/to/APNsAuthKey.p8',
    keyId: 'YOUR_KEY_ID',
    teamId: 'YOUR_TEAM_ID',
    production: false // 开发环境设为 false
  },
  // FCM (Android) 配置
  fcm: {
    serverKey: 'YOUR_FCM_SERVER_KEY',
    senderId: 'YOUR_SENDER_ID'
  },
  // Web Push (VAPID)
  webPush: {
    publicKey: 'YOUR_PUBLIC_VAPID_KEY',
    privateKey: 'YOUR_PRIVATE_VAPID_KEY',
    subject: 'mailto:admin@example.com'
  }
};

2 启动服务

# 开发模式
npm run dev
# 生产模式
npm start
# 使用 PM2 管理
pm2 start server.js --name "openclaw"

客户端集成

1 Android 配置

// build.gradle (app)
dependencies {
    implementation 'com.google.firebase:firebase-messaging:23.0.0'
}
// AndroidManifest.xml
<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

2 iOS 配置

// AppDelegate.swift
import UserNotifications
func application(_ application: UIApplication, 
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
        // 处理授权结果
    }
    application.registerForRemoteNotifications()
    return true
}
// 获取 device token
func application(_ application: UIApplication, 
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    // 发送 token 到 OpenClaw 服务器
}

3 Web 配置

// 请求推送权限
async function requestNotificationPermission() {
  const permission = await Notification.requestPermission();
  if (permission === 'granted') {
    // 注册 Service Worker
    const registration = await navigator.serviceWorker.register('/sw.js');
    // 获取订阅对象
    const subscription = await registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: 'YOUR_VAPID_PUBLIC_KEY'
    });
    // 发送订阅信息到 OpenClaw 服务器
    await fetch('/api/push/subscribe', {
      method: 'POST',
      body: JSON.stringify(subscription),
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

API 使用示例

1 注册设备

# POST /api/devices
curl -X POST http://localhost:3000/api/devices \
  -H "Content-Type: application/json" \
  -d '{
    "platform": "android",
    "token": "DEVICE_TOKEN",
    "userId": "user123",
    "tags": ["premium", "vip"]
  }'

2 发送推送通知

# POST /api/push/send
curl -X POST http://localhost:3000/api/push/send \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "target": {
      "type": "user",
      "value": "user123"
    },
    "notification": {
      "title": "新消息",
      "body": "您有一条新的通知",
      "data": {
        "type": "message",
        "id": "msg123"
      },
      "badge": 1,
      "sound": "default"
    },
    "options": {
      "priority": "high",
      "ttl": 3600
    }
  }'

3 批量发送

// JavaScript 示例
const sendBulkNotifications = async (devices, message) => {
  const response = await fetch('http://localhost:3000/api/push/bulk', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_KEY'
    },
    body: JSON.stringify({
      devices: devices,
      notification: message
    })
  });
  return await response.json();
};

高级配置

1 消息队列配置

# config/queue.yaml
jobs:
  push_notification:
    queue: 'push',
    attempts: 3,
    backoff: 5000,
  analytics:
    queue: 'analytics',
    attempts: 1

2 安全配置

// config/security.js
module.exports = {
  rateLimit: {
    windowMs: 15 * 60 * 1000, // 15分钟
    max: 100 // 每个IP最多100次请求
  },
  apiKeys: {
    'YOUR_API_KEY': {
      name: 'Web App',
      permissions: ['send', 'read']
    }
  },
  cors: {
    origin: ['https://yourdomain.com'],
    credentials: true
  }
};

监控和日志

1 启用监控

# 安装监控工具
npm install @openclaw/monitor
# 启动监控面板
openclaw-monitor --port 3001

2 日志配置

// config/logger.js
const winston = require('winston');
module.exports = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ 
      filename: 'logs/error.log', 
      level: 'error' 
    }),
    new winston.transports.File({ 
      filename: 'logs/combined.log' 
    })
  ]
});

故障排除

常见问题及解决方案:

  1. 推送无法送达

    # 检查服务状态
    curl http://localhost:3000/health
    # 查看队列状态
    redis-cli monitor
  2. 证书问题(iOS)

    # 验证 APNs 证书
    openssl x509 -in apns.pem -text -noout
  3. FCM 配置错误

    // 测试 FCM 连接
    const admin = require('firebase-admin');
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: 'https://your-project.firebaseio.com'
    });

性能优化建议

  1. 使用连接池
  2. 启用消息压缩
  3. 配置适当的 TTL
  4. 实现消息去重
  5. 使用 CDN 分发大文件

参考资源

这个配置教程涵盖了 OpenClaw 的主要功能,根据实际需求,您可能需要调整配置参数,建议在生产环境部署前进行充分的测试。

标签: 安装 v14+

抱歉,评论功能暂时关闭!