refactor: 清理调试代码和废弃文件

删除的废弃文件:
- test-feishu-upload.js (测试文件)
- debug-upload.js (调试工具)
- check-bucket-override.js (诊断工具)
- feishu-card-server.js (废弃的卡片服务器)
- feishu-websocket-listener.js (废弃的 WebSocket 监听器)
- openclaw-bridge.js (废弃的桥接代码)
- setup.sh, start-listener.sh, verify-url.js (废弃脚本)
- cards/ 目录 (未使用的卡片模板)
- ARCHITECTURE.md, INTEGRATION.md 等废弃文档

优化:
- openclaw-processor.js: 添加 DEBUG 环境变量控制日志输出
- 移除生产环境不必要的调试日志

清理后核心文件:
- openclaw-processor.js (OpenClaw 处理器)
- openclaw-handler.js (HTTP 处理器)
- scripts/upload-to-qiniu.js (核心上传脚本)
- scripts/feishu-listener.js (独立监听器)
- scripts/update-bucket-setting.js (存储桶设置工具)
- deploy.sh (部署脚本)
This commit is contained in:
daoqi
2026-03-07 16:08:47 +08:00
parent 1aeae9cc51
commit 9b584cdad4
16 changed files with 3 additions and 2670 deletions

View File

@@ -1,213 +0,0 @@
#!/usr/bin/env node
/**
* 七牛云存储桶覆盖设置检查脚本
*
* 用途:检查存储桶是否允许覆盖上传
*
* 用法:
* node check-bucket-override.js [bucket-name]
*/
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const https = require('https');
const http = require('http');
const DEFAULT_CONFIG_PATH = path.join(process.env.HOME || process.env.USERPROFILE, '.openclaw/credentials/qiniu-config.json');
function loadConfig() {
if (!fs.existsSync(DEFAULT_CONFIG_PATH)) {
throw new Error(`配置文件不存在:${DEFAULT_CONFIG_PATH}`);
}
return JSON.parse(fs.readFileSync(DEFAULT_CONFIG_PATH, 'utf-8'));
}
function hmacSha1(data, secret) {
return crypto.createHmac('sha1', secret).update(data).digest();
}
function urlSafeBase64(data) {
return Buffer.from(data).toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
function generateAccessToken(accessKey, secretKey, method, path, body = '') {
const host = 'kodo.qiniu.com';
const contentType = 'application/json';
// 格式Method Path\nHost: Host\nContent-Type: ContentType\n\nBody
const signData = `${method} ${path}\nHost: ${host}\nContent-Type: ${contentType}\n\n${body}`;
const signature = hmacSha1(signData, secretKey);
const encodedSign = urlSafeBase64(signature);
return `Qiniu ${accessKey}:${encodedSign}`;
}
function httpRequest(url, options, body = null) {
return new Promise((resolve, reject) => {
const protocol = url.startsWith('https') ? https : http;
const req = protocol.request(url, options, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
const json = JSON.parse(data);
resolve({ status: res.statusCode, data: json });
} catch (e) {
resolve({ status: res.statusCode, data: data });
}
});
});
req.on('error', reject);
if (body) {
req.write(body);
}
req.end();
});
}
async function checkBucket(bucketName) {
const config = loadConfig();
const bucketConfig = config.buckets[bucketName || 'default'];
if (!bucketConfig) {
throw new Error(`存储桶配置 "${bucketName || 'default'}" 不存在`);
}
const { accessKey, secretKey, bucket, region } = bucketConfig;
console.log('🔍 检查存储桶覆盖设置...\n');
console.log(`存储桶:${bucket}`);
console.log(`区域:${region}`);
console.log(`AccessKey: ${accessKey.substring(0, 4)}...${accessKey.substring(accessKey.length - 4)}`);
console.log('');
// 1. 获取存储桶列表
// 七牛云 API 文档https://developer.qiniu.com/kodo/api/1314/list-buckets
const listBucketsUrl = 'https://kodo.qiniu.com/v2/buckets';
const accessToken = generateAccessToken(accessKey, secretKey, 'GET', '/v2/buckets');
const listOptions = {
method: 'GET',
headers: {
'Host': 'kodo.qiniu.com',
'Authorization': accessToken
}
};
console.log('📋 获取存储桶列表...');
const listResult = await httpRequest(listBucketsUrl, listOptions);
if (listResult.status !== 200) {
console.error('❌ 获取存储桶列表失败:', listResult.data);
return;
}
const buckets = listResult.data;
const targetBucket = buckets.find(b => b.name === bucket);
if (!targetBucket) {
console.error(`❌ 未找到存储桶:${bucket}`);
console.log('\n可用的存储桶:');
buckets.forEach(b => console.log(` - ${b.name}`));
return;
}
console.log('✅ 存储桶存在\n');
// 2. 获取存储桶详细信息
const bucketInfoUrl = `https://kodo.qiniu.com/v2/buckets/${bucket}`;
const bucketInfoToken = generateAccessToken(accessKey, secretKey, 'GET', `/v2/buckets/${bucket}`);
const infoOptions = {
method: 'GET',
headers: {
'Host': 'kodo.qiniu.com',
'Authorization': bucketInfoToken
}
};
console.log('📋 获取存储桶详细信息...');
const infoResult = await httpRequest(bucketInfoUrl, infoOptions);
if (infoResult.status !== 200) {
console.error('❌ 获取存储桶信息失败:', infoResult.data);
console.log('\n⚠ 可能是权限不足,请检查 AccessKey/SecretKey 是否有存储桶管理权限');
return;
}
const bucketInfo = infoResult.data;
console.log('\n📊 存储桶配置信息:');
console.log('─────────────────────────────────────');
console.log(` 名称:${bucketInfo.name || 'N/A'}`);
console.log(` 区域:${bucketInfo.region || bucketInfo.info?.region || 'N/A'}`);
console.log(` 创建时间:${bucketInfo.createdAt || bucketInfo.info?.createdAt || 'N/A'}`);
// 检查覆盖相关设置
const info = bucketInfo.info || bucketInfo;
console.log('\n🔒 安全设置:');
console.log('─────────────────────────────────────');
// 防覆盖设置(关键!)
const noOverwrite = info.noOverwrite !== undefined ? info.noOverwrite : '未设置';
console.log(` 防覆盖:${noOverwrite === true || noOverwrite === 1 ? '❌ 已启用(禁止覆盖)' : '✅ 未启用(允许覆盖)'}`);
// 私有空间设置
const private = info.private !== undefined ? info.private : '未知';
console.log(` 空间类型:${private === true || private === 1 ? '私有空间' : '公共空间'}`);
// 其他设置
if (info.maxSpace !== undefined) {
console.log(` 容量限制:${info.maxSpace} bytes`);
}
console.log('\n💡 解决方案:');
console.log('─────────────────────────────────────');
if (noOverwrite === true || noOverwrite === 1) {
console.log('⚠️ 存储桶已启用"防覆盖"设置,需要关闭才能覆盖上传同名文件。\n');
console.log('关闭方法:');
console.log('1. 登录七牛云控制台https://portal.qiniu.com/');
console.log(`2. 进入"对象存储" → 选择存储桶 "${bucket}"`);
console.log('3. 点击"设置" → "空间设置"');
console.log('4. 找到"防覆盖"选项,关闭它');
console.log('5. 保存设置后重试上传\n');
console.log('或者使用命令行关闭:');
console.log(`node scripts/update-bucket-setting.js ${bucket} noOverwrite 0`);
} else {
console.log('✅ 存储桶允许覆盖上传');
console.log('\n如果仍然无法覆盖可能原因:');
console.log('1. 上传凭证 scope 指定了具体 key但上传时使用了不同的 key');
console.log('2. 上传 API 端点不正确');
console.log('3. 文件正在被其他进程占用');
console.log('\n建议:');
console.log('- 检查上传日志中的实际上传 key 是否一致');
console.log('- 使用相同的完整路径(包括前导 /');
}
}
async function main() {
const bucketName = process.argv[2];
try {
await checkBucket(bucketName);
} catch (error) {
console.error('❌ 错误:', error.message);
process.exit(1);
}
}
if (require.main === module) {
main();
}
module.exports = { checkBucket };

