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 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) {
const stringToSign = `${timestamp}\n${config.DINGTALK_APP_SECRET}`;
const hmac = crypto.createHmac('sha256', config.DINGTALK_APP_SECRET);
const secret = process.env.DINGTALK_APP_SECRET;
const stringToSign = `${timestamp}\n${secret}`;
const hmac = crypto.createHmac('sha256', secret);
hmac.update(stringToSign);
const computedSign = hmac.digest('base64');
return computedSign === sign;
return hmac.digest('base64') === sign;
}
// 处理钉钉推送的消息
function handleWebhook(req, res) {
const { timestamp, sign } = req.headers;
// Webhook 接收消息
app.post('/webhook', async (req, res) => {
console.log('收到消息:', req.body);
// 验证签名
if (!verifySign(timestamp, sign)) {
return res.status(403).json({ error: '签名验证失败' });
const { text, senderStaffId, conversationId } = req.body;
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 reply = {
msgtype: 'text',
text: {
content: `你好呀,我是秋秋~ 收到你的消息:"${message.text?.content || '空消息'}" 🌸`
}
};
res.json(reply);
}
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`);
});