diff --git a/matrix/room.py b/matrix/room.py index 2cde9f2..162cfae 100644 --- a/matrix/room.py +++ b/matrix/room.py @@ -461,3 +461,21 @@ async def kick_user(self, user_id: str, reason: str | None = None) -> None: ) except Exception as e: raise MatrixError(f"Failed to kick user: {e}") + + async def leave(self) -> None: + """Leave the room. + + The bot will leave the room and will no longer receive events from it. + This is useful for bots that join rooms temporarily or need to decline + invitations after inspection. + + ## Example + + ```python + await room.leave() + ``` + """ + try: + await self.client.room_leave(room_id=self.room_id) + except Exception as e: + raise MatrixError(f"Failed to leave room: {e}") diff --git a/tests/test_room.py b/tests/test_room.py index 8d5e39a..a5bc0a2 100644 --- a/tests/test_room.py +++ b/tests/test_room.py @@ -368,6 +368,26 @@ async def test_kick_user_with_error__expect_matrix_error(room, client): await room.kick_user("@troublemaker:example.com") +# LEAVE + + +@pytest.mark.asyncio +async def test_leave__expect_room_leave_called(room, client): + client.room_leave = AsyncMock() + + await room.leave() + + client.room_leave.assert_awaited_once_with(room_id="!room:example.com") + + +@pytest.mark.asyncio +async def test_leave_with_error__expect_matrix_error(room, client): + client.room_leave = AsyncMock(side_effect=Exception("Not in room")) + + with pytest.raises(MatrixError, match="Failed to leave room"): + await room.leave() + + def test_room_properties__expect_correct_delegation_to_matrix_room(room, matrix_room): assert room.room_id == "!room:example.com" assert room.name == "Test Room"