View File

@@ -1,275 +0,0 @@
#!/usr/bin/env node
/**
* 七牛云上传调试脚本
*
* 用途:测试上传并显示详细错误信息
*
* 用法:
* node debug-upload.js --file <文件路径> --key <目标路径>
*/
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const https = require('https');
const http = require('http');
const DEFAULT_CONFIG_PATH = path.join(process.env.HOME || process.env.USERPROFILE, '.openclaw/credentials/qiniu-config.json');
function loadConfig() {
if (!fs.existsSync(DEFAULT_CONFIG_PATH)) {
throw new Error(`配置文件不存在:${DEFAULT_CONFIG_PATH}`);
}
return JSON.parse(fs.readFileSync(DEFAULT_CONFIG_PATH, 'utf-8'));
}
function hmacSha1(data, secret) {
return crypto.createHmac('sha1', secret).update(data).digest();
}
function urlSafeBase64(data) {
return Buffer.from(data).toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
function generateUploadToken(accessKey, secretKey, bucket, key = null, expires = 3600) {
const deadline = Math.floor(Date.now() / 1000) + expires;
// 关键修复scope 必须包含 key 才能覆盖上传
let scope = bucket;
if (key) {
scope = `${bucket}:${key}`; // ✅ 添加 key允许覆盖
}
console.log('📝 上传凭证参数:');
console.log(` scope: ${scope} (包含 key 才能覆盖)`);
console.log(` deadline: ${deadline}`);
console.log(` key: ${key || '(未指定,使用表单中的 key)'}`);
const putPolicy = {
scope: scope,
deadline: deadline,
returnBody: JSON.stringify({
success: true,
key: '$(key)',
hash: '$(etag)',
fsize: '$(fsize)',
bucket: '$(bucket)',
url: `$(domain)/$(key)`
})
};
console.log('\n📋 上传凭证策略:');
console.log(JSON.stringify(putPolicy, null, 2));
const encodedPolicy = urlSafeBase64(JSON.stringify(putPolicy));
const encodedSignature = urlSafeBase64(hmacSha1(encodedPolicy, secretKey));
const token = `${accessKey}:${encodedSignature}:${encodedPolicy}`;
console.log('\n🔑 生成的上传凭证:');
console.log(` ${accessKey}:${encodedSignature.substring(0, 20)}...`);
return token;
}
function httpRequest(url, options, body = null) {
return new Promise((resolve, reject) => {
const protocol = url.startsWith('https') ? https : http;
console.log(`\n📤 发送请求:`);
console.log(` URL: ${url}`);
console.log(` Method: ${options.method}`);
console.log(` Headers:`, JSON.stringify(options.headers, null, 2));
const req = protocol.request(url, options, (res) => {
console.log(`\n📥 收到响应:`);
console.log(` Status: ${res.statusCode}`);
console.log(` Headers:`, JSON.stringify(res.headers, null, 2));
let data = '';
res.on('data', chunk => {
data += chunk;
console.log(` 接收数据块:${chunk.length} bytes`);
});
res.on('end', () => {
console.log(`\n📦 完整响应数据:`);
console.log(data);
try {
const json = JSON.parse(data);
resolve({ status: res.statusCode, data: json });
} catch (e) {
resolve({ status: res.statusCode, data: data, raw: true });
}
});
});
req.on('error', (e) => {
console.error('❌ 请求错误:', e);
reject(e);
});
if (body) {
console.log(`\n📤 请求体大小:${body.length} bytes`);
req.write(body);
}
req.end();
});
}
async function debugUpload() {
const args = process.argv.slice(2);
let filePath = null;
let key = null;
let bucketName = 'default';
for (let i = 0; i < args.length; i++) {
if (args[i] === '--file' && args[i + 1]) {
filePath = args[i + 1];
i++;
} else if (args[i] === '--key' && args[i + 1]) {
key = args[i + 1];
i++;
} else if (args[i] === '--bucket' && args[i + 1]) {
bucketName = args[i + 1];
i++;
}
}
if (!filePath) {
console.error('❌ 缺少必需参数 --file');
console.error('用法node debug-upload.js --file <文件路径> [--key <目标路径>] [--bucket <存储桶名>]');
process.exit(1);
}
if (!fs.existsSync(filePath)) {
console.error(`❌ 文件不存在:${filePath}`);
process.exit(1);
}
const config = loadConfig();
const bucketConfig = config.buckets[bucketName];
if (!bucketConfig) {
console.error(`❌ 存储桶配置 "${bucketName}" 不存在`);
process.exit(1);
}
const { accessKey, secretKey, bucket, region, domain } = bucketConfig;
// 确定目标 key
if (!key) {
key = path.basename(filePath);
} else if (key.startsWith('/')) {
key = key.substring(1);
}
console.log('═══════════════════════════════════════════════════════════');
console.log('🔍 七牛云上传调试');
console.log('═══════════════════════════════════════════════════════════');
console.log(`\n📁 文件信息:`);
console.log(` 本地路径:${filePath}`);
console.log(` 文件大小:${fs.statSync(filePath).size} bytes`);
console.log(` 目标 key: ${key}`);
console.log(` 存储桶:${bucket}`);
console.log(` 区域:${region}`);
console.log(` 域名:${domain}`);
// 生成上传凭证
console.log('\n═══════════════════════════════════════════════════════════');
const uploadToken = generateUploadToken(accessKey, secretKey, bucket, key);
// 构建上传请求
const regionEndpoint = getUploadEndpoint(region);
const boundary = '----WebKitFormBoundary' + Math.random().toString(36).substring(2);
const fileContent = fs.readFileSync(filePath);
const fileName = path.basename(filePath);
const bodyParts = [
`------${boundary}`,
'Content-Disposition: form-data; name="token"',
'',
uploadToken,
`------${boundary}`,
'Content-Disposition: form-data; name="key"',
'',
key,
`------${boundary}`,
`Content-Disposition: form-data; name="file"; filename="${fileName}"`,
'Content-Type: application/octet-stream',
'',
'',
];
const bodyBuffer = Buffer.concat([
Buffer.from(bodyParts.join('\r\n'), 'utf-8'),
fileContent,
Buffer.from(`\r\n------${boundary}--\r\n`, 'utf-8')
]);
const uploadUrl = `${regionEndpoint}/`;
const uploadOptions = {
method: 'POST',
headers: {
'Content-Type': `multipart/form-data; boundary=----${boundary}`,
'Content-Length': bodyBuffer.length
}
};
console.log('\n═══════════════════════════════════════════════════════════');
console.log('📤 开始上传...');
console.log('═══════════════════════════════════════════════════════════');
try {
const result = await httpRequest(uploadUrl, uploadOptions, bodyBuffer);
console.log('\n═══════════════════════════════════════════════════════════');
console.log('📊 上传结果:');
console.log('═══════════════════════════════════════════════════════════');
if (result.status === 200) {
console.log('✅ 上传成功!');
console.log(` key: ${result.data.key}`);
console.log(` hash: ${result.data.hash}`);
console.log(` url: ${domain}/${result.data.key}`);
} else {
console.log('❌ 上传失败!');
console.log(` HTTP Status: ${result.status}`);
console.log(` 错误信息:`, JSON.stringify(result.data, null, 2));
// 解析常见错误
if (result.data.error) {
console.log('\n🔍 错误分析:');
if (result.data.error.includes('file exists')) {
console.log(' ⚠️ 文件已存在,存储桶可能禁止覆盖');
} else if (result.data.error.includes('invalid token')) {
console.log(' ⚠️ 上传凭证无效,检查 AccessKey/SecretKey');
} else if (result.data.error.includes('bucket')) {
console.log(' ⚠️ 存储桶配置问题');
}
}
}
} catch (error) {
console.error('❌ 上传过程出错:', error.message);
}
}
function getUploadEndpoint(region) {
const endpoints = {
'z0': 'https://up.qiniup.com',
'z1': 'https://up-z1.qiniup.com',
'z2': 'https://up-z2.qiniup.com',
'na0': 'https://up-na0.qiniup.com',
'as0': 'https://up-as0.qiniup.com'
};
return endpoints[region] || endpoints['z0'];
}
debugUpload().catch(console.error);

View File

@@ -1,410 +0,0 @@
#!/usr/bin/env node
/**
* 飞书卡片交互服务器
*
* 功能:
* 1. 接收飞书卡片按钮点击回调
* 2. 处理交互逻辑(上传、配置、帮助)
* 3. 回复交互式消息
*
* 使用方式:
* node scripts/feishu-card-server.js [port]
*
* 默认端口3000
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
// ============ 配置 ============
const PORT = process.argv[2] || 3000;
const CARD_TEMPLATE_PATH = path.join(__dirname, '../cards/upload-card.json');
const QINIU_CONFIG_PATH = path.join(process.env.HOME || process.env.USERPROFILE, '.openclaw/credentials/qiniu-config.json');
// 飞书验证令牌(在飞书开发者后台设置)
const FEISHU_VERIFICATION_TOKEN = process.env.FEISHU_VERIFICATION_TOKEN || 'your_verification_token';
// ============ 工具函数 ============
function loadConfig(configPath = QINIU_CONFIG_PATH) {
if (!fs.existsSync(configPath)) {
throw new Error(`配置文件不存在:${configPath}`);
}
return JSON.parse(fs.readFileSync(configPath, 'utf-8'));
}
function loadCardTemplate(templatePath = CARD_TEMPLATE_PATH) {
if (!fs.existsSync(templatePath)) {
throw new Error(`卡片模板不存在:${templatePath}`);
}
return JSON.parse(fs.readFileSync(templatePath, 'utf-8'));
}
function renderCard(template, variables) {
let cardJson = JSON.stringify(template);
for (const [key, value] of Object.entries(variables)) {
cardJson = cardJson.replace(new RegExp(`{{${key}}}`, 'g'), value);
}
return JSON.parse(cardJson);
}
function getRegionName(regionCode) {
const regions = {
'z0': '华东',
'z1': '华北',
'z2': '华南',
'na0': '北美',
'as0': '东南亚'
};
return regions[regionCode] || '未知';
}
// ============ 飞书鉴权 ============
/**
* 验证飞书请求签名
* 文档https://open.feishu.cn/document/ukTMukTMukTM/uYjNwYjL2YDM14SM2ATN
*/
function verifyFeishuSignature(req, body) {
const signature = req.headers['x-feishu-signature'];
if (!signature) return false;
// 简单验证,生产环境需要严格验证
return true;
}
// ============ 卡片交互处理 ============
/**
* 处理卡片按钮点击
*/
async function handleCardInteraction(req, res) {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', async () => {
try {
const data = JSON.parse(body);
// 飞书挑战验证
if (data.type === 'url_verification') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ challenge: data.challenge }));
return;
}
// 处理交互事件
if (data.type === 'interactive_card.action') {
const action = data.action?.value?.action;
const userId = data.user?.user_id;
const openId = data.user?.open_id;
const tenantKey = data.tenant_key;
console.log(`收到卡片交互:${action}, 用户:${userId}`);
let responseCard;
switch (action) {
case 'upload_select':
responseCard = await handleUploadSelect(data);
break;
case 'config_view':
responseCard = await handleConfigView(data);
break;
case 'help':
responseCard = await handleHelp(data);
break;
default:
responseCard = createErrorResponse('未知操作');
}
// 回复卡片
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
type: 'interactive_card.response',
card: responseCard
}));
return;
}
// 未知类型
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
} catch (error) {
console.error('处理交互失败:', error);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: error.message }));
}
});
}
/**
* 处理"选择文件上传"按钮
*/
async function handleUploadSelect(data) {
const config = loadConfig();
const bucketName = data.action?.value?.bucket || 'default';
const bucketConfig = config.buckets[bucketName];
if (!bucketConfig) {
return createErrorResponse(`存储桶 "${bucketName}" 不存在`);
}
// 回复引导用户上传文件
return {
config: {
wide_screen_mode: true
},
header: {
template: "green",
title: {
content: "📎 选择文件",
tag: "plain_text"
}
},
elements: [
{
tag: "div",
text: {
content: `请点击下方按钮选择要上传的文件,文件将上传到 **${bucketName}** 存储桶。`,
tag: "lark_md"
}
},
{
tag: "action",
actions: [
{
tag: "button",
text: {
content: "📁 选择文件",
tag: "plain_text"
},
type: "primary",
url: "feishu://attachment/select" // 飞书内部协议,触发文件选择
}
]
}
]
};
}
/**
* 处理"查看配置"按钮
*/
async function handleConfigView(data) {
const config = loadConfig();
let bucketList = '';
for (const [name, bucket] of Object.entries(config.buckets)) {
bucketList += `**${name}**: ${bucket.bucket} (${bucket.region})\n`;
}
return {
config: {
wide_screen_mode: true
},
header: {
template: "blue",
title: {
content: "📋 当前配置",
tag: "plain_text"
}
},
elements: [
{
tag: "div",
text: {
content: bucketList || '暂无配置',
tag: "lark_md"
}
},
{
tag: "hr"
},
{
tag: "note",
elements: [
{
tag: "plain_text",
content: `配置文件:${QINIU_CONFIG_PATH}`
}
]
}
]
};
}
/**
* 处理"帮助"按钮
*/
async function handleHelp(data) {
return {
config: {
wide_screen_mode: true
},
header: {
template: "grey",
title: {
content: "❓ 帮助",
tag: "plain_text"
}
},
elements: [
{
tag: "div",
text: {
content: `**七牛云上传帮助**
📤 **上传文件**
- 点击"选择文件上传"按钮
- 选择要上传的文件
- 自动上传到七牛云
⚙️ **快捷命令**
- \`/u\` - 快速上传
- \`/qc\` - 查看配置
- \`/qh\` - 显示帮助
📦 **存储桶**
- 支持多存储桶配置
- 上传时可指定目标桶`,
tag: "lark_md"
}
}
]
};
}
/**
* 创建错误响应
*/
function createErrorResponse(message) {
return {
config: {
wide_screen_mode: true
},
header: {
template: "red",
title: {
content: "❌ 错误",
tag: "plain_text"
}
},
elements: [
{
tag: "div",
text: {
content: message,
tag: "lark_md"
}
}
]
};
}
// ============ 主页面(测试用) ============
function serveHomePage(res) {
const html = `
<!DOCTYPE html>
<html>
<head>
<title>七牛云上传 - 飞书卡片服务器</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; }
h1 { color: #333; }
.status { padding: 10px; background: #e8f5e9; border-radius: 4px; margin: 20px 0; }
.config { background: #f5f5f5; padding: 15px; border-radius: 4px; }
code { background: #eee; padding: 2px 6px; border-radius: 3px; }
</style>
</head>
<body>
<h1>🍙 七牛云上传 - 飞书卡片服务器</h1>
<div class="status">
✅ 服务器运行中
<br>端口:<code>${PORT}</code>
</div>
<div class="config">
<h3>配置信息</h3>
<p>卡片模板:<code>${CARD_TEMPLATE_PATH}</code></p>
<p>七牛配置:<code>${QINIU_CONFIG_PATH}</code></p>
</div>
<h3>飞书开发者后台配置</h3>
<ol>
<li>请求网址:<code>http://你的服务器IP:${PORT}/feishu/card</code></li>
<li>数据加密方式:选择"不加密"</li>
<li>验证令牌:在环境变量中设置 <code>FEISHU_VERIFICATION_TOKEN</code></li>
</ol>
<h3>测试</h3>
<p>使用 curl 测试:</p>
<pre><code>curl -X POST http://localhost:${PORT}/feishu/card \\
-H "Content-Type: application/json" \\
-d '{"type":"url_verification","challenge":"test123"}'</code></pre>
</body>
</html>
`;
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(html);
}
// ============ HTTP 服务器 ============
const server = http.createServer((req, res) => {
console.log(`${new Date().toISOString()} ${req.method} ${req.url}`);
// CORS 头(飞书回调需要)
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Feishu-Signature');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// 主页
if (req.url === '/' || req.url === '/health') {
serveHomePage(res);
return;
}
// 卡片交互回调
if (req.url === '/feishu/card' && req.method === 'POST') {
handleCardInteraction(req, res);
return;
}
// 404
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
});
// ============ 启动服务器 ============
server.listen(PORT, () => {
console.log(`🍙 七牛云卡片服务器已启动`);
console.log(`端口:${PORT}`);
console.log(`主页http://localhost:${PORT}/`);
console.log(`回调地址http://localhost:${PORT}/feishu/card`);
console.log(`\n在飞书开发者后台配置请求网址为http://你的服务器IP:${PORT}/feishu/card`);
});
// 优雅退出
process.on('SIGINT', () => {
console.log('\n正在关闭服务器...');
server.close(() => {
console.log('服务器已关闭');
process.exit(0);
});
});

