Files
jsmind_xiezuo_project/wechat/wechat_test.py
T
2024-05-20 20:30:51 +08:00

106 lines
4.2 KiB
Python

#!/usr/bin/env python
# 后端
# WS server example that synchronizes state across clients
import asyncio
import json
import websockets
import re
from zhipuai import ZhipuAI
conversation_history = []
async def gml_chat(messages,conversation_history):
if len(conversation_history) >= 4:
conversation_history.pop(0)
print("-==========================---")
print(conversation_history)
client = ZhipuAI(api_key="92a0e4868cda21d22fe6fd0f4c0bf6fb.oZ4IE9PPDOhsLKPp")
conversation_history.append({"role": "user", "content": messages})
# conversation_history.extend(messages)
response = client.chat.completions.create(
model="glm-3-turbo",
# messages=[
# {
# "role": "user",
# "content": prompt
# }
# ],
messages = conversation_history,
top_p=0.7,
temperature=0.95,
max_tokens=1024,
stream=True,
)
content = ""
for trunk in response:
# print(trunk.choices[0].delta)
content = content + trunk.choices[0].delta.content
conversation_history.append({"role": "assistant", "content": content})
robot_message = json.dumps(
{"type": "user", "content": content, "from": "机器人"})
await asyncio.wait([user.send(robot_message) for user in USERS.values()])
return content
# print(gml_chat("你好"))
# 名字:websockets
USERS = {}
async def chat(websocket, path):
# 握手
await websocket.send(json.dumps({"type": "handshake"}))
async for message in websocket:
data = json.loads(message)
print("---------------------")
print(data)
print(data['content'])
message = ''
# 用户发信息
if data["type"] == 'send':
name = '404'
for k, v in USERS.items():
if v == websocket:
name = k
pattern = r"@机器人"
matches = re.findall(pattern, data['content'])
if len(USERS) != 0:
if len(matches):
question_rebot = re.sub(pattern, "", data['content'])
# robot_reply = await gml_chat(question_rebot) # 获取机器人的回复
message = json.dumps(
{"type": "user", "content": data["content"], "from": name})
await asyncio.wait([user.send(message) for user in USERS.values()])
robot_reply = await gml_chat(question_rebot,conversation_history) # 获取机器人的回复
# await asyncio.wait([user.send(message) for user in USERS.values()])
# robot_message = json.dumps(
# {"type": "user", "content": robot_reply, "from": "机器人"})
# # await asyncio.wait([user.send(robot_message) for user in USERS.values()])
else:
message = json.dumps(
{"type": "user", "content": data["content"], "from": name})
await asyncio.wait([user.send(message) for user in USERS.values()])
# if len(USERS) != 0: # asyncio.wait doesn't accept an empty list
# message = json.dumps(
# {"type": "user", "content": data["content"], "from": name})
#用户登录
elif data["type"] == 'login':
USERS[data["content"]] = websocket
if len(USERS) != 0: # asyncio.wait doesn't accept an empty list
message = json.dumps(
{"type": "login", "content": data["content"], "user_list": list(USERS.keys())})
await asyncio.wait([user.send(message) for user in USERS.values()])
#用户退出
elif data["type"] == 'logout':
del USERS[data["content"]]
if len(USERS) != 0: # asyncio.wait doesn't accept an empty list
message = json.dumps(
{"type": "logout", "content": data["content"], "user_list": list(USERS.keys())})
await asyncio.wait([user.send(message) for user in USERS.values()])
# 群发
# await asyncio.wait([user.send(message) for user in USERS.values()])
start_server = websockets.serve(chat, "0.0.0.0", 9001)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()