Skip to content

Your lightweight open-source personal agent.

merge main into pr-532 and keep qq msg_seq/startup behavior while adding group @message support with regression tests

Re-bin3e9c5aa34a08
diff --cc nanobot/channels/qq.py
index c0eb2b182,6c5804900..4809fd3ed
--- a/nanobot/channels/qq.py
+++ b/nanobot/channels/qq.py
@@@ -13,7 -13,7 +13,7 @@@ from nanobot.config.schema import QQCon
try:
import botpy
- from botpy.message import C2CMessage, GroupMessage # 1. Import GroupMessage
- from botpy.message import C2CMessage
++ from botpy.message import C2CMessage, GroupMessage
QQ_AVAILABLE = True
except ImportError:
@@@ -33,23 -31,17 +32,20 @@@ def _make_bot_class(channel: "QQChannel
class _Bot(botpy.Client):
def __init__(self):
- super().__init__(intents=intents)
+ # Disable botpy's file log — nanobot uses loguru; default "botpy.log" fails on read-only fs
+ super().__init__(intents=intents, ext_handlers=False)
async def on_ready(self):
- logger.info(f"QQ bot ready: {self.robot.name}")
+ logger.info("QQ bot ready: {}", self.robot.name)
async def on_c2c_message_create(self, message: "C2CMessage"):
- # C2C (Private) message
- await channel._on_message(message)
+ await channel._on_message(message, is_group=False)
+
+ async def on_group_at_message_create(self, message: "GroupMessage"):
- # 3. Added: Listen for group @messages
- # Note: Official bots only receive messages @mentioning them unless privileged
+ await channel._on_message(message, is_group=True)
async def on_direct_message_create(self, message):
- # Guild Direct Message
- await channel._on_message(message)
+ await channel._on_message(message, is_group=False)
return _Bot
@@@ -64,10 -56,7 +60,8 @@@ class QQChannel(BaseChannel)
self.config: QQConfig = config
self._client: "botpy.Client | None" = None
self._processed_ids: deque = deque(maxlen=1000)
- self._bot_task: asyncio.Task | None = None
- # Cache to track if chat_id is a group or individual to select the correct reply API
- # Format: {chat_id: "group" | "c2c"}
- self._chat_type_cache: Dict[str, str] = {}
+ self._msg_seq: int = 1 # 消息序列号,避免被 QQ API 去重
++ self._chat_type_cache: dict[str, str] = {}
async def start(self) -> None:
"""Start the QQ bot."""
@@@ -82,9 -71,9 +76,8 @@@
self._running = True
BotClass = _make_bot_class(self)
self._client = BotClass()
--
- self._bot_task = asyncio.create_task(self._run_bot())
- logger.info("QQ bot started (C2C private message)")
+ logger.info("QQ bot started (C2C & Group supported)")
+ await self._run_bot()
async def _run_bot(self) -> None:
"""Run the bot connection with auto-reconnect."""
@@@ -113,31 -101,20 +105,31 @@@
if not self._client:
logger.warning("QQ client not initialized")
return
-
- # 4. Modified send logic: Check chat_id type to call the correct API
- msg_type = self._chat_type_cache.get(msg.chat_id, "c2c") # Default to c2c
+
try:
+ msg_id = msg.metadata.get("message_id")
- self._msg_seq += 1 # 递增序列号
- await self._client.api.post_c2c_message(
- openid=msg.chat_id,
- msg_type=0,
- content=msg.content,
- msg_id=msg_id,
- msg_seq=self._msg_seq, # 添加序列号避免去重
- )
++ self._msg_seq += 1
++ msg_type = self._chat_type_cache.get(msg.chat_id, "c2c")
+ if msg_type == "group":
- # Send group message
+ await self._client.api.post_group_message(
+ group_openid=msg.chat_id,
- msg_type=0,
- msg_id=msg.metadata.get("message_id"), # Reply to specific message ID (optional but recommended)
- content=msg.content
++ msg_type=0,
++ content=msg.content,
++ msg_id=msg_id,
++ msg_seq=self._msg_seq,
+ )
+ else:
- # Send C2C (private) message
+ await self._client.api.post_c2c_message(
+ openid=msg.chat_id,
+ msg_type=0,
- msg_id=msg.metadata.get("message_id"),
+ content=msg.content,
++ msg_id=msg_id,
++ msg_seq=self._msg_seq,
+ )
except Exception as e:
- logger.error(f"Error sending QQ message ({msg_type}): {e}")
+ logger.error("Error sending QQ message: {}", e)
- async def _on_message(self, data: "C2CMessage") -> None:
+ async def _on_message(self, data: "C2CMessage | GroupMessage", is_group: bool = False) -> None:
"""Handle incoming message from QQ."""
try:
# Dedup by message ID
@@@ -149,26 -128,12 +141,20 @@@
if not content:
return
- # 5. Extract ID and cache type
+ if is_group:
- # Group message: chat_id uses group_openid
+ chat_id = data.group_openid
- user_id = data.author.member_openid # Sender's ID
++ user_id = data.author.member_openid
+ self._chat_type_cache[chat_id] = "group"
-
- # Remove @bot text (optional, prevents Nanobot from treating the name as prompt)
- # content = content.replace("@BotName", "").strip()
+ else:
- # Private message: chat_id uses user_openid
+ chat_id = str(getattr(data.author, 'id', None) or getattr(data.author, 'user_openid', 'unknown'))
+ user_id = chat_id
+ self._chat_type_cache[chat_id] = "c2c"
+
await self._handle_message(
sender_id=user_id,
- chat_id=user_id,
+ chat_id=chat_id,
content=content,
metadata={"message_id": data.id},
)
- except Exception as e:
- logger.error(f"Error handling QQ message: {e}")
+ except Exception:
+ logger.exception("Error handling QQ message")
-
diff --cc tests/test_qq_channel.py
index 000000000,000000000..90b4e6010
new file mode 100644
--- /dev/null
+++ b/tests/test_qq_channel.py
@@@ -1,0 -1,0 +1,66 @@@
++from types import SimpleNamespace
++
++import pytest
++
++from nanobot.bus.events import OutboundMessage
++from nanobot.bus.queue import MessageBus
++from nanobot.channels.qq import QQChannel
++from nanobot.config.schema import QQConfig
++
++
++class _FakeApi:
++ def __init__(self) -> None:
++ self.c2c_calls: list[dict] = []
++ self.group_calls: list[dict] = []
++
++ async def post_c2c_message(self, **kwargs) -> None:
++ self.c2c_calls.append(kwargs)
++
++ async def post_group_message(self, **kwargs) -> None:
++ self.group_calls.append(kwargs)
++
++
++class _FakeClient:
++ def __init__(self) -> None:
++ self.api = _FakeApi()
++
++
++async def test_on_group_message_routes_to_group_chat_id() -> None:
++ channel = QQChannel(QQConfig(app_id="app", secret="secret", allow_from=["user1"]), MessageBus())
++
++ data = SimpleNamespace(
++ id="msg1",
++ content="hello",
++ group_openid="group123",
++ author=SimpleNamespace(member_openid="user1"),
++ )
++
++ await channel._on_message(data, is_group=True)
++
++ msg = await channel.bus.consume_inbound()
++ assert msg.sender_id == "user1"
++ assert msg.chat_id == "group123"
++
++
++async def test_send_group_message_uses_group_api_with_msg_seq() -> None:
++ channel = QQChannel(QQConfig(app_id="app", secret="secret", allow_from=["*"]), MessageBus())
++ channel._client = _FakeClient()
++ channel._chat_type_cache["group123"] = "group"
++
++ await channel.send(
++ OutboundMessage(
++ channel="qq",
++ chat_id="group123",
++ content="hello",
++ metadata={"message_id": "msg1"},
++ )
++ )
++
++ assert len(channel._client.api.group_calls) == 1
++ call = channel._client.api.group_calls[0]
++ assert call["group_openid"] == "group123"
++ assert call["msg_id"] == "msg1"
++ assert call["msg_seq"] == 2
++ assert not channel._client.api.c2c_calls