View File

@@ -1,477 +0,0 @@
#!/usr/bin/env node
/**
* 飞书长连接监听器 - 七牛云上传自动化
*
* 使用飞书 WebSocket 长连接接收事件
*
* 使用方式:
* node scripts/feishu-websocket-listener.js
*/
const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const https = require('https');
const { exec } = require('child_process');
// ============ 配置 ============
const CONFIG = {
appId: process.env.FEISHU_APP_ID || 'cli_a92ce47b02381bcc',
appSecret: process.env.FEISHU_APP_SECRET || 'WpCWhqOPKv3F5Lhn11DqubrssJnAodot',
encryptKey: process.env.FEISHU_ENCRYPT_KEY || '',
openclawCredentials: path.join(process.env.HOME || process.env.USERPROFILE, '.openclaw/credentials'),
scriptDir: __dirname
};
// ============ 工具函数 ============
function log(...args) {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}]`, ...args);
}
function verifySignature(timestamp, nonce, signature) {
if (!CONFIG.encryptKey) return true;
const arr = [CONFIG.encryptKey, timestamp, nonce];
arr.sort();
const str = arr.join('');
const hash = crypto.createHash('sha1').update(str).digest('hex');
return hash === signature;
}
// ============ 命令解析 ============
function parseUploadCommand(text) {
const match = text.match(/^\/upload(?:\s+(.+))?$/i);
if (!match) return null;
const args = (match[1] || '').trim().split(/\s+/).filter(Boolean);
let targetPath = null;
let useOriginal = false;
let bucket = 'default';
for (const arg of args) {
if (arg === '--original') {
useOriginal = true;
} else if (arg.startsWith('/') || arg.includes('.')) {
targetPath = arg;
} else {
bucket = arg;
}
}
return {
command: 'upload',
targetPath: targetPath,
useOriginal: useOriginal,
bucket: bucket
};
}
function parseConfigCommand(text) {
const match = text.match(/^\/qiniu-config\s+(.+)$/i);
if (!match) return null;
const args = match[1].trim().split(/\s+/);
const subCommand = args[0];
return {
command: 'config',
subCommand: subCommand,
args: args.slice(1)
};
}
// ============ 飞书 API ============
async function getAccessToken(appId, appSecret) {
const url = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal';
const body = JSON.stringify({
app_id: appId,
app_secret: appSecret
});
return new Promise((resolve, reject) => {
const req = https.request(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
const result = JSON.parse(data);
if (result.code === 0) {
resolve(result.tenant_access_token);
} else {
reject(new Error(`获取 token 失败:${result.msg}`));
}
} catch (e) {
reject(e);
}
});
});
req.on('error', reject);
req.write(body);
req.end();
});
}
async function sendMessageToChat(chatId, text) {
try {
const token = await getAccessToken(CONFIG.appId, CONFIG.appSecret);
const url = 'https://open.feishu.cn/open-apis/im/v1/messages';
const body = JSON.stringify({
receive_id: chatId,
msg_type: 'text',
content: JSON.stringify({ text })
});
await new Promise((resolve, reject) => {
const req = https.request(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
}, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
resolve(JSON.parse(data));
} catch (e) {
reject(e);
}
});
});
req.on('error', reject);
req.write(body);
req.end();
});
} catch (e) {
log('发送消息失败:', e.message);
}
}
async function downloadFeishuFile(token, fileKey, destPath) {
const url = `https://open.feishu.cn/open-apis/im/v1/files/${fileKey}/download`;
return new Promise((resolve, reject) => {
const req = https.get(url, {
headers: { 'Authorization': `Bearer ${token}` }
}, (res) => {
if (res.statusCode !== 200) {
reject(new Error(`下载失败:${res.statusCode}`));
return;
}
const file = fs.createWriteStream(destPath);
res.pipe(file);
file.on('finish', () => {
file.close();
resolve(destPath);
});
}).on('error', reject);
});
}
// ============ 消息处理 ============
async function handleUploadCommand(message, cmd) {
const { chat_id, attachments } = message;
if (!attachments || attachments.length === 0) {
await sendMessageToChat(chat_id,
'❌ 请附上要上传的文件\n\n' +
'💡 使用示例:\n' +
'/upload /config/test/file.txt default\n' +
'[附上文件]\n\n' +
'或:/upload --original default\n' +
'[附上文件] (使用原文件名)'
);
return;
}
const attachment = attachments[0];
const fileKey = attachment.file_key;
const originalFileName = attachment.file_name;
log(`处理附件:${originalFileName} (${fileKey})`);
let targetKey;
if (cmd.useOriginal) {
targetKey = originalFileName;
} else if (cmd.targetPath) {
targetKey = cmd.targetPath.startsWith('/') ? cmd.targetPath.substring(1) : cmd.targetPath;
} else {
targetKey = originalFileName;
}
const tempDir = path.join(CONFIG.openclawCredentials, 'temp');
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir, { recursive: true });
}
const tempFile = path.join(tempDir, `upload_${Date.now()}_${originalFileName}`);
try {
const token = await getAccessToken(CONFIG.appId, CONFIG.appSecret);
log('下载文件中...');
await sendMessageToChat(chat_id, `📥 正在下载文件:${originalFileName}`);
await downloadFeishuFile(token, fileKey, tempFile);
log('上传到七牛云...');
await sendMessageToChat(chat_id, `📤 正在上传到七牛云:${targetKey}\n存储桶:${cmd.bucket}`);
const uploadScript = path.join(CONFIG.scriptDir, 'upload-to-qiniu.js');
const uploadCmd = `node "${uploadScript}" upload --file "${tempFile}" --key "${targetKey}" --bucket "${cmd.bucket}"`;
const { stdout, stderr } = await new Promise((resolve, reject) => {
exec(uploadCmd, (error, stdout, stderr) => {
if (error) {
reject(new Error(`上传失败:${stderr || error.message}`));
return;
}
resolve({ stdout, stderr });
});
});
log(stdout);
const urlMatch = stdout.match(/🔗 URL: (.+)/);
const fileUrl = urlMatch ? urlMatch[1] : 'N/A';
await sendMessageToChat(chat_id,
`✅ 上传成功!\n\n` +
`📦 文件:${targetKey}\n` +
`🔗 链接:${fileUrl}\n` +
`💾 原文件:${originalFileName}\n` +
`🪣 存储桶:${cmd.bucket}`
);
} catch (error) {
log('处理失败:', error.message);
await sendMessageToChat(chat_id, `❌ 上传失败:${error.message}`);
} finally {
if (fs.existsSync(tempFile)) {
fs.unlinkSync(tempFile);
}
}
}
async function handleConfigCommand(message, cmd) {
const { chat_id } = message;
const uploadScript = path.join(CONFIG.scriptDir, 'upload-to-qiniu.js');
const configCmd = `node "${uploadScript}" config ${cmd.subCommand} ${cmd.args.join(' ')}`;
try {
const { stdout, stderr } = await new Promise((resolve, reject) => {
exec(configCmd, (error, stdout, stderr) => {
if (error) {
reject(new Error(stderr || error.message));
return;
}
resolve({ stdout, stderr });
});
});
await sendMessageToChat(chat_id, '```\n' + stdout + '\n```');
} catch (error) {
await sendMessageToChat(chat_id, `❌ 配置命令执行失败:${error.message}`);
}
}
async function showHelp(message) {
const helpText = `
🍙 七牛云上传 - 使用帮助
📤 上传文件:
/upload [目标路径] [存储桶名]
/upload --original [存储桶名]
示例:
/upload /config/test/file.txt default
/upload --original default
⚙️ 配置管理:
/qiniu-config list # 查看配置
/qiniu-config set <key> <value> # 修改配置
/qiniu-config set-bucket <name> <json> # 添加存储桶
/qiniu-config reset # 重置配置
示例:
/qiniu-config set default.accessKey YOUR_KEY
/qiniu-config set default.domain https://cdn.example.com
`;
await sendMessageToChat(message.chat_id, helpText);
}
async function processMessage(message) {
log('收到消息:', message.message_id);
const content = JSON.parse(message.content);
const text = content.text || '';
const configCmd = parseConfigCommand(text.trim());
if (configCmd) {
log('配置命令:', configCmd.subCommand);
await handleConfigCommand(message, configCmd);
return;
}
if (text.trim() === '/qiniu-help' || text.trim() === '/help') {
await showHelp(message);
return;
}
const uploadCmd = parseUploadCommand(text.trim());
if (uploadCmd) {
log('上传命令:', uploadCmd);
await handleUploadCommand(message, uploadCmd);
return;
}
log('不是已知命令,跳过');
}
// ============ WebSocket 长连接 ============
let ws = null;
let reconnectAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 10;
const RECONNECT_DELAY = 5000;
async function getWebSocketUrl() {
// 获取 WebSocket 连接地址
const token = await getAccessToken(CONFIG.appId, CONFIG.appSecret);
const url = 'https://open.feishu.cn/open-apis/connect/v1/ws';
return new Promise((resolve, reject) => {
const req = https.request(url, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
}, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
const result = JSON.parse(data);
if (result.code === 0) {
resolve(result.data.ws_url);
} else {
reject(new Error(`获取 WebSocket URL 失败:${result.msg}`));
}
} catch (e) {
reject(e);
}
});
});
req.on('error', reject);
req.write(JSON.stringify({}));
req.end();
});
}
function connectWebSocket() {
getWebSocketUrl().then((wsUrl) => {
log('🔌 连接 WebSocket:', wsUrl);
ws = new WebSocket(wsUrl);
ws.on('open', () => {
log('✅ WebSocket 已连接');
reconnectAttempts = 0;
});
ws.on('message', async (data) => {
try {
const event = JSON.parse(data.toString());
// 处理不同类型的事件
if (event.type === 'im.message.receive_v1') {
await processMessage(event.event.message);
} else if (event.type === 'verification') {
// 验证挑战
log('收到验证挑战');
ws.send(JSON.stringify({ challenge: event.challenge }));
} else {
log('未知事件类型:', event.type);
}
} catch (e) {
log('处理消息失败:', e.message);
}
});
ws.on('close', () => {
log('⚠️ WebSocket 已断开');
scheduleReconnect();
});
ws.on('error', (error) => {
log('❌ WebSocket 错误:', error.message);
});
}).catch((error) => {
log('❌ 获取 WebSocket URL 失败:', error.message);
scheduleReconnect();
});
}
function scheduleReconnect() {
if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
log('❌ 重连次数已达上限,停止重连');
return;
}
reconnectAttempts++;
const delay = RECONNECT_DELAY * reconnectAttempts;
log(`🔄 ${delay/1000}秒后尝试重连 (${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`);
setTimeout(() => {
connectWebSocket();
}, delay);
}
// ============ 主函数 ============
function main() {
log('🍙 七牛云上传 - 飞书长连接监听器');
log('配置文件:~/.openclaw/credentials/qiniu-config.json');
log('应用 ID:', CONFIG.appId);
log('');
// 检查配置
const configPath = path.join(CONFIG.openclawCredentials, 'qiniu-config.json');
if (!fs.existsSync(configPath)) {
log('⚠️ 警告:七牛云配置文件不存在');
log(' 运行node upload-to-qiniu.js config init');
}
// 连接 WebSocket
connectWebSocket();
}
main();

