fastqq 0.1.2__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.
Potentially problematic release.
This version of fastqq might be problematic. Click here for more details.
- fastqq/__init__.py +3 -0
- fastqq/__main__.py +4 -0
- fastqq/bot.py +105 -0
- fastqq/cli.py +138 -0
- fastqq/config.py +280 -0
- fastqq/contacts.py +195 -0
- fastqq/engine.py +389 -0
- fastqq/errors.py +10 -0
- fastqq/gateway.py +298 -0
- fastqq/log.py +69 -0
- fastqq/onebot/__init__.py +1 -0
- fastqq/onebot/api.py +206 -0
- fastqq/onebot/events.py +83 -0
- fastqq/onebot/message.py +210 -0
- fastqq/py.typed +0 -0
- fastqq/tools/__init__.py +1 -0
- fastqq/tools/inspect_ntqq.py +296 -0
- fastqq/uia/__init__.py +1 -0
- fastqq/uia/client.py +970 -0
- fastqq/uia/clipboard.py +54 -0
- fastqq/uia/selectors.py +120 -0
- fastqq/uia/win32.py +106 -0
- fastqq-0.1.2.dist-info/METADATA +507 -0
- fastqq-0.1.2.dist-info/RECORD +27 -0
- fastqq-0.1.2.dist-info/WHEEL +5 -0
- fastqq-0.1.2.dist-info/entry_points.txt +2 -0
- fastqq-0.1.2.dist-info/top_level.txt +1 -0
fastqq/__init__.py
ADDED
fastqq/__main__.py
ADDED
fastqq/bot.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""应用编排层:配置 + 缓存 + 引擎 + WebSocket 网关。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .config import FastQQConfig
|
|
10
|
+
from .contacts import ContactsStore
|
|
11
|
+
from .engine import EngineState, OutgoingResult, UIAEngine
|
|
12
|
+
from .errors import SuspendedError
|
|
13
|
+
from .gateway import OneBotGateway
|
|
14
|
+
from .log import get_logger
|
|
15
|
+
from .onebot.message import Segment
|
|
16
|
+
|
|
17
|
+
LOG = get_logger("fastqq.bot")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FastQQBot:
|
|
21
|
+
def __init__(self, config: FastQQConfig, config_path: Path) -> None:
|
|
22
|
+
self.config = config
|
|
23
|
+
self.config_path = Path(config_path)
|
|
24
|
+
self.contacts = ContactsStore(
|
|
25
|
+
config.cache_path(self.config_path), config.session_map
|
|
26
|
+
)
|
|
27
|
+
self.nickname = config.nickname
|
|
28
|
+
self._gateway: OneBotGateway | None = None
|
|
29
|
+
self.engine = UIAEngine(
|
|
30
|
+
config,
|
|
31
|
+
self.contacts,
|
|
32
|
+
on_message=self._on_message,
|
|
33
|
+
on_state_change=self._on_state_change,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def gateway(self) -> OneBotGateway:
|
|
38
|
+
if self._gateway is None:
|
|
39
|
+
self._gateway = OneBotGateway(self.config, self, self.engine)
|
|
40
|
+
return self._gateway
|
|
41
|
+
|
|
42
|
+
# ------------------------------------------------------------- 回调
|
|
43
|
+
async def _on_message(self, payload: dict[str, Any]) -> None:
|
|
44
|
+
await self.gateway.broadcast(payload)
|
|
45
|
+
|
|
46
|
+
def _on_state_change(self, previous: EngineState, current: EngineState) -> None:
|
|
47
|
+
if self._gateway is not None:
|
|
48
|
+
self._gateway.on_state_change(previous, current)
|
|
49
|
+
|
|
50
|
+
# ---------------------------------------------------------------- 状态
|
|
51
|
+
def status_payload(self) -> dict[str, bool]:
|
|
52
|
+
# 默认静默模式下,假死引擎仍刻意报告 online/good,让下游框架保持连接。
|
|
53
|
+
if self.engine.suspended and self.config.offline.notify_downstream:
|
|
54
|
+
return {"online": False, "good": False}
|
|
55
|
+
return {"online": True, "good": True}
|
|
56
|
+
|
|
57
|
+
# --------------------------------------------------------------- 生命周期
|
|
58
|
+
async def start(self) -> None:
|
|
59
|
+
await self.engine.start()
|
|
60
|
+
await self.gateway.start()
|
|
61
|
+
if not self.nickname:
|
|
62
|
+
try:
|
|
63
|
+
self.nickname = await self.engine._call(self.engine.client.nickname)
|
|
64
|
+
except Exception:
|
|
65
|
+
self.nickname = "FastQQ"
|
|
66
|
+
LOG.info("FastQQ started for QQ %s", self.config.bot_uin)
|
|
67
|
+
|
|
68
|
+
async def stop(self) -> None:
|
|
69
|
+
await self.gateway.stop()
|
|
70
|
+
await self.engine.stop()
|
|
71
|
+
self.contacts.save()
|
|
72
|
+
|
|
73
|
+
async def run_forever(self) -> None:
|
|
74
|
+
await self.start()
|
|
75
|
+
stop_event = asyncio.Event()
|
|
76
|
+
loop = asyncio.get_running_loop()
|
|
77
|
+
for sig_name in ("SIGINT", "SIGTERM"):
|
|
78
|
+
sig = getattr(__import__("signal"), sig_name, None)
|
|
79
|
+
if sig is None:
|
|
80
|
+
continue
|
|
81
|
+
try:
|
|
82
|
+
loop.add_signal_handler(sig, stop_event.set)
|
|
83
|
+
except (NotImplementedError, RuntimeError, AttributeError):
|
|
84
|
+
pass
|
|
85
|
+
try:
|
|
86
|
+
await stop_event.wait()
|
|
87
|
+
finally:
|
|
88
|
+
await self.stop()
|
|
89
|
+
|
|
90
|
+
# ------------------------------------------------------------------- 发送
|
|
91
|
+
async def send(
|
|
92
|
+
self,
|
|
93
|
+
*,
|
|
94
|
+
kind: str,
|
|
95
|
+
target_id: int,
|
|
96
|
+
segments: list[Segment],
|
|
97
|
+
) -> OutgoingResult:
|
|
98
|
+
if self.engine.suspended:
|
|
99
|
+
raise SuspendedError("QQNT is temporarily offline (suspended)")
|
|
100
|
+
result = await self.engine.send(kind=kind, target_id=target_id, segments=segments)
|
|
101
|
+
if kind == "group":
|
|
102
|
+
self.contacts.learn_group(result.target_id, result.title)
|
|
103
|
+
else:
|
|
104
|
+
self.contacts.learn_friend(result.target_id, result.title)
|
|
105
|
+
return result
|
fastqq/cli.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""`fastqq` 命令行入口。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .config import (
|
|
12
|
+
ConfigError,
|
|
13
|
+
generate_ws_token,
|
|
14
|
+
load_config,
|
|
15
|
+
write_default_config,
|
|
16
|
+
)
|
|
17
|
+
from .log import get_logger, setup_logging
|
|
18
|
+
|
|
19
|
+
LOG = get_logger("fastqq.cli")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _print_token(token: str) -> None:
|
|
23
|
+
line = "=" * 64
|
|
24
|
+
print()
|
|
25
|
+
print(line)
|
|
26
|
+
print(" FastQQ configuration created")
|
|
27
|
+
print(f" ws_token : {token}")
|
|
28
|
+
print(" Keep this token secret. It is required by ncatbot / OneBot clients.")
|
|
29
|
+
print(line)
|
|
30
|
+
print()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def cmd_init(args: argparse.Namespace) -> int:
|
|
34
|
+
cwd = Path.cwd()
|
|
35
|
+
config_path = cwd / "config.yaml"
|
|
36
|
+
cache_path = cwd / "contacts_cache.json"
|
|
37
|
+
if config_path.exists() and not args.force:
|
|
38
|
+
print(
|
|
39
|
+
f"config.yaml already exists at {config_path}\n"
|
|
40
|
+
"Use `fastqq init --force` only if you intend to replace it.",
|
|
41
|
+
file=sys.stderr,
|
|
42
|
+
)
|
|
43
|
+
return 2
|
|
44
|
+
token = generate_ws_token()
|
|
45
|
+
write_default_config(config_path, token, cache_path)
|
|
46
|
+
_print_token(token)
|
|
47
|
+
print(f"Config : {config_path}")
|
|
48
|
+
print(f"Cache : {cache_path}")
|
|
49
|
+
print("Next : edit config.yaml, set bot_uin, then run `fastqq run`.")
|
|
50
|
+
return 0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def cmd_run(args: argparse.Namespace) -> int:
|
|
54
|
+
path = Path(args.config).expanduser()
|
|
55
|
+
if not path.is_absolute():
|
|
56
|
+
path = Path.cwd() / path
|
|
57
|
+
try:
|
|
58
|
+
config = load_config(path)
|
|
59
|
+
except ConfigError as exc:
|
|
60
|
+
print(str(exc), file=sys.stderr)
|
|
61
|
+
return 2
|
|
62
|
+
problems = config.run_problems()
|
|
63
|
+
if problems:
|
|
64
|
+
print("FastQQ cannot start:", file=sys.stderr)
|
|
65
|
+
for problem in problems:
|
|
66
|
+
print(f" - {problem}", file=sys.stderr)
|
|
67
|
+
return 2
|
|
68
|
+
|
|
69
|
+
setup_logging(args.log_level or "INFO")
|
|
70
|
+
# 延迟导入,让 `fastqq --help` 保持快速,且不依赖 UIA 也能显示帮助。
|
|
71
|
+
from .bot import FastQQBot
|
|
72
|
+
|
|
73
|
+
bot = FastQQBot(config, path)
|
|
74
|
+
try:
|
|
75
|
+
asyncio.run(bot.run_forever())
|
|
76
|
+
except KeyboardInterrupt:
|
|
77
|
+
LOG.info("stopped by user")
|
|
78
|
+
except Exception:
|
|
79
|
+
LOG.exception("FastQQ terminated unexpectedly")
|
|
80
|
+
return 1
|
|
81
|
+
return 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def cmd_inspect(args: argparse.Namespace) -> int:
|
|
85
|
+
from .tools.inspect_ntqq import dump_qq_tree
|
|
86
|
+
|
|
87
|
+
return dump_qq_tree(Path(args.output), args.max_depth, args.max_nodes)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
91
|
+
parser = argparse.ArgumentParser(
|
|
92
|
+
prog="fastqq",
|
|
93
|
+
description="QQNT UIA -> OneBot v11 WebSocket gateway (zero injection).",
|
|
94
|
+
)
|
|
95
|
+
parser.add_argument("--version", action="version", version=f"fastqq {__version__}")
|
|
96
|
+
sub = parser.add_subparsers(dest="command")
|
|
97
|
+
|
|
98
|
+
init_parser = sub.add_parser(
|
|
99
|
+
"init", help="create config.yaml and contacts_cache.json in the current directory"
|
|
100
|
+
)
|
|
101
|
+
init_parser.add_argument(
|
|
102
|
+
"--force", action="store_true", help="replace an existing config.yaml"
|
|
103
|
+
)
|
|
104
|
+
init_parser.set_defaults(func=cmd_init)
|
|
105
|
+
|
|
106
|
+
run_parser = sub.add_parser("run", help="start FastQQ from config.yaml")
|
|
107
|
+
run_parser.add_argument(
|
|
108
|
+
"--config", default="config.yaml", help="path to config.yaml (default: ./config.yaml)"
|
|
109
|
+
)
|
|
110
|
+
run_parser.add_argument(
|
|
111
|
+
"--log-level",
|
|
112
|
+
default="INFO",
|
|
113
|
+
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
|
|
114
|
+
help="console log level",
|
|
115
|
+
)
|
|
116
|
+
run_parser.set_defaults(func=cmd_run)
|
|
117
|
+
|
|
118
|
+
inspect_parser = sub.add_parser(
|
|
119
|
+
"inspect", help="dump the live QQNT UIA tree to uia_dump.txt"
|
|
120
|
+
)
|
|
121
|
+
inspect_parser.add_argument("--output", "-o", default="uia_dump.txt")
|
|
122
|
+
inspect_parser.add_argument("--max-depth", type=int, default=40)
|
|
123
|
+
inspect_parser.add_argument("--max-nodes", type=int, default=20000)
|
|
124
|
+
inspect_parser.set_defaults(func=cmd_inspect)
|
|
125
|
+
return parser
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def main(argv: list[str] | None = None) -> int:
|
|
129
|
+
parser = build_parser()
|
|
130
|
+
args = parser.parse_args(argv)
|
|
131
|
+
if not getattr(args, "command", None):
|
|
132
|
+
parser.print_help()
|
|
133
|
+
return 0
|
|
134
|
+
return int(args.func(args))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
if __name__ == "__main__": # pragma: no cover
|
|
138
|
+
raise SystemExit(main())
|
fastqq/config.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""配置模型与 `fastqq init` 模板。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import secrets
|
|
7
|
+
import string
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
from urllib.parse import urlparse
|
|
11
|
+
|
|
12
|
+
import yaml
|
|
13
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
14
|
+
|
|
15
|
+
# Token 符号刻意限制在 URL 查询参数、YAML 双引号标量、Shell 参数和
|
|
16
|
+
# HTTP Bearer Token 中都安全的字符集合内。
|
|
17
|
+
TOKEN_SYMBOLS = "!@$^*_-~."
|
|
18
|
+
TOKEN_LENGTH = 16
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ConfigError(ValueError):
|
|
22
|
+
"""配置文件不可用时抛出。"""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def generate_ws_token(length: int = TOKEN_LENGTH) -> str:
|
|
26
|
+
"""生成同时包含大写字母、小写字母、数字和符号的高熵 Token。
|
|
27
|
+
|
|
28
|
+
字符表避开 ``& = ? # % /``,确保 Token 经过 URL 查询参数、YAML 解析和
|
|
29
|
+
普通 Shell 引号处理后仍保持不变。
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
if length < 8:
|
|
33
|
+
raise ValueError("token length must be at least 8")
|
|
34
|
+
alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits + TOKEN_SYMBOLS
|
|
35
|
+
checks = (
|
|
36
|
+
string.ascii_uppercase,
|
|
37
|
+
string.ascii_lowercase,
|
|
38
|
+
string.digits,
|
|
39
|
+
TOKEN_SYMBOLS,
|
|
40
|
+
)
|
|
41
|
+
while True:
|
|
42
|
+
token = "".join(secrets.choice(alphabet) for _ in range(length))
|
|
43
|
+
if all(any(ch in group for ch in token) for group in checks):
|
|
44
|
+
return token
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ForwardWSConfig(BaseModel):
|
|
48
|
+
model_config = ConfigDict(extra="ignore")
|
|
49
|
+
|
|
50
|
+
enabled: bool = True
|
|
51
|
+
host: str = "0.0.0.0"
|
|
52
|
+
port: int = Field(default=3001, ge=1, le=65535)
|
|
53
|
+
path: str = "/onebot/v11/ws"
|
|
54
|
+
|
|
55
|
+
@field_validator("host")
|
|
56
|
+
@classmethod
|
|
57
|
+
def _host_not_empty(cls, value: str) -> str:
|
|
58
|
+
value = value.strip()
|
|
59
|
+
if not value:
|
|
60
|
+
raise ValueError("forward_ws.host must not be empty")
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
@field_validator("path")
|
|
64
|
+
@classmethod
|
|
65
|
+
def _path_starts_with_slash(cls, value: str) -> str:
|
|
66
|
+
value = value.strip() or "/onebot/v11/ws"
|
|
67
|
+
if not value.startswith("/"):
|
|
68
|
+
value = "/" + value
|
|
69
|
+
return value
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class ReverseWSConfig(BaseModel):
|
|
73
|
+
model_config = ConfigDict(extra="ignore")
|
|
74
|
+
|
|
75
|
+
enabled: bool = False
|
|
76
|
+
url: str = ""
|
|
77
|
+
reconnect_interval: float = Field(default=5.0, ge=0.5, le=600.0)
|
|
78
|
+
|
|
79
|
+
@field_validator("url")
|
|
80
|
+
@classmethod
|
|
81
|
+
def _url_valid(cls, value: str) -> str:
|
|
82
|
+
value = value.strip()
|
|
83
|
+
if not value:
|
|
84
|
+
return value
|
|
85
|
+
parsed = urlparse(value)
|
|
86
|
+
if parsed.scheme not in {"ws", "wss"} or not parsed.netloc:
|
|
87
|
+
raise ValueError("reverse_ws.url must be a ws:// or wss:// URL")
|
|
88
|
+
return value
|
|
89
|
+
|
|
90
|
+
@model_validator(mode="after")
|
|
91
|
+
def _url_required_when_enabled(self) -> ReverseWSConfig:
|
|
92
|
+
if self.enabled and not self.url:
|
|
93
|
+
raise ValueError("reverse_ws.url is required when reverse_ws.enabled is true")
|
|
94
|
+
return self
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class OfflineConfig(BaseModel):
|
|
98
|
+
model_config = ConfigDict(extra="ignore")
|
|
99
|
+
|
|
100
|
+
# 这些默认值是刻意设置的:不能因为 QQNT 正在重连,就让 ncatbot 等下游
|
|
101
|
+
# 框架收到 lifecycle:disable 并自行退出。
|
|
102
|
+
notify_downstream: bool = False
|
|
103
|
+
keep_ws_alive: bool = True
|
|
104
|
+
poll_interval: float = Field(default=2.0, ge=0.2, le=60.0)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class EngineConfig(BaseModel):
|
|
108
|
+
model_config = ConfigDict(extra="ignore")
|
|
109
|
+
|
|
110
|
+
tick_interval: float = Field(default=0.12, ge=0.08, le=1.0)
|
|
111
|
+
send_timeout: float = Field(default=10.0, ge=2.0, le=120.0)
|
|
112
|
+
switch_timeout: float = Field(default=3.0, ge=1.0, le=30.0)
|
|
113
|
+
max_messages_per_scan: int = Field(default=50, ge=1, le=500)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class SessionMapConfig(BaseModel):
|
|
117
|
+
"""为只暴露显示名称的 UIA 界面提供手工“名称 ↔ 数字 ID”绑定。
|
|
118
|
+
|
|
119
|
+
YAML 写法::
|
|
120
|
+
|
|
121
|
+
session_map:
|
|
122
|
+
groups:
|
|
123
|
+
"200000001": "我的测试群"
|
|
124
|
+
users:
|
|
125
|
+
"123456789": "示例用户"
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
model_config = ConfigDict(extra="ignore")
|
|
129
|
+
|
|
130
|
+
groups: dict[int, str] = Field(default_factory=dict)
|
|
131
|
+
users: dict[int, str] = Field(default_factory=dict)
|
|
132
|
+
|
|
133
|
+
@field_validator("groups", "users", mode="before")
|
|
134
|
+
@classmethod
|
|
135
|
+
def _coerce_mapping(cls, value: Any) -> dict[int, str]:
|
|
136
|
+
if value is None:
|
|
137
|
+
return {}
|
|
138
|
+
if not isinstance(value, dict):
|
|
139
|
+
raise ValueError("session_map groups/users must be a mapping of id -> display name")
|
|
140
|
+
result: dict[int, str] = {}
|
|
141
|
+
for key, name in value.items():
|
|
142
|
+
try:
|
|
143
|
+
qid = int(key)
|
|
144
|
+
except (TypeError, ValueError) as exc:
|
|
145
|
+
raise ValueError(f"invalid QQ id in session_map: {key!r}") from exc
|
|
146
|
+
if qid <= 0:
|
|
147
|
+
raise ValueError(f"QQ id must be positive: {qid}")
|
|
148
|
+
result[qid] = str(name)
|
|
149
|
+
return result
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class FastQQConfig(BaseModel):
|
|
153
|
+
model_config = ConfigDict(extra="ignore")
|
|
154
|
+
|
|
155
|
+
bot_uin: int = Field(default=0, ge=0)
|
|
156
|
+
nickname: str = ""
|
|
157
|
+
ws_token: str = ""
|
|
158
|
+
heartbeat_interval: float = Field(default=5.0, ge=1.0, le=300.0)
|
|
159
|
+
contacts_cache: str = "contacts_cache.json"
|
|
160
|
+
forward_ws: ForwardWSConfig = Field(default_factory=ForwardWSConfig)
|
|
161
|
+
reverse_ws: ReverseWSConfig = Field(default_factory=ReverseWSConfig)
|
|
162
|
+
offline: OfflineConfig = Field(default_factory=OfflineConfig)
|
|
163
|
+
engine: EngineConfig = Field(default_factory=EngineConfig)
|
|
164
|
+
session_map: SessionMapConfig = Field(default_factory=SessionMapConfig)
|
|
165
|
+
|
|
166
|
+
@field_validator("nickname")
|
|
167
|
+
@classmethod
|
|
168
|
+
def _strip_nickname(cls, value: str) -> str:
|
|
169
|
+
return value.strip()
|
|
170
|
+
|
|
171
|
+
@model_validator(mode="after")
|
|
172
|
+
def _at_least_one_transport(self) -> FastQQConfig:
|
|
173
|
+
if not self.forward_ws.enabled and not self.reverse_ws.enabled:
|
|
174
|
+
raise ValueError("at least one of forward_ws.enabled or reverse_ws.enabled must be true")
|
|
175
|
+
return self
|
|
176
|
+
|
|
177
|
+
def run_problems(self) -> list[str]:
|
|
178
|
+
"""返回阻止 `fastqq run` 启动的可读原因。"""
|
|
179
|
+
|
|
180
|
+
problems: list[str] = []
|
|
181
|
+
if self.bot_uin <= 0:
|
|
182
|
+
problems.append(
|
|
183
|
+
"`bot_uin` is not configured. Open config.yaml and set your numeric QQ number "
|
|
184
|
+
"(for example `bot_uin: 123456789`)."
|
|
185
|
+
)
|
|
186
|
+
if self.reverse_ws.enabled and not self.reverse_ws.url:
|
|
187
|
+
problems.append("`reverse_ws.url` must be set when reverse WebSocket is enabled.")
|
|
188
|
+
if not self.ws_token:
|
|
189
|
+
problems.append(
|
|
190
|
+
"`ws_token` is empty. Run `fastqq init` again or generate a 16-character token."
|
|
191
|
+
)
|
|
192
|
+
return problems
|
|
193
|
+
|
|
194
|
+
def cache_path(self, config_path: Path) -> Path:
|
|
195
|
+
path = Path(self.contacts_cache)
|
|
196
|
+
if not path.is_absolute():
|
|
197
|
+
path = config_path.resolve().parent / path
|
|
198
|
+
return path
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
DEFAULT_CONFIG_TEMPLATE = """\
|
|
202
|
+
# FastQQ 配置文件
|
|
203
|
+
# 仓库地址:https://gitlab.com/zetsr/fastqq
|
|
204
|
+
# 将端口暴露到公网前,请先阅读 README 和免责声明。
|
|
205
|
+
|
|
206
|
+
bot_uin: 0 # 必填:机器人 QQ 号,例如 123456789
|
|
207
|
+
nickname: "" # 可选;FastQQ 可以从 QQNT 自动读取当前昵称
|
|
208
|
+
ws_token: "__WS_TOKEN__" # 由 `fastqq init` 生成
|
|
209
|
+
|
|
210
|
+
heartbeat_interval: 5.0 # 心跳间隔,单位:秒
|
|
211
|
+
|
|
212
|
+
forward_ws: # FastQQ 作为 WebSocket 服务端
|
|
213
|
+
enabled: true
|
|
214
|
+
host: 0.0.0.0
|
|
215
|
+
port: 3001
|
|
216
|
+
path: /onebot/v11/ws
|
|
217
|
+
|
|
218
|
+
reverse_ws: # FastQQ 作为 WebSocket 客户端
|
|
219
|
+
enabled: false
|
|
220
|
+
url: "" # 例如 ws://1.2.3.4:3001/onebot/v11/ws
|
|
221
|
+
reconnect_interval: 5.0
|
|
222
|
+
|
|
223
|
+
offline:
|
|
224
|
+
# 当 QQNT 暂时离线时,让 ncatbot 等下游框架继续存活。
|
|
225
|
+
# notify_downstream=false 时不会发送 lifecycle:disable,WebSocket 和
|
|
226
|
+
# 心跳都会继续保持。
|
|
227
|
+
notify_downstream: false
|
|
228
|
+
keep_ws_alive: true
|
|
229
|
+
poll_interval: 2.0
|
|
230
|
+
|
|
231
|
+
engine:
|
|
232
|
+
tick_interval: 0.12 # 支持的 UIA 轮询区间为 80-150 毫秒
|
|
233
|
+
send_timeout: 10.0
|
|
234
|
+
switch_timeout: 3.0
|
|
235
|
+
max_messages_per_scan: 50
|
|
236
|
+
|
|
237
|
+
contacts_cache: contacts_cache.json
|
|
238
|
+
|
|
239
|
+
# UIA 对大多数会话只暴露显示名称。如果需要在首次发送前接收某个会话的事件,
|
|
240
|
+
# 请在这里绑定显示名称与数字 ID。
|
|
241
|
+
session_map:
|
|
242
|
+
groups: {}
|
|
243
|
+
users: {}
|
|
244
|
+
"""
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def write_default_config(config_path: Path, token: str, cache_path: Path) -> None:
|
|
248
|
+
config_path.write_text(
|
|
249
|
+
DEFAULT_CONFIG_TEMPLATE.replace("__WS_TOKEN__", token),
|
|
250
|
+
encoding="utf-8",
|
|
251
|
+
newline="\n",
|
|
252
|
+
)
|
|
253
|
+
if not cache_path.exists():
|
|
254
|
+
cache_path.write_text(
|
|
255
|
+
json.dumps({"version": 1, "groups": {}, "friends": {}}, indent=2) + "\n",
|
|
256
|
+
encoding="utf-8",
|
|
257
|
+
newline="\n",
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def load_config(path: Path) -> FastQQConfig:
|
|
262
|
+
path = Path(path)
|
|
263
|
+
if not path.is_file():
|
|
264
|
+
raise ConfigError(
|
|
265
|
+
f"configuration file not found: {path}\nRun `fastqq init` in this directory first."
|
|
266
|
+
)
|
|
267
|
+
try:
|
|
268
|
+
raw = yaml.safe_load(path.read_text(encoding="utf-8"))
|
|
269
|
+
except OSError as exc:
|
|
270
|
+
raise ConfigError(f"cannot read {path}: {exc}") from exc
|
|
271
|
+
except yaml.YAMLError as exc:
|
|
272
|
+
raise ConfigError(f"invalid YAML in {path}: {exc}") from exc
|
|
273
|
+
if raw is None:
|
|
274
|
+
raise ConfigError(f"{path} is empty; run `fastqq init` to create a template")
|
|
275
|
+
if not isinstance(raw, dict):
|
|
276
|
+
raise ConfigError(f"{path} must contain a YAML mapping at the top level")
|
|
277
|
+
try:
|
|
278
|
+
return FastQQConfig.model_validate(raw)
|
|
279
|
+
except Exception as exc:
|
|
280
|
+
raise ConfigError(f"invalid configuration in {path}:\n{exc}") from exc
|