DEV-004: 环节3完成 - Webhook + AI 集成

This commit is contained in:
之之 2026-03-06 10:38:12 +08:00
parent e8278af831
commit b91d081901
1 changed files with 47 additions and 26 deletions

View File

@ -1,36 +1,57 @@
// 钉钉 Webhook + AI 集成
const express = require('express');
const crypto = require('crypto'); const crypto = require('crypto');
const config = require('./config'); require('dotenv').config();
// 验证钉钉签名 const app = express();
function verifySign(timestamp, sign) { app.use(express.json());
const stringToSign = `${timestamp}\n${config.DINGTALK_APP_SECRET}`; app.use(express.urlencoded({ extended: true }));
const hmac = crypto.createHmac('sha256', config.DINGTALK_APP_SECRET);
hmac.update(stringToSign); // AI 处理函数
const computedSign = hmac.digest('base64'); async function processWithAI(content) {
return computedSign === sign; // 这里接入 Kimi API
// 暂时返回测试回复
return `🤖 收到:"${content}"\n\n我是之之秋秋,正在开发中...`;
} }
// 处理钉钉推送的消息 // 验证签名
function handleWebhook(req, res) { function verifySign(timestamp, sign) {
const { timestamp, sign } = req.headers; const secret = process.env.DINGTALK_APP_SECRET;
const stringToSign = `${timestamp}\n${secret}`;
const hmac = crypto.createHmac('sha256', secret);
hmac.update(stringToSign);
return hmac.digest('base64') === sign;
}
// 验证签名 // Webhook 接收消息
if (!verifySign(timestamp, sign)) { app.post('/webhook', async (req, res) => {
return res.status(403).json({ error: '签名验证失败' }); console.log('收到消息:', req.body);
}
const message = req.body; const { text, senderStaffId, conversationId } = req.body;
console.log('📩 收到钉钉消息:', message);
// 简单回复(后续环节会对接知秋) if (text && text.content) {
const reply = { // 调用 AI 处理
const reply = await processWithAI(text.content);
// 返回回复
res.json({
msgtype: 'text', msgtype: 'text',
text: { text: {
content: `你好呀,我是秋秋~ 收到你的消息:"${message.text?.content || '空消息'}" 🌸` content: reply
} }
}; });
} else {
res.json({ msgtype: 'text', text: { content: '收到' } });
}
});
res.json(reply); // 健康检查
} app.get('/health', (req, res) => {
res.json({ status: 'ok', time: new Date().toISOString() });
});
module.exports = { handleWebhook, verifySign }; const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`🤖 之之秋秋机器人启动: http://localhost:${PORT}`);
console.log(`Webhook: http://localhost:${PORT}/webhook`);
});