View File

@@ -1,82 +0,0 @@
#!/usr/bin/env node
/**
* OpenClaw 桥接脚本
*
* 功能:
* 1. 从 OpenClaw 接收消息
* 2. 调用上传脚本
* 3. 回复结果
*
* 使用方式(由 OpenClaw 调用):
* node scripts/openclaw-bridge.js <command> [args...]
*/
const { exec } = require('child_process');
const path = require('path');
const UPLOAD_SCRIPT = path.join(__dirname, 'upload-to-qiniu.js');
// 从命令行获取参数
const args = process.argv.slice(2);
const command = args[0];
if (!command) {
console.error('用法node openclaw-bridge.js <command> [args...]');
console.error('命令upload, config, help');
process.exit(1);
}
// 执行对应的命令
switch (command) {
case 'upload':
executeUpload(args.slice(1));
break;
case 'config':
executeConfig(args.slice(1));
break;
case 'help':
executeHelp();
break;
default:
console.error(`未知命令:${command}`);
process.exit(1);
}
function executeUpload(uploadArgs) {
const cmd = `node ${UPLOAD_SCRIPT} upload ${uploadArgs.join(' ')}`;
console.log(`执行:${cmd}`);
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.error(`上传失败:${error.message}`);
console.error(stderr);
process.exit(1);
}
console.log(stdout);
});
}
function executeConfig(configArgs) {
const cmd = `node ${UPLOAD_SCRIPT} config ${configArgs.join(' ')}`;
console.log(`执行:${cmd}`);
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.error(`配置操作失败:${error.message}`);
console.error(stderr);
process.exit(1);
}
console.log(stdout);
});
}
function executeHelp() {
const cmd = `node ${UPLOAD_SCRIPT} --help`;
exec(cmd, (error, stdout, stderr) => {
if (error) {
// 忽略帮助命令的错误
}
console.log(stdout);
});
}

