@mcviseron/dsh-qq-bridge 0.2.0 → 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.
@@ -0,0 +1,185 @@
1
+ """Runtime settings shared by the supervisor, the bot and the settings page.
2
+
3
+ Stored as bot/config.json and re-read when its mtime changes, so the panel can
4
+ flip switches without restarting anything. Keys here are behaviour-level: secrets
5
+ may be overridden too, but those only take effect when the bot process restarts.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Any, Dict, Optional, Tuple
14
+
15
+ CONFIG_PATH = Path(__file__).resolve().parent / "config.json"
16
+
17
+ DEFAULTS: Dict[str, Any] = {
18
+ # 总开关与分渠道开关
19
+ "enabled": True,
20
+ "c2c_enabled": True,
21
+ "group_enabled": True,
22
+ # 群聊行为
23
+ "group_full_mode": True,
24
+ "chatter_batch": 8,
25
+ "chatter_max_s": 120,
26
+ "chatter_cooldown_s": 45,
27
+ "interject_hook_only": True,
28
+ "interject_cold_s": 1200,
29
+ "judge_join_threshold": 2,
30
+ "judge_score_output": True,
31
+ "judge_target_ratio": 0.3,
32
+ "judge_silent_streak": 3,
33
+ "judge_force_per_hour": 1,
34
+ "send_file_timeout_s": 60,
35
+ "metrics_keep_days": 30,
36
+ "admin_owner_window_s": 300,
37
+ "bot_say_memory_s": 300,
38
+ "stuck_turn_s": 180,
39
+ # 人设:只在新会话的第一条消息里发一次(关掉则跟以前一样)
40
+ "persona_enabled": False,
41
+ "persona_group": "",
42
+ "persona_c2c": "",
43
+ # 发送行为
44
+ "md_auto": True,
45
+ "ack_delay_s": 5,
46
+ "debounce_ms": 700,
47
+ "debounce_max_ms": 3000,
48
+ "max_chars": 1600,
49
+ # 群聊过滤与插话边界
50
+ "group_allowlist": "",
51
+ "c2c_allowlist": "",
52
+ "bot_aliases": "蓝色大肥鱼,大肥鱼,机器人,DSH,dsh",
53
+ "quiet_hours": "",
54
+ # 「还在处理,请稍等…」这种占位提示:默认关闭(会打断流式、影响观感)
55
+ "ack_enabled": False,
56
+ # 群聊主动消息策略:A=主会话内判断(现状),B=独立判断 AI 先筛(测试)
57
+ "group_mode": "A",
58
+ # 群聊获取范围:true = 本端只处理 @/点名/命令,其余群消息丢弃
59
+ "group_at_only": False,
60
+ # 静默时段(晚间闲聊不回):开关 + 时间段
61
+ "quiet_enabled": True,
62
+ # 审批决定后重发“已处理”卡片(关掉则只发一行文字确认)
63
+ "approval_inline_redraw": True,
64
+ "kick_confirm": True,
65
+ "stream_retry_s": 120,
66
+ # 自动分组:每个 QQ 会话一个独立工作区
67
+ "auto_group": True,
68
+ "auto_group_root": "D:\\dsh-qqbot-temp",
69
+ # 消息池(引用解析 + /撤回 + 插话判断的上下文窗口)
70
+ "pool_ttl_s": 1800,
71
+ "pool_max": 100,
72
+ # 引用消息:识别开关、随提示词带给模型的原文上限、排查日志
73
+ "quote_enabled": True,
74
+ "quote_context_chars": 300,
75
+ "quote_probe": False,
76
+ # 流式(平台只支持单聊)
77
+ "stream_enabled": False,
78
+ "stream_mode": "api",
79
+ "stream_interval_ms": 500,
80
+ "stream_min_chars": 14,
81
+ "stream_max_chunks": 6,
82
+ # 图片与文件
83
+ "image_max_mb": 8,
84
+ "image_cache_s": 120,
85
+ "capture_enabled": True,
86
+ # 频率限制:每个会话每小时最多回多少条,0=不限
87
+ "rate_limit_per_hour": 0,
88
+ # 桥接(改完需重启机器人)
89
+ "bridge_url": "http://127.0.0.1:39061",
90
+ "bridge_token": "",
91
+ # 设置页
92
+ "panel_host": "127.0.0.1",
93
+ "panel_port": 39062,
94
+ # 进程守护
95
+ "desired_running": True,
96
+ # 凭据覆盖(留空则用 .env)
97
+ "appid": "",
98
+ "appsecret": "",
99
+ }
100
+
101
+ SECRET_KEYS = {"appsecret"}
102
+
103
+
104
+ class RuntimeConfig:
105
+ """Small mtime-watched JSON config with defaults."""
106
+
107
+ def __init__(self, path: Path = CONFIG_PATH) -> None:
108
+ self.path = path
109
+ self._data: Dict[str, Any] = dict(DEFAULTS)
110
+ self._mtime = 0.0
111
+ self.reload(force=True)
112
+
113
+ def reload(self, *, force: bool = False) -> bool:
114
+ """Reload when the file changed; returns True when values were refreshed."""
115
+ try:
116
+ mtime = self.path.stat().st_mtime
117
+ except OSError:
118
+ return False
119
+ if not force and mtime == self._mtime:
120
+ return False
121
+ try:
122
+ parsed = json.loads(self.path.read_text(encoding="utf-8"))
123
+ except (OSError, json.JSONDecodeError):
124
+ return False
125
+ if not isinstance(parsed, dict):
126
+ return False
127
+ data = dict(DEFAULTS)
128
+ data.update({key: value for key, value in parsed.items() if key in DEFAULTS})
129
+ self._data = data
130
+ self._mtime = mtime
131
+ return True
132
+
133
+ # -- typed access ------------------------------------------------------- #
134
+ def get(self, key: str) -> Any:
135
+ self.reload()
136
+ return self._data.get(key, DEFAULTS.get(key))
137
+
138
+ def get_bool(self, key: str) -> bool:
139
+ value = self.get(key)
140
+ if isinstance(value, bool):
141
+ return value
142
+ return str(value).strip().lower() in {"1", "true", "yes", "on"}
143
+
144
+ def get_int(self, key: str) -> int:
145
+ try:
146
+ return int(self.get(key))
147
+ except (TypeError, ValueError):
148
+ try:
149
+ return int(DEFAULTS[key])
150
+ except KeyError:
151
+ return 0 # 未登记的新键不该把调用方炸掉
152
+
153
+ def get_float(self, key: str) -> float:
154
+ try:
155
+ return float(self.get(key))
156
+ except (TypeError, ValueError):
157
+ try:
158
+ return float(DEFAULTS[key])
159
+ except KeyError:
160
+ return 0.0
161
+
162
+ def snapshot(self, *, mask_secrets: bool = True) -> Dict[str, Any]:
163
+ self.reload()
164
+ data = dict(self._data)
165
+ if mask_secrets:
166
+ for key in SECRET_KEYS:
167
+ value = str(data.get(key) or "")
168
+ data[key] = (value[:4] + "****" + value[-2:]) if len(value) > 6 else ("****" if value else "")
169
+ return data
170
+
171
+ def update(self, patch: Dict[str, Any]) -> Dict[str, Any]:
172
+ """Persist a partial update; unknown keys and blank secrets are ignored."""
173
+ current = self.snapshot(mask_secrets=False)
174
+ for key, value in (patch or {}).items():
175
+ if key not in DEFAULTS:
176
+ continue
177
+ if key in SECRET_KEYS and isinstance(value, str) and value.strip() == "":
178
+ continue
179
+ current[key] = value
180
+ self.path.parent.mkdir(parents=True, exist_ok=True)
181
+ temporary = self.path.with_suffix(".tmp")
182
+ temporary.write_text(json.dumps(current, ensure_ascii=False, indent=2), encoding="utf-8")
183
+ os.replace(temporary, self.path)
184
+ self.reload(force=True)
185
+ return self.snapshot()
@@ -0,0 +1,11 @@
1
+ @echo off
2
+ setlocal
3
+ title DSH-QQ-Bot STOP
4
+
5
+ call "D:\anaconda3\Scripts\activate.bat" "D:\anaconda3" >nul 2>&1
6
+ call conda activate ChatClone-BotPy >nul 2>&1
7
+
8
+ cd /d "%~dp0"
9
+ echo Stopping the supervised bot (auto-restart will NOT bring it back)...
10
+ python -u main.py --stop
11
+ timeout /t 2 >nul
@@ -0,0 +1,48 @@
1
+ """Judge prompt must tell the model whether it is a bystander or the addressee."""
2
+ import os as _os, tempfile as _tempfile
3
+ _os.environ.setdefault("DSH_QQBOT_STATE_DIR", _tempfile.mkdtemp(prefix="qqbot-test-"))
4
+ import asyncio
5
+ import sys
6
+ import time
7
+ from pathlib import Path
8
+
9
+ sys.path.insert(0, str(Path('.').resolve()))
10
+ import test_group_alias as T # noqa: E402
11
+ from main import Chatter # noqa: E402
12
+
13
+
14
+ def check(name, ok, extra=""):
15
+ print(("ok " if ok else "FAIL ") + name + (f" {extra}" if extra else ""))
16
+ return 0 if ok else 1
17
+
18
+
19
+ async def prompt_for(lines):
20
+ bot = T.make_bot()
21
+ bot._register(T.CONV, "group", T.GROUP, "M1")
22
+ bot.chatter[T.CONV] = Chatter(lines=list(lines), first_at=time.time(), last_judge_at=0.0)
23
+ await bot._maybe_judge(T.CONV, force_timer=True)
24
+ bot._in_quiet_hours = lambda: False
25
+ return bot.bridge.calls[-1]["text"] if bot.bridge.calls else ""
26
+
27
+
28
+ async def main():
29
+ failures = 0
30
+
31
+ two_people = await prompt_for(["群友B0001: 好无聊啊", "群友A0002: 那我们去玩游戏吧"])
32
+ failures += check("两人对话 -> 标注旁观者",
33
+ "里发言的人" in two_people and "群友A0002" in two_people, two_people[:60])
34
+ failures += check("两人对话时仍给出沉默出口", "①" in two_people and "一对一搭话" in two_people)
35
+ failures += check("保留原格式与判断段", "像群里的一员那样" in two_people)
36
+
37
+ called = await prompt_for(["群友B0001: 好无聊啊", "群友A0002: 大肥鱼你觉得呢"])
38
+ failures += check("最后一句叫名字 -> 跳过判断直接作答",
39
+ "【群聊插话判断】" not in called and "大肥鱼你觉得呢" in called, called[:60])
40
+
41
+ solo = await prompt_for(["群友B0001: 今天好热"])
42
+ failures += check("单人独白 -> 只陈述事实不劝沉默", "最后一句来自" in solo and "沉默" in solo, solo[:60])
43
+
44
+ print("ALL PASS" if failures == 0 else f"{failures} FAILED")
45
+ return 0 if failures == 0 else 1
46
+
47
+
48
+ sys.exit(asyncio.run(main()))
@@ -0,0 +1,149 @@
1
+ """Offline check of the command paths in main.py (no gateway, no DSH)."""
2
+ import os as _os, tempfile as _tempfile
3
+ _os.environ.setdefault("DSH_QQBOT_STATE_DIR", _tempfile.mkdtemp(prefix="qqbot-test-"))
4
+ import asyncio
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from viseron_qqbotpy import GroupMessage, User
9
+
10
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
11
+ from main import DSHBot, load_config # noqa: E402
12
+
13
+
14
+ class _RT:
15
+ """Runtime-config stub: streaming on, everything else default."""
16
+
17
+ def get_bool(self, key, default=True):
18
+ if key == "group_at_only":
19
+ return False
20
+ return True if key == "stream_enabled" else default
21
+
22
+ def get_int(self, key, default=0):
23
+ return default
24
+
25
+ def get_float(self, key, default=0.0):
26
+ return default
27
+
28
+ def get_str(self, key, default=""):
29
+ return default
30
+
31
+ def get(self, key, default=None):
32
+ return default
33
+
34
+ class StubAPI:
35
+ def __init__(self):
36
+ self.posts = []
37
+ self.links = 0
38
+
39
+ async def get_group_bot_state(self, group_openid):
40
+ return {
41
+ "member_openid": "BOTMEMBER",
42
+ "joined_at": "2026-10-29T01:47:32+08:00",
43
+ "recv_msg_setting": "all",
44
+ "allow_proactive_msg": True,
45
+ "member_role": "member",
46
+ }
47
+
48
+ async def get_group_member(self, group_openid, member_openid):
49
+ raise RuntimeError("11253 capability not opened")
50
+
51
+ async def create_url_link(self, callback_data=None, **kwargs):
52
+ self.links += 1
53
+ return {"data": {"url": "https://bot.q.qq.com/s/TESTLINK"}}
54
+
55
+ async def post_group_message(self, **payload):
56
+ self.posts.append(payload)
57
+ return {"id": "m1"}
58
+
59
+
60
+ def make_bot():
61
+ config = load_config()
62
+ bot = DSHBot(intents=None, config=config) if False else DSHBot.__new__(DSHBot)
63
+ bot.config = config
64
+ bot.api = StubAPI()
65
+ bot.pool = {}
66
+ bot._chat_turns = {}
67
+ bot.member_index = {}
68
+ bot.pool_idx = {}
69
+ bot._pending_quotes = {}
70
+ bot.rt = _RT()
71
+ bot._suppress_reply = set()
72
+ bot._seen_ids = {}
73
+ bot._streamed_turns = {}
74
+ bot._streams = {}
75
+ bot._urgent_tasks = {}
76
+ bot._inflight = {}
77
+ bot._inflight_at = {}
78
+ bot._rate = {}
79
+ bot._submitted_at = {}
80
+ bot._bot_spoke_at = {}
81
+ bot._last_sent = {}
82
+ bot._last_bot_say = {}
83
+ bot._addressed_at = {}
84
+ bot.recent_images = {}
85
+ bot.chatter = {}
86
+ bot.queued = {}
87
+ bot.messages_owner = {}
88
+ bot._watchdog_task = None
89
+ bot.state = type("S", (), {
90
+ "owner_openid": "OWNER",
91
+ "group_owners": {"CCE96DDF6F462E1010E5721BBA1B6CBB": "35AD3A2431B0901EDD915A29F1AFF7F1"},
92
+ "save": lambda self: None,
93
+ })()
94
+ bot.owner_openid = "OWNER"
95
+ bot.targets = {}
96
+ bot.pending_approvals = {}
97
+ bot.pending = {}
98
+ bot.group_state = {}
99
+ bot.chime = {}
100
+ bot._msg_seq = 0
101
+ bot._acks = {}
102
+ bot._pull_task = None
103
+ bot._in_quiet_hours = lambda: False
104
+ return bot
105
+
106
+
107
+ def group_message(text, member="35AD3A2431B0901EDD915A29F1AFF7F1"):
108
+ return GroupMessage(
109
+ id="msg1",
110
+ group_openid="CCE96DDF6F462E1010E5721BBA1B6CBB",
111
+ content=text,
112
+ author=User(member_openid=member, user_openid="OWNEROPENID000000000000000000"),
113
+ )
114
+
115
+
116
+ async def main():
117
+ failures = []
118
+
119
+ bot = make_bot()
120
+ await bot.on_group_at_message_create(group_message("/状态"))
121
+ posts = bot.api.posts
122
+ body = posts[0]["content"] if posts and "content" in posts[0] else (posts[0].get("markdown") or {}).get("content", "")
123
+ ok = bool(posts) and "消息范围" in body and "全量" in body
124
+ print(("ok " if ok else "FAIL ") + "/状态 回复群状态")
125
+ if not ok:
126
+ failures.append("status")
127
+ print(" posts:", posts[:1])
128
+
129
+ bot = make_bot()
130
+ await bot.on_group_at_message_create(group_message("/链接"))
131
+ posts = bot.api.posts
132
+ body = (posts[0].get("content") or (posts[0].get("markdown") or {}).get("content", "")) if posts else ""
133
+ ok = "https://bot.q.qq.com/s/TESTLINK" in body
134
+ print(("ok " if ok else "FAIL ") + "/链接 返回邀请链接")
135
+ if not ok:
136
+ failures.append("link")
137
+
138
+ bot = make_bot()
139
+ await bot.on_group_at_message_create(group_message("/帮助"))
140
+ ok = bool(bot.api.posts)
141
+ print(("ok " if ok else "FAIL ") + "/帮助 有回复")
142
+ if not ok:
143
+ failures.append("help")
144
+
145
+ print("ALL PASS" if not failures else f"{len(failures)} FAILED")
146
+ return 0 if not failures else 1
147
+
148
+
149
+ sys.exit(asyncio.run(main()))
@@ -0,0 +1,149 @@
1
+ """Plan A routing: naming the bot in plain text must get a real answer."""
2
+ import os as _os, tempfile as _tempfile
3
+ _os.environ.setdefault("DSH_QQBOT_STATE_DIR", _tempfile.mkdtemp(prefix="qqbot-test-"))
4
+ import asyncio
5
+ import dataclasses
6
+ import sys
7
+ import time
8
+ from pathlib import Path
9
+
10
+ sys.path.insert(0, str(Path('.').resolve()))
11
+ from main import DSHBot, Chatter, load_config # noqa: E402
12
+
13
+ GROUP = "CCE96DDF6F462E1010E5721BBA1B6CBB"
14
+ CONV = f"group:{GROUP}"
15
+
16
+
17
+ class _RT:
18
+ def get_bool(self, key, default=True):
19
+ if key == "group_at_only":
20
+ return False
21
+ if key == "interject_hook_only":
22
+ return False # 这些用例验证的是判断提示词本身,不走省钱预筛
23
+ return default
24
+
25
+ def get_int(self, key, default=0):
26
+ return default
27
+
28
+ def get_float(self, key, default=0.0):
29
+ return default
30
+
31
+ def get_str(self, key, default=""):
32
+ return default
33
+
34
+ def get(self, key, default=None):
35
+ return default
36
+
37
+
38
+ class StubAPI:
39
+ def __init__(self):
40
+ self.posts = []
41
+
42
+ async def post_group_message(self, **kw):
43
+ self.posts.append(kw)
44
+ return {"id": "g1"}
45
+
46
+ async def post_c2c_message(self, **kw):
47
+ self.posts.append(kw)
48
+ return {"id": "c1"}
49
+
50
+ async def get_group_bot_state(self, group_openid):
51
+ return {"member_openid": "BOTMEMBER", "recv_msg_setting": "all", "allow_proactive_msg": True}
52
+
53
+
54
+ class StubBridge:
55
+ def __init__(self):
56
+ self.calls = []
57
+
58
+ async def inbound(self, **kw):
59
+ self.calls.append(kw)
60
+ return {"ok": True}
61
+
62
+ async def pull(self, cursor, wait):
63
+ return {"cursor": 0, "events": []}
64
+
65
+
66
+ class Msg:
67
+ def __init__(self, text, message_id="M1"):
68
+ self.id = message_id
69
+ self.content = text
70
+ self.group_openid = GROUP
71
+ self.attachments = []
72
+ self.mentions = []
73
+ self.raw = {}
74
+ self.author = type("A", (), {"member_openid": "MEMBER1", "user_openid": "U1"})()
75
+
76
+
77
+ def make_bot():
78
+ config = dataclasses.replace(load_config(), ack_delay_s=0, debounce_s=0.0, debounce_max_s=0.0)
79
+ bot = DSHBot.__new__(DSHBot)
80
+ bot.config = config
81
+ bot.api = StubAPI()
82
+ bot.bridge = StubBridge()
83
+ bot.state = type("S", (), {"owner_openid": "OWNER", "group_owners": {}, "save": lambda self: None})()
84
+ bot.owner_openid = "OWNER"
85
+ bot.rt = _RT()
86
+ bot._in_quiet_hours = lambda: False # 静默时段按真实时间判断,会让夜间跑测试假失败
87
+ for name in ("targets", "pending_approvals", "pending", "queued", "recent_images", "group_state", "chime",
88
+ "_seen_ids", "_submitted_at", "_inflight", "_inflight_at", "_rate", "_addressed_at",
89
+ "_bot_spoke_at", "_last_sent", "_last_bot_say", "_streams", "_acks", "_pending_quotes", "pool"):
90
+ setattr(bot, name, {})
91
+ bot.pool_idx = {}
92
+ bot._streamed_turns = {}
93
+ bot._chat_turns = {}
94
+ bot.member_index = {}
95
+ bot._suppress_reply = set()
96
+ bot._urgent_tasks = set()
97
+ bot._pull_task = None
98
+ bot._watchdog_task = None
99
+ bot.chatter = {}
100
+ bot._msg_seq = 0
101
+ return bot
102
+
103
+
104
+ def check(name, ok, extra=""):
105
+ print(("ok " if ok else "FAIL ") + name + (f" {extra}" if extra else ""))
106
+ return 0 if ok else 1
107
+
108
+
109
+ async def main():
110
+ failures = 0
111
+
112
+ bot = make_bot()
113
+ bot._register(CONV, "group", GROUP, "M1")
114
+ await bot.on_group_message_create(Msg("大肥鱼 你看看这个"))
115
+ await asyncio.sleep(0.2)
116
+ sent = bot.bridge.calls[-1]["text"] if bot.bridge.calls else ""
117
+ failures += check("正文里叫名字 -> 直接进工作模式", bool(sent) and "【群聊插话判断】" not in sent, sent[:40])
118
+
119
+ bot = make_bot()
120
+ bot._register(CONV, "group", GROUP, "M1")
121
+ bot.chatter[CONV] = Chatter(lines=["群友A: 大肥鱼在吗"], first_at=time.time(), last_judge_at=0.0)
122
+ await bot._maybe_judge(CONV, force_timer=True)
123
+ sent = bot.bridge.calls[-1]["text"] if bot.bridge.calls else ""
124
+ failures += check("缓冲里叫名字 -> 跳过判断直接答", bool(sent) and "【群聊插话判断】" not in sent, sent[:40])
125
+
126
+ bot = make_bot()
127
+ bot._register(CONV, "group", GROUP, "M1")
128
+ bot.chatter[CONV] = Chatter(lines=["群友A: 今晚开黑"], first_at=time.time(), last_judge_at=0.0)
129
+ await bot._maybe_judge(CONV, force_timer=True)
130
+ sent = bot.bridge.calls[-1]["text"] if bot.bridge.calls else ""
131
+ failures += check("普通闲聊 -> 仍走插话判断", "【群聊插话判断】" in sent, sent[:40])
132
+
133
+ bot = make_bot()
134
+ bot._register(CONV, "group", GROUP, "M1")
135
+ bot.chatter[CONV] = Chatter(lines=["群友A: 今晚开黑"], first_at=time.time(), last_judge_at=0.0)
136
+ await bot._maybe_judge(CONV, force_timer=True)
137
+ sent = bot.bridge.calls[-1]["text"] if bot.bridge.calls else ""
138
+ failures += check(
139
+ "判断提示词给出说话对象并留出口",
140
+ "最后一句来自" in sent and ("NO_REPLY" in sent or "[[join: 0~3]]" in sent),
141
+ "",
142
+ )
143
+
144
+ print("ALL PASS" if failures == 0 else f"{failures} FAILED")
145
+ return 0 if failures == 0 else 1
146
+
147
+
148
+ if __name__ == "__main__":
149
+ sys.exit(asyncio.run(main()))