qqbot-cli 1.0.0__py3-none-any.whl

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.
qqbot_cli/runner.py ADDED
@@ -0,0 +1,152 @@
1
+ # -*- coding: utf-8 -*-
2
+ """建虚拟环境、装依赖、启动主程序。
3
+
4
+ **为什么用虚拟环境**:主程序需要 `Werkzeug>=3.1.9`(安全修复版)等固定版本。
5
+ 直接装进用户系统 Python 可能和他们已有的包冲突,装了也可能起不来。
6
+ 每个安装目录一个 `.venv`,升级、删除都不影响系统环境。
7
+ """
8
+
9
+ import json
10
+ import os
11
+ import subprocess
12
+ import sys
13
+ from typing import Callable, Dict, List, Optional
14
+
15
+ from . import paths
16
+
17
+
18
+ class SetupError(RuntimeError):
19
+ """建环境/装依赖失败。"""
20
+
21
+
22
+ def _run(cmd: List[str], cwd: Optional[str] = None, timeout: int = 900,
23
+ progress: Optional[Callable[[str], None]] = None) -> subprocess.CompletedProcess:
24
+ """跑一个子进程并收集输出(失败时把最后几行带进异常)。"""
25
+ if progress:
26
+ progress(" ".join(cmd[:4]) + (" …" if len(cmd) > 4 else ""))
27
+ try:
28
+ completed = subprocess.run(
29
+ cmd, cwd=cwd, timeout=timeout,
30
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
31
+ text=True, encoding="utf-8", errors="replace")
32
+ except FileNotFoundError:
33
+ raise SetupError("找不到命令:%s" % cmd[0])
34
+ except subprocess.TimeoutExpired:
35
+ raise SetupError("命令超时(%d 秒):%s" % (timeout, " ".join(cmd[:3])))
36
+ if completed.returncode != 0:
37
+ tail = "\n".join((completed.stdout or "").strip().splitlines()[-12:])
38
+ raise SetupError("命令失败(退出码 %d):%s\n%s"
39
+ % (completed.returncode, " ".join(cmd[:3]), tail))
40
+ return completed
41
+
42
+
43
+ def check_python() -> None:
44
+ """启动器自己所在解释器要 >=3.9(和主程序一致)。"""
45
+ if sys.version_info < paths.MIN_PYTHON:
46
+ raise SetupError(
47
+ "需要 Python %d.%d 或更高版本,当前是 %d.%d"
48
+ % (paths.MIN_PYTHON[0], paths.MIN_PYTHON[1],
49
+ sys.version_info[0], sys.version_info[1]))
50
+
51
+
52
+ def ensure_venv(install_dir: str, progress: Optional[Callable[[str], None]] = None) -> str:
53
+ """建好 `<安装目录>/.venv`,返回里面的 python 路径。已存在就直接用。"""
54
+ python = paths.venv_python(install_dir)
55
+ if os.path.exists(python):
56
+ return python
57
+ if progress:
58
+ progress("创建虚拟环境 …")
59
+ try:
60
+ _run([paths.current_python(), "-m", "venv",
61
+ os.path.join(install_dir, paths.VENV_DIR)], timeout=300)
62
+ except SetupError as exc:
63
+ raise SetupError("创建虚拟环境失败:%s\n"
64
+ "(Linux 上可能需要装 python3-venv)" % exc)
65
+ if not os.path.exists(python):
66
+ raise SetupError("虚拟环境建好了但找不到 python:%s" % python)
67
+ return python
68
+
69
+
70
+ def install_requirements(install_dir: str, python: str,
71
+ progress: Optional[Callable[[str], None]] = None) -> None:
72
+ """装主程序的依赖。优先用装好的 requirements.txt,没有就用内置清单。"""
73
+ if progress:
74
+ progress("安装依赖(首次可能要一两分钟)…")
75
+ requirement_file = os.path.join(install_dir, "requirements.txt")
76
+ if os.path.exists(requirement_file):
77
+ cmd = [python, "-m", "pip", "install", "-q", "-r", requirement_file]
78
+ else:
79
+ cmd = [python, "-m", "pip", "install", "-q"] + list(paths.PROGRAM_REQUIRES)
80
+ try:
81
+ _run(cmd, timeout=1800)
82
+ except SetupError as exc:
83
+ raise SetupError("安装依赖失败:%s\n"
84
+ "(如果是网络问题,可以配国内镜像后重试:\n"
85
+ " pip config set global.index-url "
86
+ "https://pypi.tuna.tsinghua.edu.cn/simple)" % exc)
87
+
88
+
89
+ def verify_dependencies(python: str) -> Dict[str, str]:
90
+ """确认关键依赖真的能导入;返回 {包名: 版本}。"""
91
+ script = (
92
+ "import json\n"
93
+ "from importlib.metadata import version\n"
94
+ "out = {}\n"
95
+ "for name in ('Flask', 'Werkzeug', 'requests', 'websocket-client'):\n"
96
+ " try:\n"
97
+ " out[name] = version(name)\n"
98
+ " except Exception:\n"
99
+ " out[name] = ''\n"
100
+ "print(json.dumps(out))\n"
101
+ )
102
+ completed = subprocess.run([python, "-c", script], capture_output=True,
103
+ text=True, encoding="utf-8", errors="replace",
104
+ timeout=120)
105
+ if completed.returncode != 0:
106
+ raise SetupError("依赖自检失败:%s" % (completed.stderr or "").strip()[:300])
107
+ try:
108
+ data = json.loads(completed.stdout.strip().splitlines()[-1])
109
+ except Exception:
110
+ raise SetupError("依赖自检返回内容无法解析")
111
+ missing = [name for name, ver in data.items() if not ver]
112
+ if missing:
113
+ raise SetupError("这些依赖没装上:%s" % ", ".join(missing))
114
+ return data
115
+
116
+
117
+ def launch(install_dir: str, python: str, extra_args: Optional[List[str]] = None) -> int:
118
+ """在当前进程里直接跑主程序(前台运行,Ctrl+C 退出)。"""
119
+ entry = os.path.join(install_dir, "run.py")
120
+ if not os.path.exists(entry):
121
+ raise SetupError("安装目录里找不到 run.py:%s" % install_dir)
122
+ cmd = [python, entry] + list(extra_args or [])
123
+ try:
124
+ # 前台交接:让主程序直接接管这个终端(能看到彩色日志、能 Ctrl+C)
125
+ return subprocess.call(cmd, cwd=install_dir)
126
+ except KeyboardInterrupt:
127
+ return 0
128
+
129
+
130
+ def is_installed(install_dir: str) -> bool:
131
+ """判断这个目录里是否已经装好了主程序。"""
132
+ marker = os.path.join(install_dir, paths.MARKER_FILE)
133
+ entry = os.path.join(install_dir, "run.py")
134
+ return os.path.exists(marker) and os.path.exists(entry)
135
+
136
+
137
+ def read_marker(install_dir: str) -> Dict:
138
+ marker = os.path.join(install_dir, paths.MARKER_FILE)
139
+ try:
140
+ with open(marker, "r", encoding="utf-8") as handle:
141
+ data = json.load(handle)
142
+ return data if isinstance(data, dict) else {}
143
+ except Exception:
144
+ return {}
145
+
146
+
147
+ def write_marker(install_dir: str, data: Dict) -> None:
148
+ marker = os.path.join(install_dir, paths.MARKER_FILE)
149
+ payload = dict(data or {})
150
+ payload["install_dir"] = install_dir
151
+ with open(marker, "w", encoding="utf-8") as handle:
152
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
qqbot_cli/uninstall.py ADDED
@@ -0,0 +1,260 @@
1
+ # -*- coding: utf-8 -*-
2
+ """卸载与数据导出。
3
+
4
+ **两件事分开做**:
5
+ · **导出**:把 `config.json` + `data/` 打包成一个 zip,放哪儿都行;
6
+ · **卸载**:删掉安装目录。删之前先问要不要导出 —— 不导出就删,数据就真没了。
7
+
8
+ `data/` 里的东西是用户自己的(消息库、媒体、日志),所以默认行为是**先问**,
9
+ 而不是默认删除。导出用 zip,Windows / Linux / macOS 都能双击打开。
10
+ """
11
+
12
+ import os
13
+ import shutil
14
+ import zipfile
15
+ from typing import Callable, Dict, List, Optional, Tuple
16
+
17
+ from . import paths
18
+
19
+ # 导出时一定要带上的(存在才带)
20
+ EXPORT_ITEMS = ("config.json", "data")
21
+ # 不算「数据」的东西,导出时不带(体积大、可重建、或纯缓存)
22
+ EXPORT_SKIP_DIRS = {"__pycache__", ".venv", ".git", "node_modules"}
23
+ EXPORT_SKIP_SUFFIXES = (".pyc", ".pyo", ".log.1", ".db-wal", ".db-shm")
24
+
25
+
26
+ class UninstallError(RuntimeError):
27
+ """卸载/导出过程中的可预期错误。"""
28
+
29
+
30
+ # ---------------------------------------------------------------- 统计
31
+ def measure(install_dir: str) -> Dict:
32
+ """统计安装目录里有什么、多大、有多少条消息,卸载前给用户看。
33
+
34
+ 返回 {exists, total_bytes, total_files, data_bytes, data_files,
35
+ has_config, has_data, extra},`extra` 是既不属于程序也不属于数据的
36
+ 条目(用户自己放进去的东西)。
37
+ """
38
+ info = {
39
+ "exists": os.path.isdir(install_dir),
40
+ "total_bytes": 0, "total_files": 0,
41
+ "data_bytes": 0, "data_files": 0,
42
+ "has_config": False, "has_data": False,
43
+ "extra": [],
44
+ }
45
+ if not info["exists"]:
46
+ return info
47
+ info["has_config"] = os.path.exists(os.path.join(install_dir, "config.json"))
48
+ info["has_data"] = os.path.isdir(os.path.join(install_dir, "data"))
49
+ for name in os.listdir(install_dir):
50
+ full = os.path.join(install_dir, name)
51
+ if name == "data":
52
+ size, count = _walk_size(full)
53
+ info["data_bytes"] = size
54
+ info["data_files"] = count
55
+ if os.path.isfile(full):
56
+ try:
57
+ info["total_bytes"] += os.path.getsize(full)
58
+ info["total_files"] += 1
59
+ except OSError:
60
+ pass
61
+ elif os.path.isdir(full):
62
+ size, count = _walk_size(full)
63
+ info["total_bytes"] += size
64
+ info["total_files"] += count
65
+ # 既不是程序文件也不是数据的条目
66
+ program_items = set(EXPORT_ITEMS) | {
67
+ "run.py", "core", "web", "plugins", "docs", "tools", "tests",
68
+ "build_exe.py", "build_exe.bat", "requirements.txt", "README.md",
69
+ "AGENTS.md", "LICENSE", "PACKAGING.md", "start.bat", "start.sh",
70
+ paths.MARKER_FILE, paths.VENV_DIR, ".gitattributes", ".gitignore",
71
+ "config配置说明文件.txt", ".qqbot-download",
72
+ }
73
+ for name in os.listdir(install_dir):
74
+ if name not in program_items:
75
+ info["extra"].append(name)
76
+ return info
77
+
78
+
79
+ def _walk_size(root: str) -> Tuple[int, int]:
80
+ total = 0
81
+ count = 0
82
+ for base, dirs, files in os.walk(root):
83
+ dirs[:] = [d for d in dirs if d not in EXPORT_SKIP_DIRS]
84
+ for name in files:
85
+ try:
86
+ total += os.path.getsize(os.path.join(base, name))
87
+ count += 1
88
+ except OSError:
89
+ continue
90
+ return total, count
91
+
92
+
93
+ def human_size(num: int) -> str:
94
+ size = float(max(0, num))
95
+ for unit in ("B", "KB", "MB", "GB"):
96
+ if size < 1024 or unit == "GB":
97
+ if unit == "B":
98
+ return "%d %s" % (int(size), unit)
99
+ return "%.1f %s" % (size, unit)
100
+ size /= 1024
101
+ return "%.1f GB" % size
102
+
103
+
104
+ # ---------------------------------------------------------------- 导出
105
+ def default_export_path(install_dir: str) -> str:
106
+ """默认导出到哪:安装目录**外面**,避免连着一起被删。"""
107
+ parent = os.path.dirname(os.path.abspath(install_dir).rstrip("/\\")) or "."
108
+ base = os.path.basename(os.path.abspath(install_dir).rstrip("/\\")) or "qqbot"
109
+ stamp = _timestamp()
110
+ return os.path.join(parent, "%s-backup-%s.zip" % (base, stamp))
111
+
112
+
113
+ def _timestamp() -> str:
114
+ import time
115
+ return time.strftime("%Y%m%d_%H%M%S")
116
+
117
+
118
+ def export_data(install_dir: str, target: str,
119
+ progress: Optional[Callable[[str], None]] = None) -> Dict:
120
+ """把 `config.json` + `data/` 打包成 zip。
121
+
122
+ 返回 {path, bytes, files, skipped}。`skipped` 是被跳过的文件
123
+ (正在被占用、读不了等),不会因此中断整个导出。
124
+ """
125
+ if not os.path.isdir(install_dir):
126
+ raise UninstallError("安装目录不存在:%s" % install_dir)
127
+ config = os.path.join(install_dir, "config.json")
128
+ data_dir = os.path.join(install_dir, "data")
129
+ if not os.path.exists(config) and not os.path.isdir(data_dir):
130
+ raise UninstallError("这个目录里没有 config.json 也没有 data/,没什么可导出的")
131
+
132
+ target = os.path.abspath(target)
133
+ if not target.lower().endswith(".zip"):
134
+ target += ".zip"
135
+ parent = os.path.dirname(target)
136
+ if parent and not os.path.isdir(parent):
137
+ raise UninstallError("导出位置的上级目录不存在:%s" % parent)
138
+ # 不允许导到 data/ 里面(边写边打包会把自己装进去)
139
+ try:
140
+ inside = os.path.commonpath([os.path.abspath(target), os.path.abspath(data_dir)]) \
141
+ == os.path.abspath(data_dir)
142
+ except ValueError:
143
+ inside = False
144
+ if inside:
145
+ raise UninstallError("导出文件不能放在 data/ 目录里面")
146
+
147
+ if progress:
148
+ progress("正在打包配置与数据 …")
149
+ files = 0
150
+ skipped: List[str] = []
151
+ try:
152
+ with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED,
153
+ compresslevel=6) as bundle:
154
+ if os.path.exists(config):
155
+ try:
156
+ bundle.write(config, "config.json")
157
+ files += 1
158
+ except OSError:
159
+ skipped.append("config.json")
160
+ if os.path.isdir(data_dir):
161
+ for base, dirs, names in os.walk(data_dir):
162
+ dirs[:] = [d for d in dirs if d not in EXPORT_SKIP_DIRS]
163
+ for name in names:
164
+ full = os.path.join(base, name)
165
+ relative = os.path.relpath(full, install_dir).replace("\\", "/")
166
+ try:
167
+ bundle.write(full, relative)
168
+ files += 1
169
+ except (OSError, ValueError):
170
+ # 被占用/没权限:跳过并记下来,不中断整个导出
171
+ skipped.append(relative)
172
+ except OSError as exc:
173
+ _quiet_remove(target)
174
+ raise UninstallError("写导出文件失败:%s" % exc)
175
+ try:
176
+ size = os.path.getsize(target)
177
+ except OSError:
178
+ size = 0
179
+ return {"path": target, "bytes": size, "files": files, "skipped": skipped}
180
+
181
+
182
+ def _quiet_remove(path: str) -> None:
183
+ try:
184
+ if os.path.exists(path):
185
+ os.remove(path)
186
+ except OSError:
187
+ pass
188
+
189
+
190
+ # ---------------------------------------------------------------- 卸载
191
+ def uninstall(install_dir: str, progress: Optional[Callable[[str], None]] = None) -> Dict:
192
+ """删除整个安装目录。
193
+
194
+ **调用方必须先确认过**(问过用户要不要导出)。这里只负责删,并且:
195
+ · 校验目录看起来确实是本程序的安装目录 —— 防止把用户随手输的路径删掉;
196
+ · 删不掉的文件单独列出来(Windows 上文件被占用很常见)。
197
+ """
198
+ install_dir = os.path.abspath(install_dir)
199
+ if not os.path.isdir(install_dir):
200
+ raise UninstallError("安装目录不存在:%s" % install_dir)
201
+ # 安全检查:必须是本程序的安装目录
202
+ looks_like_ours = (
203
+ os.path.exists(os.path.join(install_dir, "run.py"))
204
+ or os.path.exists(os.path.join(install_dir, paths.MARKER_FILE))
205
+ or os.path.exists(os.path.join(install_dir, "config.json")))
206
+ if not looks_like_ours:
207
+ raise UninstallError(
208
+ "这个目录看起来不是 QQBotMerged 的安装目录(没有 run.py / 安装记录),"
209
+ "为安全起见没有删除:%s" % install_dir)
210
+ # 再挡一次:不允许删到根目录/盘符/用户主目录
211
+ guarded = {os.path.abspath(os.sep), os.path.abspath(os.path.expanduser("~"))}
212
+ try:
213
+ guarded.add(os.path.abspath(os.path.dirname(os.path.expanduser("~"))))
214
+ except Exception:
215
+ pass
216
+ if install_dir in guarded or len(install_dir) <= 3:
217
+ raise UninstallError("拒绝删除这个路径(太靠近根目录):%s" % install_dir)
218
+
219
+ if progress:
220
+ progress("正在删除 …")
221
+ failed: List[str] = []
222
+ import sys
223
+
224
+ def _on_error(func, path, exc_info):
225
+ failed.append(path)
226
+
227
+ # Python 3.12 起推荐 onexc(onerror 仍存在但会发弃用警告)。
228
+ # **不能只靠 try/except TypeError**:3.12+ 里 onerror 依然存在,
229
+ # 传它不会报错,只会静默发警告 —— 所以按版本选参数。
230
+ if sys.version_info >= (3, 12):
231
+ shutil.rmtree(install_dir, onexc=_on_error)
232
+ else:
233
+ shutil.rmtree(install_dir, onerror=_on_error)
234
+ removed = not os.path.exists(install_dir)
235
+ return {"removed": removed, "failed": failed[:20],
236
+ "failed_count": len(failed), "path": install_dir}
237
+
238
+
239
+ def forget_state(install_dir: str = "") -> int:
240
+ """把"记住装在哪"的记录清掉(卸载后别再指向一个不存在的目录)。
241
+
242
+ 返回清掉了几处。
243
+ """
244
+ import json
245
+ count = 0
246
+ for path in paths._state_files(install_dir):
247
+ try:
248
+ if not os.path.exists(path):
249
+ continue
250
+ with open(path, "r", encoding="utf-8") as handle:
251
+ data = json.load(handle)
252
+ recorded = str((data or {}).get("install_dir") or "")
253
+ if install_dir and recorded and \
254
+ os.path.abspath(recorded) != os.path.abspath(install_dir):
255
+ continue # 这条记录指向别的安装,别动
256
+ os.remove(path)
257
+ count += 1
258
+ except Exception:
259
+ continue
260
+ return count
qqbot_cli/wizard.py ADDED
@@ -0,0 +1,192 @@
1
+ # -*- coding: utf-8 -*-
2
+ """初始向导:问几个必填项,生成 `config.json`。
3
+
4
+ **只问最少的几项**:主程序有 118 个配置项,全问不现实。这里只问
5
+ 「装了没它就干不了活」的那几个,其余走默认值,装完在网页设置页改。
6
+
7
+ 写出来的 `config.json` 只包含**用户填的**和必要的骨架;主程序启动时会
8
+ 按 `core/config_schema.py` 自动补全缺的项(缺失项自动补全相当于自带迁移)。
9
+ """
10
+
11
+ import json
12
+ import os
13
+ import secrets
14
+ from typing import Dict, List, Optional
15
+
16
+ from . import paths
17
+
18
+
19
+ # ---------------------------------------------------------------- 输入
20
+ def ask(prompt: str, default: str = "", allow_empty: bool = True) -> str:
21
+ """问一句;直接回车用默认值。"""
22
+ suffix = " [%s]" % default if default else ""
23
+ while True:
24
+ try:
25
+ answer = input("%s%s: " % (prompt, suffix)).strip()
26
+ except (EOFError, KeyboardInterrupt):
27
+ print()
28
+ raise
29
+ if answer:
30
+ return answer
31
+ if default or allow_empty:
32
+ return default
33
+ print(" 这一项不能留空,请再输一次。")
34
+
35
+
36
+ def ask_yes(prompt: str, default: bool = True) -> bool:
37
+ hint = "Y/n" if default else "y/N"
38
+ try:
39
+ answer = input("%s [%s]: " % (prompt, hint)).strip().lower()
40
+ except (EOFError, KeyboardInterrupt):
41
+ print()
42
+ raise
43
+ if not answer:
44
+ return default
45
+ return answer in ("y", "yes", "是", "1", "对")
46
+
47
+
48
+ def ask_port(prompt: str, default: int = 8666) -> int:
49
+ while True:
50
+ text = ask(prompt, str(default))
51
+ try:
52
+ port = int(text)
53
+ except ValueError:
54
+ print(" 端口要是数字,再试一次。")
55
+ continue
56
+ if 1 <= port <= 65535:
57
+ return port
58
+ print(" 端口范围是 1~65535,再试一次。")
59
+
60
+
61
+ # ---------------------------------------------------------------- 向导
62
+ def run_wizard(install_dir: str, tag: str = "",
63
+ existing: Optional[Dict] = None) -> Dict:
64
+ """跑一遍向导,返回写进 config.json 的那份数据。"""
65
+ existing = existing or {}
66
+ web = existing.get("web") or {}
67
+ bots: List[Dict] = list(existing.get("bots") or [])
68
+ first_bot = bots[0] if bots else {}
69
+
70
+ print()
71
+ print("=" * 60)
72
+ print(" 基本配置")
73
+ print(" (都可以留空,装好之后在网页「设置」里改)")
74
+ print("=" * 60)
75
+ print()
76
+
77
+ app_id = ask("AppID(QQ 开放平台的机器人 AppID)", first_bot.get("app_id") or "")
78
+ app_secret = ask("AppSecret", first_bot.get("app_secret") or "")
79
+ bot_name = ask("给这个机器人起个名字", first_bot.get("name") or "我的机器人")
80
+
81
+ print()
82
+ print("-- AI 回复(可选,留空就只用关键词和插件)--")
83
+ ai = existing.get("ai") or {}
84
+ api_key = ask("AI 的 API Key", ai.get("api_key") or "")
85
+ base_url = ask("AI 接口地址", ai.get("base_url") or "https://api.deepseek.com")
86
+ model = ask("AI 模型名", ai.get("model") or "deepseek-chat")
87
+
88
+ print()
89
+ print("-- 网页后台 --")
90
+ port = ask_port("网页端口", int(web.get("port") or 8666))
91
+
92
+ token = str(web.get("token") or "").strip()
93
+ if not token:
94
+ token = secrets.token_urlsafe(24)
95
+ print(" 已自动生成访问令牌(登录网页要用,稍后会一并打印)")
96
+
97
+ bot_entry = {
98
+ "id": first_bot.get("id") or "bot1",
99
+ "name": bot_name or "我的机器人",
100
+ "enabled": bool(app_id and app_secret),
101
+ "app_id": app_id,
102
+ "app_secret": app_secret,
103
+ }
104
+ if first_bot:
105
+ others = bots[1:]
106
+ else:
107
+ others = []
108
+
109
+ config = {
110
+ "web": {
111
+ "host": web.get("host") or "127.0.0.1",
112
+ "port": port,
113
+ "token": token,
114
+ },
115
+ "ai": {
116
+ "api_key": api_key,
117
+ "base_url": base_url or "https://api.deepseek.com",
118
+ "model": model or "deepseek-chat",
119
+ },
120
+ "bots": [bot_entry] + others,
121
+ "active_bot_id": bot_entry["id"],
122
+ }
123
+ if existing:
124
+ # 保留用户原文件里其它分组,只覆盖我们问过的这几项
125
+ merged = dict(existing)
126
+ merged["web"] = dict(web, **config["web"])
127
+ merged["ai"] = dict(ai, **config["ai"])
128
+ merged["bots"] = config["bots"]
129
+ merged["active_bot_id"] = config["active_bot_id"]
130
+ config = merged
131
+
132
+ if not app_id or not app_secret:
133
+ print()
134
+ print(" 注意:没填 AppID/AppSecret,机器人会处于「未启用」状态。")
135
+ print(" 装好之后在网页「设置 → 机器人账号」里补上即可启用。")
136
+ return config
137
+
138
+
139
+ def write_config(install_dir: str, config: Dict) -> str:
140
+ """写 config.json;已有的先备份一份。返回文件路径。"""
141
+ target = os.path.join(install_dir, "config.json")
142
+ if os.path.exists(target):
143
+ backup = target + ".bak"
144
+ try:
145
+ os.replace(target, backup)
146
+ print(" 原 config.json 已备份为 config.json.bak")
147
+ except OSError:
148
+ pass
149
+ with open(target, "w", encoding="utf-8") as handle:
150
+ json.dump(config, handle, ensure_ascii=False, indent=2)
151
+ return target
152
+
153
+
154
+ def show_summary(install_dir: str, config: Dict, python_versions: Dict[str, str]) -> None:
155
+ """装完把关键信息打印出来(令牌要能看到,否则用户进不去后台)。"""
156
+ web = config.get("web") or {}
157
+ host = web.get("host") or "127.0.0.1"
158
+ port = web.get("port") or 8666
159
+ token = web.get("token") or ""
160
+ shown_host = "127.0.0.1" if host in ("0.0.0.0", "") else host
161
+ url = "http://%s:%s/" % (shown_host, port)
162
+ if token:
163
+ url += "?token=%s" % token
164
+
165
+ print()
166
+ print("=" * 60)
167
+ print(" 安装完成")
168
+ print("=" * 60)
169
+ print(" 安装目录 : %s" % install_dir)
170
+ if python_versions:
171
+ print(" 依赖版本 : %s" % "、".join(
172
+ "%s %s" % (name, ver) for name, ver in python_versions.items()))
173
+ print()
174
+ print(" 后台地址 : %s" % url)
175
+ if token:
176
+ print(" 访问令牌 : %s" % token)
177
+ print(" (也写在 config.json 的 web.token 里)")
178
+ print()
179
+ print(" 启动命令 : qqbot")
180
+ print()
181
+ print(" 想看/改里面的文件,进这个目录即可:")
182
+ print(" %s" % paths.install_help_command(install_dir))
183
+ if paths.is_windows():
184
+ print(" (或在资源管理器地址栏粘贴上面的路径)")
185
+ else:
186
+ print(" (或用文件管理器打开上面的路径)")
187
+ print(" 配置 config.json · 数据 data/ · 插件 plugins/ · 日志 data/logs/")
188
+ print()
189
+ print(" 备份数据 : qqbot export")
190
+ print(" 卸载 : qqbot uninstall")
191
+ print(" 换目录装 : qqbot --dir <路径>")
192
+ print("=" * 60)