View File

@@ -1,84 +0,0 @@
#!/bin/bash
# 🍙 七牛云上传技能 - 快速配置脚本
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
echo "🍙 七牛云上传技能 - 快速配置"
echo "================================"
echo ""
# 1. 检查七牛云配置
QINIU_CONFIG="$HOME/.openclaw/credentials/qiniu-config.json"
if [ ! -f "$QINIU_CONFIG" ]; then
echo "📝 配置七牛云凭证..."
echo ""
echo "请复制配置模板并编辑:"
echo " cp qiniu-config.example.json ~/.openclaw/credentials/qiniu-config.json"
echo ""
read -p "按回车继续..."
if [ ! -f "$QINIU_CONFIG" ]; then
cp qiniu-config.example.json "$QINIU_CONFIG"
echo "✅ 已复制配置模板到:$QINIU_CONFIG"
echo ""
echo "请编辑文件并填写你的七牛云信息:"
echo " - AccessKey"
echo " - SecretKey"
echo " - Bucket 名称"
echo " - 区域代码"
echo " - CDN 域名"
echo ""
read -p "编辑完成后按回车继续..."
fi
else
echo "✅ 七牛云配置已存在"
fi
# 2. 配置飞书环境变量
if [ ! -f ".env" ]; then
echo ""
echo "📝 配置飞书环境变量..."
cp .env.example .env
echo "✅ 已创建 .env 文件"
echo ""
echo "请编辑 .env 文件并填写:"
echo " - FEISHU_VERIFY_TOKEN自定义"
echo " - FEISHU_ENCRYPT_KEY从飞书开放平台获取"
echo ""
read -p "按回车继续..."
else
echo "✅ 飞书环境变量已配置"
fi
# 3. 检查 Node.js
if ! command -v node &> /dev/null; then
echo "❌ 未找到 Node.js请先安装 Node.js"
exit 1
fi
echo ""
echo "✅ 配置完成!"
echo ""
echo "================================"
echo "📋 下一步:"
echo ""
echo "1⃣ 配置飞书开放平台事件订阅"
echo " 查看详细说明cat FEISHU_SETUP.md"
echo ""
echo "2⃣ 启动 URL 验证服务(首次配置)"
echo " ./scripts/verify-url.js"
echo ""
echo "3⃣ 验证通过后,启动正式监听器"
echo " ./scripts/start-listener.sh"
echo ""
echo "4⃣ 在飞书中测试"
echo " 发送:/upload 文件名.pdf"
echo " 附上文件"
echo ""
echo "================================"
echo ""

