明树Git Lab

Commit 12931480 authored by zfp1's avatar zfp1

update

parent 708d7635
const express = require('express');
const axios = require('axios');
const xml2js = require('xml2js');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const app = express();
const port = 3001;
// 微信服务号配置
const WECHAT_TOKEN = 'deepseektest';
const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/ask'; // 请替换为 DeepSeek 的具体 API 地址
const DEEPSEEK_API_KEY = 'sk-14f0cf16bad245169cd2563e0f9b678e'; // 请替换为你的 DeepSeek API 密钥
// 最大消息长度(微信最大支持2048字节)
const MAX_TEXT_LENGTH = 2048;
// 解析 XML 数据
app.use(bodyParser.xml({
explicitArray: false,
ignoreAttrs: true
}));
// 微信验证
app.get('/wechat', (req, res) => {
const { signature, timestamp, nonce, echostr } = req.query;
const token = WECHAT_TOKEN;
// 排序并生成加密字符串
const arr = [timestamp, nonce, token].sort();
const str = arr.join('');
const hash = crypto.createHash('sha1').update(str).digest('hex');
// 验证签名
if (hash === signature) {
res.send(echostr);
} else {
res.send('Invalid signature');
}
});
// 特殊字符转义(XML 转义)
function escapeXml(str) {
return str.replace(/[&<>'"]/g, function (char) {
switch (char) {
case '&': return '&amp;';
case '<': return '&lt;';
case '>': return '&gt;';
case "'": return '&apos;';
case '"': return '&quot;';
}
});
}
// 处理微信消息
app.post('/wechat', async (req, res) => {
const { xml } = req.body;
// 获取用户提问的内容
const userMessage = xml.Content;
if (!userMessage) {
return res.send('No content');
}
try {
// 调用 DeepSeek API 获取答案
const deepSeekResponse = await axios.post(DEEPSEEK_API_URL, {
apiKey: DEEPSEEK_API_KEY,
question: userMessage,
});
// 获取 DeepSeek API 返回的答案
let answer = deepSeekResponse.data.answer || 'Sorry, I could not find an answer.';
// 如果回答超长,截取并添加提示
if (answer.length > MAX_TEXT_LENGTH) {
answer = answer.substring(0, MAX_TEXT_LENGTH) + '... (Answer truncated)';
}
// 转义特殊字符
answer = escapeXml(answer);
// 构建微信返回消息格式
const responseMessage = `
<xml>
<ToUserName><![CDATA[${xml.FromUserName}]]></ToUserName>
<FromUserName><![CDATA[${xml.ToUserName}]]></FromUserName>
<CreateTime>${Date.now()}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[${answer}]]></Content>
</xml>
`;
// 返回消息到微信服务号
res.set('Content-Type', 'text/xml');
res.send(responseMessage);
} catch (error) {
console.error('Error calling DeepSeek API:', error);
const errorMessage = `
<xml>
<ToUserName><![CDATA[${xml.FromUserName}]]></ToUserName>
<FromUserName><![CDATA[${xml.ToUserName}]]></FromUserName>
<CreateTime>${Date.now()}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[Sorry, I couldn't fetch the answer right now. Please try again later.]]></Content>
</xml>
`;
res.set('Content-Type', 'text/xml');
res.send(errorMessage);
}
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment