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