View File

@@ -1,36 +0,0 @@
#!/bin/bash
# 🍙 七牛云上传 - 飞书监听器启动脚本
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
# 检查配置文件
if [ ! -f ".env" ]; then
echo "❌ 配置文件 .env 不存在"
echo ""
echo "请先创建配置文件:"
echo " cp .env.example .env"
echo " # 然后编辑 .env 填写你的配置"
exit 1
fi
# 加载环境变量
set -a
source .env
set +a
# 检查必要的环境变量
if [ -z "$FEISHU_APP_ID" ] || [ -z "$FEISHU_APP_SECRET" ]; then
echo "❌ 缺少必要的环境变量"
echo "请检查 .env 文件中的 FEISHU_APP_ID 和 FEISHU_APP_SECRET"
exit 1
fi
# 启动监听器
echo "🍙 启动飞书监听器..."
echo "📍 工作目录:$SCRIPT_DIR"
echo "🔌 端口:${FEISHU_LISTENER_PORT:-3000}"
echo ""
node scripts/feishu-listener.js

View File

@@ -1,99 +0,0 @@
#!/usr/bin/env node
/**
* 飞书事件订阅 URL 验证处理器
*
* 用途:处理飞书开放平台的事件订阅 URL 验证请求
* 使用方式node verify-url.js
*/
const http = require('http');
const crypto = require('crypto');
// 配置
const CONFIG = {
port: 3000,
verifyToken: process.env.FEISHU_VERIFY_TOKEN || 'qiniu_upload_token_2026',
encryptKey: process.env.FEISHU_ENCRYPT_KEY || ''
};
console.log('🍙 飞书 URL 验证服务');
console.log('验证 Token:', CONFIG.verifyToken);
console.log('加密密钥:', CONFIG.encryptKey ? '已配置' : '未配置');
console.log('监听端口:', CONFIG.port);
console.log('');
console.log('📋 配置步骤:');
console.log('1. 在飞书开放平台设置请求地址http://你的 IP:3000');
console.log('2. 设置验证 Token:', CONFIG.verifyToken);
console.log('3. 点击保存,等待验证');
console.log('');
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
console.log(`[${new Date().toISOString()}] ${req.method} ${url.pathname}`);
// 处理飞书验证请求
if (url.pathname === '/' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
try {
const event = JSON.parse(body);
// 验证类型url_verification
if (event.type === 'url_verification') {
console.log('✅ 收到验证请求');
console.log('Challenge:', event.challenge);
// 返回 challenge
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ challenge: event.challenge }));
console.log('✅ 验证成功!请在飞书开放平台确认状态');
return;
}
// 其他事件类型
console.log('事件类型:', event.type);
console.log('事件内容:', JSON.stringify(event, null, 2));
res.writeHead(200);
res.end('OK');
} catch (e) {
console.error('❌ 解析失败:', e.message);
res.writeHead(400);
res.end('Invalid JSON');
}
});
return;
}
// 健康检查
if (url.pathname === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', timestamp: Date.now() }));
return;
}
// 其他请求
res.writeHead(404);
res.end('Not Found');
});
server.listen(CONFIG.port, () => {
console.log('');
console.log('🚀 服务已启动');
console.log(`📍 监听地址http://0.0.0.0:${CONFIG.port}`);
console.log('');
console.log('💡 提示:');
console.log(' - 按 Ctrl+C 停止服务');
console.log(' - 访问 http://localhost:3000/health 检查服务状态');
console.log('');
});