fastqq 0.1.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.
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 +106 -0
- fastqq/cli.py +138 -0
- fastqq/config.py +280 -0
- fastqq/contacts.py +198 -0
- fastqq/engine.py +394 -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 +211 -0
- fastqq/py.typed +0 -0
- fastqq/tools/__init__.py +1 -0
- fastqq/tools/inspect_ntqq.py +297 -0
- fastqq/uia/__init__.py +1 -0
- fastqq/uia/client.py +973 -0
- fastqq/uia/clipboard.py +55 -0
- fastqq/uia/selectors.py +120 -0
- fastqq/uia/win32.py +106 -0
- fastqq-0.1.0.dist-info/METADATA +515 -0
- fastqq-0.1.0.dist-info/RECORD +28 -0
- fastqq-0.1.0.dist-info/WHEEL +5 -0
- fastqq-0.1.0.dist-info/entry_points.txt +2 -0
- fastqq-0.1.0.dist-info/licenses/LICENSE +21 -0
- fastqq-0.1.0.dist-info/top_level.txt +1 -0
fastqq/__init__.py
ADDED
fastqq/__main__.py
ADDED
fastqq/bot.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Application orchestration: config + cache + engine + WebSocket gateway."""
|
|
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
|
+
# ------------------------------------------------------------- callbacks
|
|
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
|
+
# ---------------------------------------------------------------- status
|
|
51
|
+
def status_payload(self) -> dict[str, bool]:
|
|
52
|
+
# In the default silent mode a suspended engine deliberately reports
|
|
53
|
+
# online/good so downstream frameworks keep their connection alive.
|
|
54
|
+
if self.engine.suspended and self.config.offline.notify_downstream:
|
|
55
|
+
return {"online": False, "good": False}
|
|
56
|
+
return {"online": True, "good": True}
|
|
57
|
+
|
|
58
|
+
# --------------------------------------------------------------- lifecycle
|
|
59
|
+
async def start(self) -> None:
|
|
60
|
+
await self.engine.start()
|
|
61
|
+
await self.gateway.start()
|
|
62
|
+
if not self.nickname:
|
|
63
|
+
try:
|
|
64
|
+
self.nickname = await self.engine._call(self.engine.client.nickname)
|
|
65
|
+
except Exception:
|
|
66
|
+
self.nickname = "FastQQ"
|
|
67
|
+
LOG.info("FastQQ started for QQ %s", self.config.bot_uin)
|
|
68
|
+
|
|
69
|
+
async def stop(self) -> None:
|
|
70
|
+
await self.gateway.stop()
|
|
71
|
+
await self.engine.stop()
|
|
72
|
+
self.contacts.save()
|
|
73
|
+
|
|
74
|
+
async def run_forever(self) -> None:
|
|
75
|
+
await self.start()
|
|
76
|
+
stop_event = asyncio.Event()
|
|
77
|
+
loop = asyncio.get_running_loop()
|
|
78
|
+
for sig_name in ("SIGINT", "SIGTERM"):
|
|
79
|
+
sig = getattr(__import__("signal"), sig_name, None)
|
|
80
|
+
if sig is None:
|
|
81
|
+
continue
|
|
82
|
+
try:
|
|
83
|
+
loop.add_signal_handler(sig, stop_event.set)
|
|
84
|
+
except (NotImplementedError, RuntimeError, AttributeError):
|
|
85
|
+
pass
|
|
86
|
+
try:
|
|
87
|
+
await stop_event.wait()
|
|
88
|
+
finally:
|
|
89
|
+
await self.stop()
|
|
90
|
+
|
|
91
|
+
# ------------------------------------------------------------------- send
|
|
92
|
+
async def send(
|
|
93
|
+
self,
|
|
94
|
+
*,
|
|
95
|
+
kind: str,
|
|
96
|
+
target_id: int,
|
|
97
|
+
segments: list[Segment],
|
|
98
|
+
) -> OutgoingResult:
|
|
99
|
+
if self.engine.suspended:
|
|
100
|
+
raise SuspendedError("QQNT is temporarily offline (suspended)")
|
|
101
|
+
result = await self.engine.send(kind=kind, target_id=target_id, segments=segments)
|
|
102
|
+
if kind == "group":
|
|
103
|
+
self.contacts.learn_group(result.target_id, result.title)
|
|
104
|
+
else:
|
|
105
|
+
self.contacts.learn_friend(result.target_id, result.title)
|
|
106
|
+
return result
|
fastqq/cli.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""`fastqq` command line interface."""
|
|
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
|
+
# Imported late so `fastqq --help` stays fast and works without 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
|
+
"""Configuration models and the `fastqq init` template."""
|
|
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
|
+
# Symbols deliberately restricted to characters that are safe in a URL query,
|
|
16
|
+
# a YAML double-quoted scalar, a shell argument and an HTTP Bearer token.
|
|
17
|
+
TOKEN_SYMBOLS = "!@$^*_-~."
|
|
18
|
+
TOKEN_LENGTH = 16
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ConfigError(ValueError):
|
|
22
|
+
"""Raised when a configuration file cannot be used."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def generate_ws_token(length: int = TOKEN_LENGTH) -> str:
|
|
26
|
+
"""Generate a high-entropy token containing upper, lower, digit and symbol.
|
|
27
|
+
|
|
28
|
+
The alphabet avoids ``& = ? # % /`` so the token survives URL query
|
|
29
|
+
encoding, YAML parsing and ordinary shell quoting unchanged.
|
|
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
|
+
# These defaults are deliberate: ncatbot and similar downstream frameworks
|
|
101
|
+
# must not receive lifecycle:disable merely because QQNT is reconnecting.
|
|
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
|
+
"""Manual name/id bindings for UIA surfaces that only expose display names.
|
|
118
|
+
|
|
119
|
+
YAML form::
|
|
120
|
+
|
|
121
|
+
session_map:
|
|
122
|
+
groups:
|
|
123
|
+
"123456789": "My test group"
|
|
124
|
+
users:
|
|
125
|
+
"1573213": "Kiana"
|
|
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
|
+
"""Return human-readable blockers for `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: 1573213`)."
|
|
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 configuration
|
|
203
|
+
# Repository: https://gitlab.com/zetsr/fastqq
|
|
204
|
+
# Read the README before exposing this port to the public Internet.
|
|
205
|
+
|
|
206
|
+
bot_uin: 0 # REQUIRED: your numeric QQ account, e.g. 1573213
|
|
207
|
+
nickname: "" # optional; FastQQ can learn the current nickname from QQNT
|
|
208
|
+
ws_token: "__WS_TOKEN__" # generated by `fastqq init`
|
|
209
|
+
|
|
210
|
+
heartbeat_interval: 5.0 # seconds
|
|
211
|
+
|
|
212
|
+
forward_ws: # FastQQ acts as a WebSocket server
|
|
213
|
+
enabled: true
|
|
214
|
+
host: 0.0.0.0
|
|
215
|
+
port: 3001
|
|
216
|
+
path: /onebot/v11/ws
|
|
217
|
+
|
|
218
|
+
reverse_ws: # FastQQ acts as a WebSocket client
|
|
219
|
+
enabled: false
|
|
220
|
+
url: "" # e.g. ws://1.2.3.4:3001/onebot/v11/ws
|
|
221
|
+
reconnect_interval: 5.0
|
|
222
|
+
|
|
223
|
+
offline:
|
|
224
|
+
# Keep downstream frameworks such as ncatbot alive when QQNT is temporarily
|
|
225
|
+
# offline. With notify_downstream=false, NO lifecycle:disable event is sent
|
|
226
|
+
# and the WebSocket plus heartbeat remain alive.
|
|
227
|
+
notify_downstream: false
|
|
228
|
+
keep_ws_alive: true
|
|
229
|
+
poll_interval: 2.0
|
|
230
|
+
|
|
231
|
+
engine:
|
|
232
|
+
tick_interval: 0.12 # 80-150 ms is the supported UIA polling range
|
|
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 only exposes display names for most sessions. Bind names to numeric ids
|
|
240
|
+
# here if you need receive-side events for a session you have not sent to yet.
|
|
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
|