Repository navigation
Expand file tree
/
Copy pathfunction.py
More file actions
210 lines (174 loc) · 7.13 KB
/
Copy pathfunction.py
File metadata and controls
210 lines (174 loc) · 7.13 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
from datetime import datetime
import asyncio
import json
import os
from pathlib import Path
import time
import aiohttp
from life import Life
from wechat_ilink import send_text_message
def require_env(name: str) -> str:
value = os.getenv(name)
if not value:
raise RuntimeError(f"Missing required environment variable: {name}")
return value
messages = [
{
"role": "system",
"content": "you are a helpful assistant",
},
]
API_KEY = require_env("REALRPG_API_KEY")
BASE_URL = os.getenv("REALRPG_BASE_URL", "https://api.deepseek.com")
MODEL = os.getenv("REALRPG_MODEL", "deepseek-chat")
DATA_DIR = Path(os.getenv("REALRPG_DATA_DIR", "Data"))
context_timeout = 60 * 60 * 10
context_max_length = 7
USER_CONTEXT_FILE = DATA_DIR / "user.json"
ROOM_CONTEXT_FILE = DATA_DIR / "room.json"
def load_json_file(path: Path, default: dict) -> dict:
if not path.exists():
return default
with path.open("r", encoding="utf-8") as file:
return json.load(file)
def save_json_file(path: Path, payload: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as file:
json.dump(payload, file, ensure_ascii=False, indent=4)
async def send_txt_msg(wxid, content, atlist=None):
if atlist:
content = f"{content}\n\n@{', '.join(atlist)}"
return await send_text_message(wxid, content)
async def send_txt_msg2(wxid, content, atlist=None):
return await send_txt_msg(wxid, content, atlist)
def read_last_lines(filename, num_lines):
with open(filename, "r", encoding="utf-8") as file:
lines = file.readlines()
return lines[-num_lines:]
async def write_work_log(wxid, content, timestamp=None):
life = Life()
if wxid == "wxid_6uj28bul7xqc22":
life = Life()
elif wxid == "wxid_o0egznhpo9j022":
life = Life(db_path="Data/life_lyy.db")
if content == "#删除":
await life.delete_latest_entry()
await send_txt_msg(wxid, "ok")
return
print(len(content))
if len(content) > 1000:
return
content = content[1:]
parts = content.split(" ")
if len(parts) < 3 or not parts[-1].isdigit():
await send_txt_msg(wxid, "格式错误:需要包含时长字段!\n正确格式:#类型 内容 时长\n例如:#运动 跑步 30")
return
type_ = parts[0]
duration = int(parts[-1])
content = " ".join(parts[1:-1])
await life.insert_life_entry(type_, content, duration)
last_ten_lines = await life.get_latest_entries()
today = int(time.time()) + 100
yesterday = int(today - 60 * 60 * 36)
history = ""
for i in range(0, 9):
line = last_ten_lines[9 - i]
if line[1] < today and line[1] > yesterday:
date_time = datetime.fromtimestamp(line[1]).strftime("%m.%d ")
duration_str = f" [{line[6]}分钟]" if len(line) > 4 else ""
record = str(line[0]) + f". {date_time}" + f"{line[2]} " + f"{line[3]}{duration_str}\n"
history += record
history += f"最新一条:{type_} + {content} + {duration}分钟"
await send_txt_msg(wxid, f"已成功记入\n最近记录\n{history}")
def add_context(role, old_msg, new_msg):
new_context = old_msg[:]
new_context.append({"role": role, "content": new_msg})
if len(new_context) > context_max_length:
new_context.pop(1)
return new_context
async def room_chat(msg, from_wxid, room_wxid):
room_info = load_json_file(ROOM_CONTEXT_FILE, {})
msg = msg.split("\u2005")[-1]
if room_wxid not in room_info:
room_info[room_wxid] = {"created_time": time.time()}
if from_wxid not in room_info[room_wxid]:
room_info[room_wxid][from_wxid] = {
"last_interaction": time.time(),
"context": add_context("user", messages, msg),
}
elif time.time() - room_info[room_wxid][from_wxid]["last_interaction"] <= context_timeout:
room_info[room_wxid][from_wxid] = {
"last_interaction": time.time(),
"context": add_context("user", room_info[room_wxid][from_wxid]["context"], msg),
}
else:
room_info[room_wxid][from_wxid] = {
"last_interaction": time.time(),
"context": add_context("user", messages, msg),
}
reply_from_bot = await fetch_open_ai_reply(
MODEL,
room_info[room_wxid][from_wxid]["context"],
API_KEY,
BASE_URL,
)
room_info[room_wxid][from_wxid] = {
"last_interaction": time.time(),
"context": add_context("assistant", room_info[room_wxid][from_wxid]["context"], reply_from_bot),
}
save_json_file(ROOM_CONTEXT_FILE, room_info)
await send_txt_msg(wxid=room_wxid, content=reply_from_bot, atlist=None)
async def private_chat(msg, uid):
user_info = load_json_file(USER_CONTEXT_FILE, {})
if uid not in user_info:
user_info[uid] = {"last_interaction": time.time(), "context": add_context("user", messages, msg)}
elif time.time() - user_info[uid]["last_interaction"] <= context_timeout:
user_info[uid] = {
"last_interaction": time.time(),
"context": add_context("user", user_info[uid]["context"], msg),
}
else:
user_info[uid] = {"last_interaction": time.time(), "context": add_context("user", messages, msg)}
reply_from_bot = await fetch_open_ai_reply(MODEL, user_info[uid]["context"], API_KEY, BASE_URL)
user_info[uid] = {
"last_interaction": time.time(),
"context": add_context("assistant", user_info[uid]["context"], reply_from_bot),
}
save_json_file(USER_CONTEXT_FILE, user_info)
await send_txt_msg(wxid=uid, content=reply_from_bot, atlist=None)
async def fetch_open_ai_reply(model, user_msg, key, base_url):
url = base_url + "/chat/completions"
payload = {
"model": model,
"messages": user_msg,
"stream": False,
}
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {key}",
"Content-Type": "application/json",
}
try:
connector = aiohttp.TCPConnector(
verify_ssl=False,
force_close=True,
enable_cleanup_closed=True,
)
timeout = aiohttp.ClientTimeout(total=90)
async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
async with session.post(url, headers=headers, json=payload, proxy=None) as response:
if response.status == 200:
data = await response.json()
return data["choices"][0]["message"]["content"]
error_text = await response.text()
print(f"API请求失败: {response.status} - {error_text}")
return f"抱歉,服务暂时不可用 (错误码: {response.status})"
except aiohttp.ClientConnectorError as e:
print(f"连接错误: {str(e)}")
return "抱歉,无法连接到服务器,请检查网络连接"
except asyncio.TimeoutError:
print("请求超时")
return "抱歉,请求超时,请稍后再试"
except Exception as e:
print(f"发生未知错误: {str(e)}")
return "抱歉,服务出现异常,请稍后再试"