diff --git a/adapter/matrix/bot.py b/adapter/matrix/bot.py index cf8fc2a..44d7c95 100644 --- a/adapter/matrix/bot.py +++ b/adapter/matrix/bot.py @@ -190,8 +190,11 @@ class MatrixBot: user=sender, ) return - chat_id = await resolve_chat_id(self.runtime.store, room.room_id, sender) - incoming = from_room_event(event, room_id=room.room_id, chat_id=chat_id) + local_chat_id = await resolve_chat_id(self.runtime.store, room.room_id, sender) + dispatch_chat_id = local_chat_id + if not body.startswith("!"): + dispatch_chat_id = (room_meta or {}).get("platform_chat_id") or local_chat_id + incoming = from_room_event(event, room_id=room.room_id, chat_id=dispatch_chat_id) if incoming is None: return try: @@ -206,7 +209,7 @@ class MatrixBot: ) outgoing = [ OutgoingMessage( - chat_id=chat_id, + chat_id=dispatch_chat_id, text="Сервис временно недоступен. Попробуйте ещё раз позже." ) ] diff --git a/tests/adapter/matrix/test_dispatcher.py b/tests/adapter/matrix/test_dispatcher.py index b3efa85..10a4f36 100644 --- a/tests/adapter/matrix/test_dispatcher.py +++ b/tests/adapter/matrix/test_dispatcher.py @@ -253,6 +253,56 @@ async def test_bot_assigns_platform_chat_id_for_existing_managed_room(): runtime.dispatcher.dispatch.assert_awaited_once() +async def test_bot_routes_plain_messages_via_platform_chat_id(): + runtime = build_runtime(platform=MockPlatformClient()) + await set_room_meta( + runtime.store, + "!chat1:example.org", + { + "chat_id": "C1", + "matrix_user_id": "@alice:example.org", + "platform_chat_id": "matrix:ctx-1", + }, + ) + client = SimpleNamespace(user_id="@bot:example.org") + bot = MatrixBot(client, runtime) + bot._send_all = AsyncMock() + runtime.dispatcher.dispatch = AsyncMock(return_value=[]) + room = SimpleNamespace(room_id="!chat1:example.org") + event = SimpleNamespace(sender="@alice:example.org", body="hello") + + await bot.on_room_message(room, event) + + dispatched = runtime.dispatcher.dispatch.await_args.args[0] + assert dispatched.chat_id == "matrix:ctx-1" + assert dispatched.text == "hello" + + +async def test_bot_keeps_commands_on_local_chat_id(): + runtime = build_runtime(platform=MockPlatformClient()) + await set_room_meta( + runtime.store, + "!chat1:example.org", + { + "chat_id": "C1", + "matrix_user_id": "@alice:example.org", + "platform_chat_id": "matrix:ctx-1", + }, + ) + client = SimpleNamespace(user_id="@bot:example.org") + bot = MatrixBot(client, runtime) + bot._send_all = AsyncMock() + runtime.dispatcher.dispatch = AsyncMock(return_value=[]) + room = SimpleNamespace(room_id="!chat1:example.org") + event = SimpleNamespace(sender="@alice:example.org", body="!rename New") + + await bot.on_room_message(room, event) + + dispatched = runtime.dispatcher.dispatch.await_args.args[0] + assert dispatched.chat_id == "C1" + assert dispatched.command == "rename" + + async def test_bot_leaves_existing_platform_chat_id_unchanged(): runtime = build_runtime(platform=MockPlatformClient()) await set_room_meta(