|

楼主 |
发表于 2025-1-30 23:15:36
|
显示全部楼层
(2) 服务器代码
python
Copy
Edit
from flask import Flask, request, jsonify
import requests
import xml.etree.ElementTree as ET
app = Flask(__name__)
# DeepSeek API
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
DEEPSEEK_API_KEY = "your-deepseek-api-key"
# 处理微信服务器验证
@app.route("/", methods=["GET", "POST"])
def wechat():
if request.method == "GET":
# 公众号接入验证
return request.args.get("echostr")
if request.method == "POST":
xml_data = request.data
root = ET.fromstring(xml_data)
from_user = root.find("FromUserName").text
to_user = root.find("ToUserName").text
content = root.find("Content").text # 用户输入的内容
# 调用 DeepSeek 进行智能问答
response_text = get_deepseek_reply(content)
# 返回 XML 响应给微信
reply_xml = f"""
<xml>
<ToUserName><![CDATA[{from_user}]]></ToUserName>
<FromUserName><![CDATA[{to_user}]]></FromUserName>
<CreateTime>{int(time.time())}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{response_text}]]></Content>
</xml>
"""
return reply_xml
# 调用 DeepSeek API
def get_deepseek_reply(user_input):
headers = {"Authorization": f"Bearer {DEEPSEEK_API_KEY}", "Content-Type": "application/json"}
payload = {
"model": "deepseek-chat",
"messages": [{"role": "user", "content": user_input}]
}
response = requests.post(DEEPSEEK_API_URL, json=payload, headers=headers)
return response.json()["choices"][0]["message"]["content"]
if __name__ == "__main__":
app.run(port=8000, debug=True)
|
|