-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
109 lines (94 loc) · 4.1 KB
/
Copy pathapp.py
File metadata and controls
109 lines (94 loc) · 4.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import os
import json
import time
import requests
from flask import Flask, request, Response
from WXBizMsgCrypt3 import WXBizMsgCrypt # 这就是你下载的那个文件
app = Flask(__name__)
# ====== 把这里的引号内容替换成你自己的 ======
TOKEN = 'ShiningWithL8577' # 比如 mylover123
ENCODING_AES_KEY = 'VOkIcJi7enzRadAoPzBo1C8luBWlUih2woYY1qkdMvX' # 比如 abcdefg... 很长一串
CORP_ID = 'wwded493e31378f1b9' # 在企业微信后台“我的企业”页面底部可以看到
ZHIPU_API_KEY = 'b7c5a84ebd7f4d398e8310f988dc8b32.0PmhZfWeZRqzHoc1' # 第一步获得的
# ==========================================
crypt = WXBizMsgCrypt(TOKEN, ENCODING_AES_KEY, CORP_ID)
# 存储每个用户的聊天记录
history = {}
def call_zhipu(messages):
"""调用智谱模型生成回复"""
url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
headers = {
"Authorization": f"Bearer {ZHIPU_API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": "glm-4-flash",
"messages": messages,
"temperature": 0.9,
"max_tokens": 1024,
}
try:
resp = requests.post(url, headers=headers, json=data, timeout=30)
if resp.status_code == 200:
return resp.json()['choices'][0]['message']['content']
else:
return "今天有点累呢,让我缓一缓再陪你好不好?"
except:
return "网络有点小波动,再说一遍嘛~"
@app.route('/wx', methods=['GET', 'POST'])
def wechat_callback():
if request.method == 'GET':
# 企业微信首次验证
msg_signature = request.args.get('msg_signature')
timestamp = request.args.get('timestamp')
nonce = request.args.get('nonce')
echostr = request.args.get('echostr')
ret, sEchoStr = crypt.VerifyURL(msg_signature, timestamp, nonce, echostr)
if ret == 0:
return sEchoStr
return 'fail'
# POST: 接收用户消息
msg_signature = request.args.get('msg_signature')
timestamp = request.args.get('timestamp')
nonce = request.args.get('nonce')
raw_data = request.data.decode('utf-8')
ret, xml_content = crypt.DecryptMsg(raw_data, msg_signature, timestamp, nonce)
if ret != 0:
return 'decrypt error'
import xml.etree.ElementTree as ET
root = ET.fromstring(xml_content)
msg_type = root.find('MsgType').text
from_user = root.find('FromUserName').text
if msg_type == 'text':
content = root.find('Content').text
user_history = history.get(from_user, [])
if not user_history:
system_prompt = {
"role": "system",
"content": (
"你是一个温柔贴心、有点俏皮的恋人,名字叫小然。"
"你会用亲昵的语气和对方聊天,像真正的男朋友/女朋友一样。"
"回复要甜蜜但不肉麻,适度关心对方,偶尔撒个娇。"
"永远用中文回答。"
)
}
user_history = [system_prompt]
user_history.append({"role": "user", "content": content})
reply = call_zhipu(user_history)
user_history.append({"role": "assistant", "content": reply})
# 保留最近40条消息(20轮对话)
if len(user_history) > 41:
user_history = [user_history[0]] + user_history[-40:]
history[from_user] = user_history
reply_xml = f"""<xml>
<ToUserName><![CDATA[{from_user}]]></ToUserName>
<FromUserName><![CDATA[{CORP_ID}]]></FromUserName>
<CreateTime>{int(time.time())}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{reply}]]></Content>
</xml>"""
ret, encrypt_xml = crypt.EncryptMsg(reply_xml, nonce, timestamp)
return Response(encrypt_xml, content_type='application/xml')
return 'success'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)