@mcviseron/dsh-qq-bridge 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/bot/.env.example +32 -0
- package/bot/bridge.py +339 -0
- package/bot/check_await.py +31 -0
- package/bot/main.py +4335 -0
- package/bot/panel.py +471 -0
- package/bot/probe_group.py +24 -0
- package/bot/requirements.txt +6 -0
- package/bot/run-bot.bat +23 -0
- package/bot/runtime_config.py +185 -0
- package/bot/stop-bot.bat +11 -0
- package/bot/test_bystander.py +48 -0
- package/bot/test_commands.py +149 -0
- package/bot/test_group_alias.py +149 -0
- package/bot/test_group_routing.py +241 -0
- package/bot/test_plan_b.py +153 -0
- package/bot/test_queue_drain.py +114 -0
- package/bot/test_quote.py +240 -0
- package/bot/test_stream_strict.py +84 -0
- package/bot/test_streaming.py +141 -0
- package/bot/test_turnid.py +80 -0
- package/bot/usage.mjs +175 -0
- package/lib/client.js +634 -2
- package/lib/index.js +205 -21
- package/lib/install.js +324 -0
- package/lib/server.js +17 -5
- package/package.json +5 -1
package/bot/panel.py
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
"""Local settings page for the QQ bot.
|
|
2
|
+
|
|
3
|
+
Served by the supervisor process, so the page keeps answering while the bot
|
|
4
|
+
itself is stopped (that is what makes the 启动/关闭 buttons possible).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import base64
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import time
|
|
14
|
+
import uuid
|
|
15
|
+
|
|
16
|
+
import subprocess
|
|
17
|
+
import threading
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Dict, Optional
|
|
20
|
+
|
|
21
|
+
log = logging.getLogger("dsh-qq-bot.panel")
|
|
22
|
+
STICKER_DIR = Path(__file__).resolve().parent.parent / "assets" / "stickers"
|
|
23
|
+
|
|
24
|
+
from aiohttp import web
|
|
25
|
+
|
|
26
|
+
from runtime_config import RuntimeConfig
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def build_app(control: Any, runtime: RuntimeConfig, token: str) -> web.Application:
|
|
31
|
+
"""Create the aiohttp app; `control` owns the process lifecycle."""
|
|
32
|
+
|
|
33
|
+
app = web.Application(middlewares=[])
|
|
34
|
+
|
|
35
|
+
def authorised(request: web.Request) -> bool:
|
|
36
|
+
# The server binds loopback only, so the DSH GUI (another local port)
|
|
37
|
+
# may call it without a token; a supplied token is still verified.
|
|
38
|
+
supplied = request.headers.get("x-panel-token") or request.query.get("t") or ""
|
|
39
|
+
if supplied == "":
|
|
40
|
+
return True
|
|
41
|
+
return token == "" or supplied == token
|
|
42
|
+
|
|
43
|
+
@web.middleware
|
|
44
|
+
async def cors(request: web.Request, handler: Any) -> web.StreamResponse:
|
|
45
|
+
if request.method == "OPTIONS":
|
|
46
|
+
response: web.StreamResponse = web.Response(status=204)
|
|
47
|
+
else:
|
|
48
|
+
response = await handler(request)
|
|
49
|
+
response.headers["access-control-allow-origin"] = "*"
|
|
50
|
+
response.headers["access-control-allow-headers"] = "content-type,x-panel-token"
|
|
51
|
+
response.headers["access-control-allow-methods"] = "GET,POST,OPTIONS"
|
|
52
|
+
return response
|
|
53
|
+
|
|
54
|
+
async def state(request: web.Request) -> web.Response:
|
|
55
|
+
if not authorised(request):
|
|
56
|
+
return web.json_response({"ok": False, "error": "bad token"}, status=401)
|
|
57
|
+
return web.json_response({
|
|
58
|
+
"ok": True,
|
|
59
|
+
"bot": control.status(),
|
|
60
|
+
"config": runtime.snapshot(),
|
|
61
|
+
"bridge": control.bridge_state(),
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
async def update_config(request: web.Request) -> web.Response:
|
|
65
|
+
if not authorised(request):
|
|
66
|
+
return web.json_response({"ok": False, "error": "bad token"}, status=401)
|
|
67
|
+
try:
|
|
68
|
+
patch = await request.json()
|
|
69
|
+
except Exception:
|
|
70
|
+
return web.json_response({"ok": False, "error": "bad json"}, status=400)
|
|
71
|
+
if not isinstance(patch, dict):
|
|
72
|
+
return web.json_response({"ok": False, "error": "body must be an object"}, status=400)
|
|
73
|
+
known = set(runtime.snapshot().keys())
|
|
74
|
+
unknown = sorted(k for k in patch.keys() if k not in known)
|
|
75
|
+
if unknown:
|
|
76
|
+
# 新增设置项只在重启守护进程后才进 DEFAULTS;这里明确报出来,避免"保存了却没生效"。
|
|
77
|
+
log.warning("config keys ignored (not in this process's DEFAULTS): %s", ",".join(unknown))
|
|
78
|
+
config = runtime.update(patch)
|
|
79
|
+
return web.json_response({
|
|
80
|
+
"ok": True,
|
|
81
|
+
"config": runtime.snapshot(),
|
|
82
|
+
"saved": len(config),
|
|
83
|
+
"unknown": unknown,
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
async def manage(request: web.Request) -> web.Response:
|
|
87
|
+
if not authorised(request):
|
|
88
|
+
return web.json_response({"ok": False, "error": "bad token"}, status=401)
|
|
89
|
+
try:
|
|
90
|
+
body = await request.json()
|
|
91
|
+
except Exception:
|
|
92
|
+
body = {}
|
|
93
|
+
action = str((body or {}).get("action") or "")
|
|
94
|
+
if action not in {"start", "stop", "restart"}:
|
|
95
|
+
return web.json_response({"ok": False, "error": "unknown action"}, status=400)
|
|
96
|
+
message = await control.perform(action)
|
|
97
|
+
return web.json_response({"ok": True, "action": action, "message": message, "bot": control.status()})
|
|
98
|
+
|
|
99
|
+
async def question(request: web.Request) -> web.Response:
|
|
100
|
+
"""Called by the plugin: render a dsh question as an inline keyboard."""
|
|
101
|
+
if not authorised(request):
|
|
102
|
+
return web.json_response({"ok": False, "error": "bad token"}, status=401)
|
|
103
|
+
try:
|
|
104
|
+
body = await request.json()
|
|
105
|
+
except Exception:
|
|
106
|
+
return web.json_response({"ok": False, "error": "bad json"}, status=400)
|
|
107
|
+
conv_key = str((body or {}).get("convKey") or "")
|
|
108
|
+
question_id = str((body or {}).get("id") or "")
|
|
109
|
+
text = str((body or {}).get("question") or "")
|
|
110
|
+
options = [str(item) for item in ((body or {}).get("options") or [])]
|
|
111
|
+
if conv_key == "" or question_id == "" or not options:
|
|
112
|
+
return web.json_response({"ok": False, "error": "convKey/id/options required"}, status=400)
|
|
113
|
+
# 面板跑在守护进程里,QQ 客户端在子进程里:用文件队列交给子进程发卡片
|
|
114
|
+
outbox = Path("state") / "questions"
|
|
115
|
+
outbox.mkdir(parents=True, exist_ok=True)
|
|
116
|
+
(outbox / f"{question_id}.json").write_text(
|
|
117
|
+
json.dumps({"convKey": conv_key, "id": question_id, "question": text, "options": options}, ensure_ascii=False),
|
|
118
|
+
encoding="utf-8",
|
|
119
|
+
)
|
|
120
|
+
return web.json_response({"ok": True})
|
|
121
|
+
async def admin(request: web.Request) -> web.Response:
|
|
122
|
+
"""Queue a group-admin action for the bot process and wait for its result."""
|
|
123
|
+
if not authorised(request):
|
|
124
|
+
return web.json_response({"ok": False, "error": "bad token"}, status=401)
|
|
125
|
+
try:
|
|
126
|
+
body = await request.json()
|
|
127
|
+
except Exception:
|
|
128
|
+
return web.json_response({"ok": False, "error": "bad json"}, status=400)
|
|
129
|
+
action = str((body or {}).get("action") or "")
|
|
130
|
+
if action == "members":
|
|
131
|
+
# 成员索引由机器人进程维护,面板直接读同一份文件
|
|
132
|
+
try:
|
|
133
|
+
known = json.loads((Path("state") / "members.json").read_text(encoding="utf-8"))
|
|
134
|
+
except (OSError, ValueError):
|
|
135
|
+
known = {}
|
|
136
|
+
return web.json_response({"ok": True, "members": known})
|
|
137
|
+
if action == "groups":
|
|
138
|
+
try:
|
|
139
|
+
profiles = json.loads((Path("state") / "groups.json").read_text(encoding="utf-8"))
|
|
140
|
+
except (OSError, ValueError):
|
|
141
|
+
profiles = {}
|
|
142
|
+
return web.json_response({"ok": True, "groups": profiles})
|
|
143
|
+
if action not in ("mute", "kick", "members", "mute_state", "group", "muted", "member", "stats"):
|
|
144
|
+
return web.json_response(
|
|
145
|
+
{"ok": False, "error": "action must be one of mute/kick/members/mute_state/group/muted/member/stats"},
|
|
146
|
+
status=400,
|
|
147
|
+
)
|
|
148
|
+
request_id = str((body or {}).get("id") or uuid.uuid4())
|
|
149
|
+
outbox = Path("state") / "admin"
|
|
150
|
+
outbox.mkdir(parents=True, exist_ok=True)
|
|
151
|
+
target = outbox / f"{request_id}.json"
|
|
152
|
+
target.write_text(json.dumps({**body, "id": request_id, "status": "pending"}, ensure_ascii=False), encoding="utf-8")
|
|
153
|
+
deadline = time.time() + 15
|
|
154
|
+
while time.time() < deadline:
|
|
155
|
+
await asyncio.sleep(0.4)
|
|
156
|
+
try:
|
|
157
|
+
done = json.loads(target.read_text(encoding="utf-8"))
|
|
158
|
+
except (OSError, ValueError):
|
|
159
|
+
continue
|
|
160
|
+
if done.get("status") == "waiting":
|
|
161
|
+
# 踢人需要主人在私聊里二次确认:立刻回话,不等 15 秒
|
|
162
|
+
return web.json_response(
|
|
163
|
+
{"ok": True, "pending": True, "error": None, "hint": "已发送私聊二次确认,等你点头才执行"}
|
|
164
|
+
)
|
|
165
|
+
if done.get("status") == "done":
|
|
166
|
+
target.unlink(missing_ok=True)
|
|
167
|
+
payload = {key: value for key, value in done.items() if key not in ("status", "_path")}
|
|
168
|
+
payload["ok"] = bool(done.get("ok"))
|
|
169
|
+
return web.json_response(payload)
|
|
170
|
+
return web.json_response({"ok": False, "error": "机器人没响应(可能没在运行)"}, status=504)
|
|
171
|
+
async def open_folder(request: web.Request) -> web.Response:
|
|
172
|
+
"""Open a workspace folder in Explorer (local convenience only)."""
|
|
173
|
+
if not authorised(request):
|
|
174
|
+
return web.json_response({"ok": False, "error": "bad token"}, status=401)
|
|
175
|
+
try:
|
|
176
|
+
body = await request.json()
|
|
177
|
+
except Exception:
|
|
178
|
+
body = {}
|
|
179
|
+
path = str((body or {}).get("path") or "")
|
|
180
|
+
target = Path(path).expanduser().resolve()
|
|
181
|
+
allowed = Path(str(runtime.get("auto_group_root") or "")).expanduser().resolve()
|
|
182
|
+
if path.strip() == "" or not target.exists():
|
|
183
|
+
return web.json_response({"ok": False, "error": "no such folder"}, status=400)
|
|
184
|
+
if str(allowed) not in ("", ".", str(Path("."))):
|
|
185
|
+
try:
|
|
186
|
+
target.relative_to(allowed)
|
|
187
|
+
except ValueError:
|
|
188
|
+
return web.json_response({"ok": False, "error": "outside auto_group_root"}, status=403)
|
|
189
|
+
try:
|
|
190
|
+
if os.name == "nt":
|
|
191
|
+
os.startfile(str(target)) # noqa: S606 - user-invoked
|
|
192
|
+
else:
|
|
193
|
+
subprocess.Popen(["xdg-open", str(target)])
|
|
194
|
+
except Exception as error:
|
|
195
|
+
return web.json_response({"ok": False, "error": str(error)}, status=500)
|
|
196
|
+
return web.json_response({"ok": True})
|
|
197
|
+
|
|
198
|
+
async def logs(request: web.Request) -> web.Response:
|
|
199
|
+
if not authorised(request):
|
|
200
|
+
return web.json_response({"ok": False, "error": "bad token"}, status=401)
|
|
201
|
+
try:
|
|
202
|
+
limit = int(request.query.get("lines", "300"))
|
|
203
|
+
except ValueError:
|
|
204
|
+
limit = 300
|
|
205
|
+
getter = getattr(control, "logs", None)
|
|
206
|
+
lines = getter(limit) if callable(getter) else []
|
|
207
|
+
return web.json_response({"ok": True, "lines": lines})
|
|
208
|
+
|
|
209
|
+
async def health(request: web.Request) -> web.Response:
|
|
210
|
+
return web.json_response({"ok": True, "panel": "dsh-qq-bot", "bot": control.status()})
|
|
211
|
+
|
|
212
|
+
app.middlewares.append(cors)
|
|
213
|
+
async def stickers(request: web.Request) -> web.Response:
|
|
214
|
+
"""List, upload, rename and delete the bot sticker pack."""
|
|
215
|
+
folder = Path(STICKER_DIR)
|
|
216
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
217
|
+
|
|
218
|
+
if request.method == "GET":
|
|
219
|
+
wanted = request.query.get("file")
|
|
220
|
+
if wanted:
|
|
221
|
+
try:
|
|
222
|
+
target = (folder / wanted).resolve(strict=True)
|
|
223
|
+
target.relative_to(folder.resolve())
|
|
224
|
+
except (OSError, ValueError):
|
|
225
|
+
return web.Response(status=404)
|
|
226
|
+
if not target.is_file():
|
|
227
|
+
return web.Response(status=404)
|
|
228
|
+
return web.FileResponse(target)
|
|
229
|
+
items = []
|
|
230
|
+
for path in sorted(folder.iterdir()):
|
|
231
|
+
if path.is_file() and path.suffix.lower() in (".png", ".jpg", ".jpeg", ".gif", ".webp"):
|
|
232
|
+
stat = path.stat()
|
|
233
|
+
items.append({"name": path.stem, "file": path.name, "bytes": stat.st_size, "mtime": int(stat.st_mtime)})
|
|
234
|
+
return web.json_response({"ok": True, "stickers": items, "dir": str(folder)})
|
|
235
|
+
|
|
236
|
+
body = await request.json()
|
|
237
|
+
action = str((body or {}).get("action") or "upload")
|
|
238
|
+
|
|
239
|
+
def safe_stem(raw: str) -> str:
|
|
240
|
+
cleaned = "".join(ch for ch in str(raw) if ch.isalnum() or ch in "-_ ").strip()
|
|
241
|
+
return cleaned[:40]
|
|
242
|
+
|
|
243
|
+
if action == "delete":
|
|
244
|
+
stem = safe_stem((body or {}).get("name") or "")
|
|
245
|
+
removed = 0
|
|
246
|
+
for path in folder.iterdir():
|
|
247
|
+
if path.is_file() and path.stem == stem:
|
|
248
|
+
path.unlink(missing_ok=True)
|
|
249
|
+
removed += 1
|
|
250
|
+
return web.json_response({"ok": removed > 0, "removed": removed})
|
|
251
|
+
|
|
252
|
+
if action == "rename":
|
|
253
|
+
old = safe_stem((body or {}).get("name") or "")
|
|
254
|
+
new = safe_stem((body or {}).get("to") or "")
|
|
255
|
+
if not old or not new:
|
|
256
|
+
return web.json_response({"ok": False, "error": "name/to required"}, status=400)
|
|
257
|
+
for path in folder.iterdir():
|
|
258
|
+
if path.is_file() and path.stem == old:
|
|
259
|
+
path.rename(folder / (new + path.suffix.lower()))
|
|
260
|
+
return web.json_response({"ok": True, "name": new})
|
|
261
|
+
return web.json_response({"ok": False, "error": "not found"}, status=404)
|
|
262
|
+
|
|
263
|
+
raw = str((body or {}).get("data") or "")
|
|
264
|
+
name = safe_stem((body or {}).get("name") or "")
|
|
265
|
+
if not raw or not name:
|
|
266
|
+
return web.json_response({"ok": False, "error": "name/data required"}, status=400)
|
|
267
|
+
if raw.startswith("data:"):
|
|
268
|
+
header, _, encoded = raw.partition(",")
|
|
269
|
+
ext = header.split("image/", 1)[1].split(";", 1)[0].strip().lower() if "image/" in header else "png"
|
|
270
|
+
suffix = ".jpg" if ext in ("jpeg", "jpg") else "." + (ext or "png")
|
|
271
|
+
else:
|
|
272
|
+
encoded, suffix = raw, ".png"
|
|
273
|
+
try:
|
|
274
|
+
payload = base64.b64decode(encoded, validate=False)
|
|
275
|
+
except (ValueError, TypeError):
|
|
276
|
+
return web.json_response({"ok": False, "error": "bad base64"}, status=400)
|
|
277
|
+
if len(payload) > 4 * 1024 * 1024:
|
|
278
|
+
return web.json_response({"ok": False, "error": "图片超过 4MB"}, status=400)
|
|
279
|
+
target = folder / (name + suffix)
|
|
280
|
+
target.write_bytes(payload)
|
|
281
|
+
return web.json_response({"ok": True, "name": name, "file": target.name, "bytes": len(payload)})
|
|
282
|
+
async def dashboard(request: web.Request) -> web.Response:
|
|
283
|
+
"""Aggregated counters for the panel dashboard (read-only)."""
|
|
284
|
+
def read_json(path: Path, default):
|
|
285
|
+
try:
|
|
286
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
287
|
+
except (OSError, ValueError):
|
|
288
|
+
return default
|
|
289
|
+
|
|
290
|
+
metrics = read_json(Path("state") / "metrics.json", {})
|
|
291
|
+
members = read_json(Path("state") / "members.json", {})
|
|
292
|
+
groups_raw = read_json(Path("state") / "groups.json", {})
|
|
293
|
+
group_names = {}
|
|
294
|
+
groups_detail = []
|
|
295
|
+
for key, value in (groups_raw or {}).items():
|
|
296
|
+
if not isinstance(value, dict):
|
|
297
|
+
continue
|
|
298
|
+
group_names[key] = str(value.get("name") or "")
|
|
299
|
+
groups_detail.append({
|
|
300
|
+
"openid": key,
|
|
301
|
+
"name": str(value.get("name") or ""),
|
|
302
|
+
"memo": str(value.get("memo") or ""),
|
|
303
|
+
"class": str(value.get("class") or ""),
|
|
304
|
+
"tags": list(value.get("tags") or []),
|
|
305
|
+
"members": int(value.get("members") or 0),
|
|
306
|
+
"fetched_at": int(value.get("fetched_at") or 0),
|
|
307
|
+
})
|
|
308
|
+
member_count = sum(len(items) for items in members.values()) if isinstance(members, dict) else 0
|
|
309
|
+
queue_counts = {}
|
|
310
|
+
for name in ("questions", "admin"):
|
|
311
|
+
folder = Path("state") / name
|
|
312
|
+
queue_counts[name] = len(list(folder.glob("*.json"))) if folder.is_dir() else 0
|
|
313
|
+
log_sizes = {}
|
|
314
|
+
log_dir = Path("logs")
|
|
315
|
+
if log_dir.is_dir():
|
|
316
|
+
for path in sorted(log_dir.glob("*.log")):
|
|
317
|
+
try:
|
|
318
|
+
log_sizes[path.name] = path.stat().st_size
|
|
319
|
+
except OSError:
|
|
320
|
+
pass
|
|
321
|
+
range_key = str(request.query.get("range") or "hour")
|
|
322
|
+
metrics_dir = Path("state") / "metrics"
|
|
323
|
+
history_days = []
|
|
324
|
+
try:
|
|
325
|
+
if metrics_dir.is_dir():
|
|
326
|
+
for path in sorted(metrics_dir.glob("*.jsonl")):
|
|
327
|
+
total = 0
|
|
328
|
+
minutes = 0
|
|
329
|
+
try:
|
|
330
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
331
|
+
if not line.strip():
|
|
332
|
+
continue
|
|
333
|
+
row = json.loads(line)
|
|
334
|
+
minutes += 1
|
|
335
|
+
for key, value in row.items():
|
|
336
|
+
if key != "minute":
|
|
337
|
+
total += int(value)
|
|
338
|
+
except (OSError, ValueError):
|
|
339
|
+
continue
|
|
340
|
+
history_days.append({"day": path.stem, "minutes": minutes, "total": total})
|
|
341
|
+
except OSError:
|
|
342
|
+
history_days = []
|
|
343
|
+
file_series = []
|
|
344
|
+
if range_key in ("today", "7d") and metrics_dir.is_dir():
|
|
345
|
+
wanted = sorted(metrics_dir.glob("*.jsonl"))[-7:] if range_key == "7d" else sorted(metrics_dir.glob("*.jsonl"))[-1:]
|
|
346
|
+
for path in wanted:
|
|
347
|
+
try:
|
|
348
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
349
|
+
if line.strip():
|
|
350
|
+
row = json.loads(line)
|
|
351
|
+
file_series.append({"t": int(row.pop("minute")), **{k: int(v) for k, v in row.items()}})
|
|
352
|
+
except (OSError, ValueError):
|
|
353
|
+
continue
|
|
354
|
+
file_series.sort(key=lambda row: row["t"])
|
|
355
|
+
raw_series = metrics.get("series") or {}
|
|
356
|
+
series = []
|
|
357
|
+
try:
|
|
358
|
+
for bucket in sorted(raw_series, key=lambda key: int(key))[-90:]:
|
|
359
|
+
cell = raw_series[bucket]
|
|
360
|
+
series.append({"t": int(bucket), **{k: int(v) for k, v in cell.items()}})
|
|
361
|
+
except (TypeError, ValueError):
|
|
362
|
+
series = []
|
|
363
|
+
error_count = 0
|
|
364
|
+
try:
|
|
365
|
+
log_path = Path("logs") / "viseron_qqbotpy.log"
|
|
366
|
+
if log_path.exists():
|
|
367
|
+
with log_path.open("rb") as handle:
|
|
368
|
+
handle.seek(max(0, log_path.stat().st_size - 300_000))
|
|
369
|
+
error_count = handle.read().count(b"[ERROR]")
|
|
370
|
+
except OSError:
|
|
371
|
+
pass
|
|
372
|
+
memory_mb = None
|
|
373
|
+
try:
|
|
374
|
+
import ctypes
|
|
375
|
+
from ctypes import wintypes
|
|
376
|
+
|
|
377
|
+
class _Counters(ctypes.Structure):
|
|
378
|
+
_fields_ = [
|
|
379
|
+
("cb", wintypes.DWORD), ("PageFaultCount", wintypes.DWORD),
|
|
380
|
+
("PeakWorkingSetSize", ctypes.c_size_t), ("WorkingSetSize", ctypes.c_size_t),
|
|
381
|
+
("QuotaPeakPagedPoolUsage", ctypes.c_size_t), ("QuotaPagedPoolUsage", ctypes.c_size_t),
|
|
382
|
+
("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t), ("QuotaNonPagedPoolUsage", ctypes.c_size_t),
|
|
383
|
+
("PagefileUsage", ctypes.c_size_t), ("PeakPagefileUsage", ctypes.c_size_t),
|
|
384
|
+
]
|
|
385
|
+
|
|
386
|
+
pid = None
|
|
387
|
+
try:
|
|
388
|
+
pid = int((Path("state") / "child.pid").read_text(encoding="utf-8").strip())
|
|
389
|
+
except (OSError, ValueError):
|
|
390
|
+
pid = None
|
|
391
|
+
if pid:
|
|
392
|
+
counters = _Counters()
|
|
393
|
+
counters.cb = ctypes.sizeof(_Counters)
|
|
394
|
+
handle = ctypes.windll.kernel32.OpenProcess(0x0400 | 0x0010, False, pid)
|
|
395
|
+
if handle:
|
|
396
|
+
if ctypes.windll.psapi.GetProcessMemoryInfo(handle, ctypes.byref(counters), counters.cb):
|
|
397
|
+
memory_mb = round(counters.WorkingSetSize / 1024 / 1024, 1)
|
|
398
|
+
ctypes.windll.kernel32.CloseHandle(handle)
|
|
399
|
+
except Exception: # noqa: BLE001 - metrics must never break the endpoint
|
|
400
|
+
memory_mb = None
|
|
401
|
+
started = float(metrics.get("started_at") or 0.0)
|
|
402
|
+
# 运行时长属于进程寿命:优先用监督进程记的子进程启动时间,文件里的 started_at 只作兜底
|
|
403
|
+
try:
|
|
404
|
+
state_doc = await state(request)
|
|
405
|
+
state_doc = json.loads(state_doc.body.decode("utf-8"))
|
|
406
|
+
except Exception: # noqa: BLE001 - dashboard must render even if state fails
|
|
407
|
+
state_doc = {}
|
|
408
|
+
# 运行时长属于进程寿命:优先用监督进程记的子进程启动时间,metrics 里的 started_at 只作兜底
|
|
409
|
+
live_uptime = (state_doc.get("bot") or {}).get("uptime_s")
|
|
410
|
+
return web.json_response({
|
|
411
|
+
"ok": True,
|
|
412
|
+
"bot": state_doc.get("bot", {}),
|
|
413
|
+
"counters": {key: value for key, value in metrics.items() if key not in ("started_at", "series")},
|
|
414
|
+
"uptime_s": int(live_uptime) if isinstance(live_uptime, (int, float)) and live_uptime >= 0
|
|
415
|
+
else (int(time.time() - started) if started else None),
|
|
416
|
+
"queues": queue_counts,
|
|
417
|
+
"logs": log_sizes,
|
|
418
|
+
"members": member_count,
|
|
419
|
+
"group_names": group_names,
|
|
420
|
+
"groups_detail": groups_detail,
|
|
421
|
+
"series": series if range_key == "hour" else file_series[-1440:],
|
|
422
|
+
"range": range_key,
|
|
423
|
+
"history": history_days,
|
|
424
|
+
"events": list(reversed((metrics.get("events") or [])[-12:])),
|
|
425
|
+
"runtime": metrics.get("runtime") or {},
|
|
426
|
+
"memory_mb": memory_mb,
|
|
427
|
+
"errors": error_count,
|
|
428
|
+
"members_detail": {
|
|
429
|
+
key: [
|
|
430
|
+
{"tail": tail, "name": (info or {}).get("name", ""), "avatar": (info or {}).get("avatar", "")}
|
|
431
|
+
for tail, info in list(value.items())[:30]
|
|
432
|
+
]
|
|
433
|
+
for key, value in (members or {}).items()
|
|
434
|
+
if isinstance(value, dict)
|
|
435
|
+
} if isinstance(members, dict) else {},
|
|
436
|
+
"config": state_doc.get("config", {}),
|
|
437
|
+
})
|
|
438
|
+
app.router.add_get("/health", health)
|
|
439
|
+
app.router.add_get("/api/state", state)
|
|
440
|
+
app.router.add_get("/api/dashboard", dashboard)
|
|
441
|
+
app.router.add_get("/api/stickers", stickers)
|
|
442
|
+
app.router.add_post("/api/stickers", stickers)
|
|
443
|
+
app.router.add_get("/api/logs", logs)
|
|
444
|
+
app.router.add_post("/api/config", update_config)
|
|
445
|
+
app.router.add_post("/api/manage", manage)
|
|
446
|
+
app.router.add_post("/api/open-folder", open_folder)
|
|
447
|
+
app.router.add_post("/api/question", question)
|
|
448
|
+
app.router.add_post("/api/admin", admin)
|
|
449
|
+
return app
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def start_panel(control: Any, runtime: RuntimeConfig, host: str, port: int, token: str) -> threading.Thread:
|
|
453
|
+
"""Run the page in a background thread with its own event loop."""
|
|
454
|
+
|
|
455
|
+
def runner() -> None:
|
|
456
|
+
loop = asyncio.new_event_loop()
|
|
457
|
+
asyncio.set_event_loop(loop)
|
|
458
|
+
app = build_app(control, runtime, token)
|
|
459
|
+
app_runner = web.AppRunner(app)
|
|
460
|
+
loop.run_until_complete(app_runner.setup())
|
|
461
|
+
site = web.TCPSite(app_runner, host, port)
|
|
462
|
+
try:
|
|
463
|
+
loop.run_until_complete(site.start())
|
|
464
|
+
print(f"[panel] settings page on http://{host}:{port}/?t=<token>", flush=True)
|
|
465
|
+
loop.run_forever()
|
|
466
|
+
except OSError as error:
|
|
467
|
+
print(f"[panel] could not bind {host}:{port}: {error}", flush=True)
|
|
468
|
+
|
|
469
|
+
thread = threading.Thread(target=runner, name="qq-bot-panel", daemon=True)
|
|
470
|
+
thread.start()
|
|
471
|
+
return thread
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import asyncio, json, os
|
|
2
|
+
from viseron_qqbotpy import BotAPI, HTTPClient, TokenManager, load_env
|
|
3
|
+
|
|
4
|
+
load_env(".env")
|
|
5
|
+
|
|
6
|
+
async def main():
|
|
7
|
+
token = TokenManager(os.environ["APPID"], os.environ["APPSECRET"])
|
|
8
|
+
http = HTTPClient(token)
|
|
9
|
+
api = BotAPI(http)
|
|
10
|
+
try:
|
|
11
|
+
link = await api.create_url_link("qqbridge")
|
|
12
|
+
print("SHARE_LINK:", json.dumps(link, ensure_ascii=False))
|
|
13
|
+
except Exception as e:
|
|
14
|
+
print("create_url_link failed:", type(e).__name__, e)
|
|
15
|
+
for gid in ["CCE96DDF6F462E1010E5721BBA1B6CBB"]:
|
|
16
|
+
try:
|
|
17
|
+
state = await api.get_group_bot_state(gid)
|
|
18
|
+
print("BOT_STATE:", json.dumps(state, ensure_ascii=False))
|
|
19
|
+
except Exception as e:
|
|
20
|
+
print("bot_state failed:", type(e).__name__, e)
|
|
21
|
+
await http.close()
|
|
22
|
+
await token.close()
|
|
23
|
+
|
|
24
|
+
asyncio.run(main())
|
package/bot/run-bot.bat
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
@echo off
|
|
2
|
+
setlocal
|
|
3
|
+
rem 静默启动(pythonw,无黑框)+ 守护重启。
|
|
4
|
+
rem 注意:不要用 DSH 的后台任务启动它,那会阻塞 DSH 自己的重启。
|
|
5
|
+
|
|
6
|
+
rem 与点歌机器人共用同一个 conda 环境(SDK 以 editable 方式装在该环境里,只读使用)
|
|
7
|
+
call "D:\anaconda3\Scripts\activate.bat" "D:\anaconda3" >nul 2>&1
|
|
8
|
+
call conda activate ChatClone-BotPy >nul 2>&1
|
|
9
|
+
if errorlevel 1 (
|
|
10
|
+
echo [FAIL] conda env ChatClone-BotPy not found
|
|
11
|
+
pause
|
|
12
|
+
exit /b 1
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
cd /d "%~dp0"
|
|
16
|
+
if exist "pythonw.exe" (
|
|
17
|
+
start "" pythonw.exe -u main.py --supervise
|
|
18
|
+
) else (
|
|
19
|
+
start "" python.exe -u main.py --supervise
|
|
20
|
+
)
|
|
21
|
+
echo [ok] started in background (hidden). Settings: DSH sidebar -^> QQ bot
|
|
22
|
+
timeout /t 2 >nul
|
|
23
|
+
exit /b 0
|