fix: require @bot in groups, verify at target, ignore non-command and textless messages

This commit is contained in:
snowy-yang committed 2026-09-12 20:12:51 +08:00
1 parent f26f34cb87
commit e39d1a0f52
2 files changed
+120 -26

No files matched your search

+50 -3
View File
@@ -27,10 +27,15 @@ class FakeOneBotClient:
async def _read(self):
async for msg in self.ws:
data = json.loads(msg.data)
if data.get("action"): # API 请求:记录消息内容并回执
self.replies.append(data["params"].get("message", ""))
if data.get("action"):
if data["action"] == "get_login_info":
result = {"user_id": 88888, "nickname": "bot"}
else:
result = None
if data["action"].startswith("send_"):
self.replies.append(data["params"].get("message", ""))
await self.ws.send_str(json.dumps(
{"status": "ok", "retcode": 0, "data": None, "echo": data.get("echo")}))
{"status": "ok", "retcode": 0, "data": result, "echo": data.get("echo")}))
async def send_message(self, text: str):
await self.ws.send_str(json.dumps({
@@ -38,6 +43,13 @@ class FakeOneBotClient:
"user_id": 10000, "message": text,
}))
async def send_group_message(self, message, group_id: int = 999):
"""message 可为字符串或 CQ 段数组。"""
await self.ws.send_str(json.dumps({
"post_type": "message", "message_type": "group",
"group_id": group_id, "user_id": 10000, "message": message,
}))
async def close(self):
self._reader.cancel()
await self.ws.close()
@@ -90,3 +102,38 @@ async def test_status_cpu_display(client):
reply = await wait_reply(client)
# Linux 风格总占用 + 核心
assert "核心" in reply and "/" in reply
async def _expect_no_reply(client, send, timeout: float = 3.0):
"""发送后确认机器人在超时内没有回复。"""
before = len(client.replies)
await send()
for _ in range(int(timeout * 10)):
if len(client.replies) > before:
raise AssertionError(f"不应回复但收到了: {client.replies[-1]}")
await asyncio.sleep(0.1)
@pytest.mark.asyncio
async def test_private_non_command_ignored(client):
# 私聊发普通消息/无文本消息不触发
await _expect_no_reply(client, lambda: client.send_message("今天天气怎么样"))
await _expect_no_reply(
client, lambda: client.send_message(
[{"type": "image", "data": {"file": "abc.jpg"}}]))
@pytest.mark.asyncio
async def test_group_requires_at_me(client):
# 群聊不 @ 不响应
await _expect_no_reply(client, lambda: client.send_group_message("/status"))
# @ 别人不响应
await _expect_no_reply(client, lambda: client.send_group_message(
[{"type": "at", "data": {"qq": "66666"}},
{"type": "text", "data": {"text": " /status"}}]))
# @ 本人才响应
await client.send_group_message(
[{"type": "at", "data": {"qq": "88888"}},
{"type": "text", "data": {"text": " /status"}}])
reply = await wait_reply(client)
assert "服务器状态" in reply