formatting

This commit is contained in:
William Kray
2025-09-09 21:21:51 -07:00
parent 5f42420619
commit a92759c100
14 changed files with 1380 additions and 967 deletions
+637 -282
View File
File diff suppressed because it is too large Load Diff
+14 -1
View File
@@ -1,2 +1,15 @@
# Helper modules for community bot
from . import message_utils, room_utils, user_utils, database_utils, report_utils, decorators, common_utils, room_creation_utils, config_manager, response_builder, diagnostic_utils, base_command_handler
from . import (
message_utils,
room_utils,
user_utils,
database_utils,
report_utils,
decorators,
common_utils,
room_creation_utils,
config_manager,
response_builder,
diagnostic_utils,
base_command_handler,
)
+15 -5
View File
@@ -36,7 +36,9 @@ class BaseCommandHandler(ABC):
"""
pass
async def check_permissions(self, evt: MessageEvent, min_level: int = 50, room_id: str = None) -> bool:
async def check_permissions(
self, evt: MessageEvent, min_level: int = 50, room_id: str = None
) -> bool:
"""Check if user has required permissions.
Args:
@@ -78,7 +80,9 @@ class BaseCommandHandler(ABC):
"""
await evt.reply(message)
async def respond_html(self, evt: MessageEvent, message: str, edits: Optional[MessageEvent] = None) -> None:
async def respond_html(
self, evt: MessageEvent, message: str, edits: Optional[MessageEvent] = None
) -> None:
"""Respond with HTML content.
Args:
@@ -174,7 +178,9 @@ class ModeratorCommandHandler(BaseCommandHandler):
return await self.execute_moderator_command(evt, *args, **kwargs)
@abstractmethod
async def execute_moderator_command(self, evt: MessageEvent, *args, **kwargs) -> Any:
async def execute_moderator_command(
self, evt: MessageEvent, *args, **kwargs
) -> Any:
"""Execute the moderator command logic.
Args:
@@ -225,7 +231,9 @@ class SpaceModeratorCommandHandler(SpaceCommandHandler, ModeratorCommandHandler)
return await self.execute_space_moderator_command(evt, *args, **kwargs)
@abstractmethod
async def execute_space_moderator_command(self, evt: MessageEvent, *args, **kwargs) -> Any:
async def execute_space_moderator_command(
self, evt: MessageEvent, *args, **kwargs
) -> Any:
"""Execute the space moderator command logic.
Args:
@@ -252,7 +260,9 @@ class SpaceAdminCommandHandler(SpaceCommandHandler, AdminCommandHandler):
return await self.execute_space_admin_command(evt, *args, **kwargs)
@abstractmethod
async def execute_space_admin_command(self, evt: MessageEvent, *args, **kwargs) -> Any:
async def execute_space_admin_command(
self, evt: MessageEvent, *args, **kwargs
) -> Any:
"""Execute the space admin command logic.
Args:
+4 -9
View File
@@ -179,7 +179,6 @@ class ConfigManager:
"""
return self.config.get("verification_timeout", 300)
def get_banlist_rooms(self) -> List[str]:
"""Get the list of banlist rooms.
@@ -202,11 +201,7 @@ class ConfigManager:
Returns:
List[str]: List of missing required configuration keys
"""
required_configs = [
"parent_room",
"room_version",
"community_slug"
]
required_configs = ["parent_room", "room_version", "community_slug"]
missing = []
for config_key in required_configs:
@@ -239,7 +234,7 @@ class ConfigManager:
"invitees": self.get_invitees(),
"invite_power_level": self.get_invite_power_level(),
"encrypt": self.is_encryption_enabled(),
"parent_room": self.get_parent_room()
"parent_room": self.get_parent_room(),
}
def get_tracking_settings(self) -> Dict[str, Any]:
@@ -253,7 +248,7 @@ class ConfigManager:
"track_messages": self.is_message_tracking_enabled(),
"track_reactions": self.is_reaction_tracking_enabled(),
"warn_threshold_days": self.get_warn_threshold_days(),
"kick_threshold_days": self.get_kick_threshold_days()
"kick_threshold_days": self.get_kick_threshold_days(),
}
def get_verification_settings(self) -> Dict[str, Any]:
@@ -266,5 +261,5 @@ class ConfigManager:
"verification_enabled": self.is_verification_enabled(),
"verification_phrase": self.get_verification_phrase(),
"verification_attempts": self.get_verification_attempts(),
"verification_timeout": self.get_verification_timeout()
"verification_timeout": self.get_verification_timeout(),
}
+30 -18
View File
@@ -40,7 +40,9 @@ async def get_messages_to_redact(client, room_id: str, mxid: str, logger) -> Lis
return []
async def redact_messages(client, database, room_id: str, sleep_time: float, logger) -> Dict[str, int]:
async def redact_messages(
client, database, room_id: str, sleep_time: float, logger
) -> Dict[str, int]:
"""Redact messages queued for redaction in a room.
Args:
@@ -59,9 +61,7 @@ async def redact_messages(client, database, room_id: str, sleep_time: float, log
)
for event in events:
try:
await client.redact(
room_id, event["event_id"], reason="content removed"
)
await client.redact(room_id, event["event_id"], reason="content removed")
counters["success"] += 1
await database.execute(
"DELETE FROM redaction_tasks WHERE event_id = $1", event["event_id"]
@@ -103,8 +103,9 @@ async def upsert_user_timestamp(database, mxid: str, timestamp: int, logger) ->
logger.error(f"Failed to upsert user timestamp: {e}")
async def get_inactive_users(database, warn_threshold_days: int, kick_threshold_days: int,
logger) -> Dict[str, List[str]]:
async def get_inactive_users(
database, warn_threshold_days: int, kick_threshold_days: int, logger
) -> Dict[str, List[str]]:
"""Get lists of users who should be warned or kicked for inactivity.
Args:
@@ -145,7 +146,7 @@ async def get_inactive_users(database, warn_threshold_days: int, kick_threshold_
return {
"warn": [row["mxid"] for row in warn_results],
"kick": [row["mxid"] for row in kick_results]
"kick": [row["mxid"] for row in kick_results],
}
except Exception as e:
logger.error(f"Failed to get inactive users: {e}")
@@ -182,17 +183,22 @@ async def get_verification_state(database, dm_room_id: str) -> Dict[str, Any]:
"""
try:
result = await database.fetchrow(
"SELECT * FROM verification_states WHERE dm_room_id = $1",
dm_room_id
"SELECT * FROM verification_states WHERE dm_room_id = $1", dm_room_id
)
return dict(result) if result else None
except Exception as e:
return None
async def create_verification_state(database, dm_room_id: str, user_id: str,
target_room_id: str, verification_phrase: str,
attempts_remaining: int, required_power_level: int) -> None:
async def create_verification_state(
database,
dm_room_id: str,
user_id: str,
target_room_id: str,
verification_phrase: str,
attempts_remaining: int,
required_power_level: int,
) -> None:
"""Create a new verification state.
Args:
@@ -211,14 +217,20 @@ async def create_verification_state(database, dm_room_id: str, user_id: str,
(dm_room_id, user_id, target_room_id, verification_phrase, attempts_remaining, required_power_level)
VALUES ($1, $2, $3, $4, $5, $6)
""",
dm_room_id, user_id, target_room_id, verification_phrase,
attempts_remaining, required_power_level
dm_room_id,
user_id,
target_room_id,
verification_phrase,
attempts_remaining,
required_power_level,
)
except Exception as e:
pass # Verification state creation is not critical
async def update_verification_attempts(database, dm_room_id: str, attempts_remaining: int) -> None:
async def update_verification_attempts(
database, dm_room_id: str, attempts_remaining: int
) -> None:
"""Update verification attempts remaining.
Args:
@@ -229,7 +241,8 @@ async def update_verification_attempts(database, dm_room_id: str, attempts_remai
try:
await database.execute(
"UPDATE verification_states SET attempts_remaining = $1 WHERE dm_room_id = $2",
attempts_remaining, dm_room_id
attempts_remaining,
dm_room_id,
)
except Exception as e:
pass # Verification state update is not critical
@@ -244,8 +257,7 @@ async def delete_verification_state(database, dm_room_id: str) -> None:
"""
try:
await database.execute(
"DELETE FROM verification_states WHERE dm_room_id = $1",
dm_room_id
"DELETE FROM verification_states WHERE dm_room_id = $1", dm_room_id
)
except Exception as e:
pass # Verification state deletion is not critical
+8
View File
@@ -12,6 +12,7 @@ def require_permission(min_level: int = 50, room_id: Optional[str] = None):
min_level: Minimum required power level (default 50 for moderator)
room_id: Room ID to check permissions in (None for parent room)
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
async def wrapper(self, evt: MessageEvent, *args, **kwargs) -> Any:
@@ -19,17 +20,21 @@ def require_permission(min_level: int = 50, room_id: Optional[str] = None):
await evt.reply("You don't have permission to use this command")
return
return await func(self, evt, *args, **kwargs)
return wrapper
return decorator
def require_parent_room(func: Callable) -> Callable:
"""Decorator to require parent room to be configured."""
@functools.wraps(func)
async def wrapper(self, evt: MessageEvent, *args, **kwargs) -> Any:
if not await self.check_parent_room(evt):
return
return await func(self, evt, *args, **kwargs)
return wrapper
@@ -39,6 +44,7 @@ def handle_errors(error_message: str = "An error occurred"):
Args:
error_message: Default error message to show to user
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
async def wrapper(self, evt: MessageEvent, *args, **kwargs) -> Any:
@@ -47,5 +53,7 @@ def handle_errors(error_message: str = "An error occurred"):
except Exception as e:
self.log.error(f"Error in {func.__name__}: {e}")
await evt.reply(f"{error_message}: {e}")
return wrapper
return decorator
+54 -69
View File
@@ -6,9 +6,7 @@ from mautrix.client import Client
async def check_space_permissions(
client: Client,
parent_room: str,
logger
client: Client, parent_room: str, logger
) -> Dict[str, Any]:
"""Check bot permissions in the parent space.
@@ -28,7 +26,10 @@ async def check_space_permissions(
# Check if bot has unlimited power (creator in modern room versions)
from .room_utils import user_has_unlimited_power
bot_has_unlimited_power = await user_has_unlimited_power(client, client.mxid, parent_room)
bot_has_unlimited_power = await user_has_unlimited_power(
client, client.mxid, parent_room
)
space_info = {
"room_id": parent_room,
@@ -37,40 +38,28 @@ async def check_space_permissions(
"bot_has_unlimited_power": bot_has_unlimited_power,
"users_higher_or_equal": [],
"users_equal": [],
"users_higher": []
"users_higher": [],
}
# Check for users with equal or higher power level
for user, level in space_power_levels.users.items():
if user != client.mxid and level >= bot_level:
if level == bot_level:
space_info["users_equal"].append({
"user": user,
"level": level
})
space_info["users_equal"].append({"user": user, "level": level})
else:
space_info["users_higher"].append({
"user": user,
"level": level
})
space_info["users_higher_or_equal"].append({
"user": user,
"level": level
})
space_info["users_higher"].append({"user": user, "level": level})
space_info["users_higher_or_equal"].append(
{"user": user, "level": level}
)
return space_info
except Exception as e:
logger.error(f"Failed to check space permissions: {e}")
return {
"room_id": parent_room,
"error": str(e)
}
return {"room_id": parent_room, "error": str(e)}
async def check_room_permissions(
client: Client,
room_id: str,
logger
client: Client, room_id: str, logger
) -> Dict[str, Any]:
"""Check bot permissions in a specific room.
@@ -87,10 +76,7 @@ async def check_room_permissions(
try:
await client.get_state_event(room_id, EventType.ROOM_MEMBER, client.mxid)
except:
return {
"room_id": room_id,
"error": "Bot not in room"
}
return {"room_id": room_id, "error": "Bot not in room"}
# Get power levels
room_power_levels = await client.get_state_event(
@@ -102,17 +88,24 @@ async def check_room_permissions(
room_name = room_id
try:
from .common_utils import get_room_name
room_name = await get_room_name(client, room_id, logger) or room_id
except:
pass
# Get room version and creators
from .room_utils import get_room_version_and_creators
room_version, creators = await get_room_version_and_creators(client, room_id, logger)
room_version, creators = await get_room_version_and_creators(
client, room_id, logger
)
# Check if bot has unlimited power (creator in modern room versions)
from .room_utils import user_has_unlimited_power
bot_has_unlimited_power = await user_has_unlimited_power(client, client.mxid, room_id)
bot_has_unlimited_power = await user_has_unlimited_power(
client, client.mxid, room_id
)
room_report = {
"room_id": room_id,
@@ -124,39 +117,28 @@ async def check_room_permissions(
"bot_has_unlimited_power": bot_has_unlimited_power,
"users_higher_or_equal": [],
"users_equal": [],
"users_higher": []
"users_higher": [],
}
# Check for users with equal or higher power level
for user, level in room_power_levels.users.items():
if user != client.mxid and level >= bot_level:
if level == bot_level:
room_report["users_equal"].append({
"user": user,
"level": level
})
room_report["users_equal"].append({"user": user, "level": level})
else:
room_report["users_higher"].append({
"user": user,
"level": level
})
room_report["users_higher_or_equal"].append({
"user": user,
"level": level
})
room_report["users_higher"].append({"user": user, "level": level})
room_report["users_higher_or_equal"].append(
{"user": user, "level": level}
)
return room_report
except Exception as e:
logger.error(f"Failed to check room permissions for {room_id}: {e}")
return {
"room_id": room_id,
"error": str(e)
}
return {"room_id": room_id, "error": str(e)}
def analyze_room_data(
room_data: Dict[str, Any],
is_modern_room_version_func
room_data: Dict[str, Any], is_modern_room_version_func
) -> Tuple[str, str, bool, bool, bool]:
"""Analyze room data to determine status and categorization.
@@ -185,9 +167,7 @@ def analyze_room_data(
return "no_admin", "problematic", False, is_modern, False
def generate_space_summary(
space_data: Dict[str, Any]
) -> str:
def generate_space_summary(space_data: Dict[str, Any]) -> str:
"""Generate HTML summary for space permissions.
Args:
@@ -218,8 +198,7 @@ def generate_space_summary(
def generate_room_summary(
rooms_data: Dict[str, Any],
is_modern_room_version_func
rooms_data: Dict[str, Any], is_modern_room_version_func
) -> Tuple[str, Dict[str, int]]:
"""Generate HTML summary for room permissions.
@@ -237,7 +216,7 @@ def generate_room_summary(
"error_rooms": 0,
"not_in_room_count": 0,
"modern_rooms": 0,
"legacy_rooms": 0
"legacy_rooms": 0,
}
for room_id, room_data in rooms_data.items():
@@ -262,12 +241,18 @@ def generate_room_summary(
stats["legacy_rooms"] += 1
# Generate room info for problematic rooms
if category in ["error", "problematic"] or (is_admin and (room_data.get("users_higher") or room_data.get("users_equal"))):
if category in ["error", "problematic"] or (
is_admin and (room_data.get("users_higher") or room_data.get("users_equal"))
):
if has_error:
if room_data["error"] == "Bot not in room":
problematic_rooms.append(f"❌ <b>{room_data.get('room_name', room_id)}</b> ({room_id}): Bot not in room")
problematic_rooms.append(
f"❌ <b>{room_data.get('room_name', room_id)}</b> ({room_id}): Bot not in room"
)
else:
problematic_rooms.append(f"❌ <b>{room_data.get('room_name', room_id)}</b> ({room_id}): Error - {room_data['error']}")
problematic_rooms.append(
f"❌ <b>{room_data.get('room_name', room_id)}</b> ({room_id}): Error - {room_data['error']}"
)
elif is_admin:
# Show unlimited power status for modern rooms
if room_data.get("bot_has_unlimited_power", False):
@@ -283,10 +268,14 @@ def generate_room_summary(
if room_data.get("users_higher"):
room_info += f" - Higher power users: {len(room_data['users_higher'])}"
if room_data.get("users_equal"):
room_info += f" - Equal power users: {len(room_data['users_equal'])}"
room_info += (
f" - Equal power users: {len(room_data['users_equal'])}"
)
problematic_rooms.append(room_info)
else:
problematic_rooms.append(f"❌ <b>{room_data['room_name']}</b> ({room_id}): Admin: No (level: {room_data['bot_power_level']}) [v{room_data.get('room_version', '1')}]")
problematic_rooms.append(
f"❌ <b>{room_data['room_name']}</b> ({room_id}): Admin: No (level: {room_data['bot_power_level']}) [v{room_data.get('room_version', '1')}]"
)
# Generate HTML response
response = ""
@@ -301,8 +290,7 @@ def generate_room_summary(
def generate_summary_stats(
space_data: Dict[str, Any],
room_stats: Dict[str, int]
space_data: Dict[str, Any], room_stats: Dict[str, int]
) -> str:
"""Generate summary statistics HTML.
@@ -321,22 +309,19 @@ def generate_summary_stats(
response += f"• Legacy room versions (1-11): {room_stats['legacy_rooms']}<br />"
# Add note about unlimited power for modern rooms
if room_stats['modern_rooms'] > 0:
if room_stats["modern_rooms"] > 0:
response += f"<br />️ <b>Note:</b> In modern room versions (12+), creators have unlimited power and cannot be restricted by power levels.<br />"
if room_stats['not_in_room_count'] > 0:
if room_stats["not_in_room_count"] > 0:
response += f"• Rooms bot not in: {room_stats['not_in_room_count']}<br />"
if room_stats['error_rooms'] > 0:
if room_stats["error_rooms"] > 0:
response += f"• Rooms with errors: {room_stats['error_rooms']}<br />"
response += "<br />"
return response
def generate_issues_and_warnings(
issues: List[str],
warnings: List[str]
) -> str:
def generate_issues_and_warnings(issues: List[str], warnings: List[str]) -> str:
"""Generate issues and warnings HTML.
Args:
+1 -1
View File
@@ -95,4 +95,4 @@ def generate_community_slug(community_name: str) -> str:
str: A slug made from the first letter of each word, lowercase
"""
words = community_name.strip().split()
return ''.join(word[0].lower() for word in words if word)
return "".join(word[0].lower() for word in words if word)
+5 -5
View File
@@ -52,7 +52,7 @@ def split_doctor_report(report_text: str, max_chunk_size: int = 4000) -> List[st
chunks = []
current_chunk = ""
for line in report_text.split('\n'):
for line in report_text.split("\n"):
if len(current_chunk) + len(line) + 1 > max_chunk_size:
if current_chunk:
chunks.append(current_chunk.strip())
@@ -63,7 +63,7 @@ def split_doctor_report(report_text: str, max_chunk_size: int = 4000) -> List[st
current_chunk = line[max_chunk_size:]
else:
if current_chunk:
current_chunk += '\n' + line
current_chunk += "\n" + line
else:
current_chunk = line
@@ -87,7 +87,7 @@ def _split_by_sections(text: str, max_size: int) -> List[str]:
sections = []
current_section = ""
lines = text.split('\n')
lines = text.split("\n")
for line in lines:
if any(line.startswith(header) for header in section_headers):
if current_section and len(current_section) > max_size:
@@ -101,7 +101,7 @@ def _split_by_sections(text: str, max_size: int) -> List[str]:
# This section would be too big
return []
if current_section:
current_section += '\n' + line
current_section += "\n" + line
else:
current_section = line
@@ -133,7 +133,7 @@ def format_ban_results(ban_event_map: Dict[str, List[str]]) -> str:
if rooms:
result_parts.append(f"Failed to ban {user} from: {', '.join(rooms)}")
return '\n'.join(result_parts) if result_parts else "No ban operations performed"
return "\n".join(result_parts) if result_parts else "No ban operations performed"
def format_sync_results(sync_results: Dict[str, List[str]]) -> str:
+19 -9
View File
@@ -57,7 +57,9 @@ class ResponseBuilder:
return f"Success: {message}"
@staticmethod
def build_list_response(title: str, items: List[str], allow_html: bool = True) -> str:
def build_list_response(
title: str, items: List[str], allow_html: bool = True
) -> str:
"""Build a list response.
Args:
@@ -69,7 +71,9 @@ class ResponseBuilder:
str: Formatted list response
"""
if not items:
return ResponseBuilder.build_html_response(title, "No items found.", allow_html)
return ResponseBuilder.build_html_response(
title, "No items found.", allow_html
)
if allow_html:
items_html = "<br />".join(items)
@@ -104,7 +108,9 @@ class ResponseBuilder:
return f"<a href='https://matrix.to/#/{user_id}'>{user_id}</a>"
@staticmethod
def build_activity_report_response(report: Dict[str, List[str]], config: Dict[str, Any]) -> str:
def build_activity_report_response(
report: Dict[str, List[str]], config: Dict[str, Any]
) -> str:
"""Build an activity report response.
Args:
@@ -135,9 +141,7 @@ class ResponseBuilder:
if report.get("ignored"):
ignored_list = "<br />".join(report["ignored"])
response_parts.append(
f"<p><b>Ignored users:</b><br />{ignored_list}</p>"
)
response_parts.append(f"<p><b>Ignored users:</b><br />{ignored_list}</p>")
return "".join(response_parts)
@@ -158,11 +162,15 @@ class ResponseBuilder:
if ban_list:
ban_list_html = "<br />".join(ban_list)
response_parts.append(f"<p><b>Users banned:</b><br /><code>{ban_list_html}</code></p>")
response_parts.append(
f"<p><b>Users banned:</b><br /><code>{ban_list_html}</code></p>"
)
if error_list:
error_list_html = "<br />".join(error_list)
response_parts.append(f"<p><b>Errors:</b><br /><code>{error_list_html}</code></p>")
response_parts.append(
f"<p><b>Errors:</b><br /><code>{error_list_html}</code></p>"
)
if not response_parts:
response_parts.append("<p>No users were banned.</p>")
@@ -213,7 +221,9 @@ class ResponseBuilder:
if report.get("space"):
space = report["space"]
space_info = f"<b>Space:</b> {space.get('room_id', 'Unknown')}<br />"
space_info += f"Bot Power Level: {space.get('bot_power_level', 'Unknown')}<br />"
space_info += (
f"Bot Power Level: {space.get('bot_power_level', 'Unknown')}<br />"
)
space_info += f"Has Admin: {space.get('has_admin', False)}<br />"
response_parts.append(f"<p>{space_info}</p>")
+48 -46
View File
@@ -8,9 +8,7 @@ from mautrix.client import Client
async def validate_room_creation_params(
roomname: str,
config: dict,
evt: Optional[MessageEvent] = None
roomname: str, config: dict, evt: Optional[MessageEvent] = None
) -> Tuple[str, bool, bool, str]:
"""Validate and process room creation parameters.
@@ -51,7 +49,7 @@ async def prepare_room_creation_data(
sanitized_name: str,
config: dict,
client: Client,
invitees: Optional[List[str]] = None
invitees: Optional[List[str]] = None,
) -> Tuple[str, str, List[str], str]:
"""Prepare data needed for room creation.
@@ -79,7 +77,7 @@ async def prepare_power_levels(
client: Client,
config: dict,
parent_room: str,
power_level_override: Optional[PowerLevelStateEventContent] = None
power_level_override: Optional[PowerLevelStateEventContent] = None,
) -> PowerLevelStateEventContent:
"""Prepare power levels for room creation.
@@ -106,7 +104,11 @@ async def prepare_power_levels(
power_levels = PowerLevelStateEventContent()
# Copy only user power levels from parent space, not the entire permission set
if parent_power_levels and hasattr(parent_power_levels, 'users') and parent_power_levels.users:
if (
parent_power_levels
and hasattr(parent_power_levels, "users")
and parent_power_levels.users
):
try:
user_power_levels = parent_power_levels.users.copy()
# Ensure bot has highest power
@@ -150,7 +152,7 @@ def prepare_initial_state(
server: str,
force_encryption: bool,
force_unencryption: bool,
creation_content: Optional[Dict[str, Any]] = None
creation_content: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
"""Prepare initial state events for room creation.
@@ -169,51 +171,52 @@ def prepare_initial_state(
# Only add space parent state if we have a parent room
if parent_room:
initial_state.extend([
initial_state.extend(
[
{
"type": str(EventType.SPACE_PARENT),
"state_key": parent_room,
"content": {
"via": [server],
"canonical": True
}
"content": {"via": [server], "canonical": True},
},
{
"type": str(EventType.ROOM_JOIN_RULES),
"content": {
"join_rule": "restricted",
"allow": [{
"type": "m.room_membership",
"room_id": parent_room
}]
}
}
])
"allow": [
{"type": "m.room_membership", "room_id": parent_room}
],
},
},
]
)
# Add encryption if needed
if (config.get("encrypt", False) and not force_unencryption) or force_encryption:
initial_state.append({
initial_state.append(
{
"type": str(EventType.ROOM_ENCRYPTION),
"content": {
"algorithm": "m.megolm.v1.aes-sha2"
"content": {"algorithm": "m.megolm.v1.aes-sha2"},
}
})
)
# Add history visibility if specified in creation_content
if creation_content and "m.room.history_visibility" in creation_content:
initial_state.append({
initial_state.append(
{
"type": str(EventType.ROOM_HISTORY_VISIBILITY),
"content": {
"history_visibility": creation_content.get("m.room.history_visibility", "joined")
"history_visibility": creation_content.get(
"m.room.history_visibility", "joined"
)
},
}
})
)
return initial_state
def adjust_power_levels_for_modern_rooms(
power_levels: PowerLevelStateEventContent,
room_version: str
power_levels: PowerLevelStateEventContent, room_version: str
) -> PowerLevelStateEventContent:
"""Adjust power levels for modern room versions.
@@ -229,17 +232,15 @@ def adjust_power_levels_for_modern_rooms(
if room_version and int(room_version) >= 12 and power_levels:
if power_levels.users:
# Remove bot from users list but keep other important settings
power_levels.users.pop("bot_mxid", None) # Will be replaced with actual bot mxid
power_levels.users.pop(
"bot_mxid", None
) # Will be replaced with actual bot mxid
return power_levels
async def add_room_to_space(
client: Client,
parent_room: str,
room_id: str,
server: str,
sleep_duration: float
client: Client, parent_room: str, room_id: str, server: str, sleep_duration: float
) -> None:
"""Add created room to parent space.
@@ -254,20 +255,14 @@ async def add_room_to_space(
await client.send_state_event(
parent_room,
EventType.SPACE_CHILD,
{
"via": [server],
"suggested": False
},
state_key=room_id
{"via": [server], "suggested": False},
state_key=room_id,
)
await asyncio.sleep(sleep_duration)
async def verify_room_creation(
client: Client,
room_id: str,
expected_version: str,
logger
client: Client, room_id: str, expected_version: str, logger
) -> None:
"""Verify that room was created with correct settings.
@@ -279,9 +274,16 @@ async def verify_room_creation(
"""
try:
from .room_utils import get_room_version_and_creators
actual_version, actual_creators = await get_room_version_and_creators(client, room_id, logger)
logger.info(f"Room {room_id} created with version {actual_version} (requested: {expected_version})")
actual_version, actual_creators = await get_room_version_and_creators(
client, room_id, logger
)
logger.info(
f"Room {room_id} created with version {actual_version} (requested: {expected_version})"
)
if actual_version != expected_version:
logger.warning(f"Room version mismatch: requested {expected_version}, got {actual_version}")
logger.warning(
f"Room version mismatch: requested {expected_version}, got {actual_version}"
)
except Exception as e:
logger.warning(f"Could not verify room version for {room_id}: {e}")
+10 -3
View File
@@ -30,7 +30,9 @@ async def validate_room_alias(client, alias_localpart: str, server: str) -> bool
return True
async def validate_room_aliases(client, room_names: list[str], community_slug: str, server: str) -> Tuple[bool, List[str]]:
async def validate_room_aliases(
client, room_names: list[str], community_slug: str, server: str
) -> Tuple[bool, List[str]]:
"""Validate that all room aliases are available.
Args:
@@ -50,6 +52,7 @@ async def validate_room_aliases(client, room_names: list[str], community_slug: s
for room_name in room_names:
# Clean the room name and create alias
from .message_utils import sanitize_room_name
sanitized_name = sanitize_room_name(room_name)
alias_localpart = f"{sanitized_name}-{community_slug}"
@@ -61,7 +64,9 @@ async def validate_room_aliases(client, room_names: list[str], community_slug: s
return len(conflicting_aliases) == 0, conflicting_aliases
async def get_room_version_and_creators(client, room_id: str, logger=None) -> Tuple[str, List[str]]:
async def get_room_version_and_creators(
client, room_id: str, logger=None
) -> Tuple[str, List[str]]:
"""Get the room version and creators for a room.
Args:
@@ -134,7 +139,9 @@ async def user_has_unlimited_power(client, user_id: str, room_id: str) -> bool:
bool: True if user has unlimited power
"""
try:
room_version, creators = await get_room_version_and_creators(client, room_id, None)
room_version, creators = await get_room_version_and_creators(
client, room_id, None
)
# In modern room versions (12+), creators have unlimited power
if is_modern_room_version(room_version):
+25 -9
View File
@@ -42,9 +42,9 @@ async def check_if_banned(client, userid: str, banlists: List[str], logger) -> b
for rule in user_policies:
try:
if bool(
fnmatch.fnmatch(userid, rule["content"]["entity"])
) and bool(re.search("ban$", rule["content"]["recommendation"])):
if bool(fnmatch.fnmatch(userid, rule["content"]["entity"])) and bool(
re.search("ban$", rule["content"]["recommendation"])
):
return True
except Exception:
# Skip invalid rules
@@ -81,10 +81,18 @@ async def get_banlist_roomids(client, banlists: List[str], logger) -> List[str]:
return banlist_roomids
async def ban_user_from_rooms(client, user: str, roomlist: List[str], reason: str = "banned",
all_rooms: bool = False, redact_on_ban: bool = False,
get_messages_to_redact_func=None, database=None,
sleep_time: float = 0.1, logger=None) -> Dict:
async def ban_user_from_rooms(
client,
user: str,
roomlist: List[str],
reason: str = "banned",
all_rooms: bool = False,
redact_on_ban: bool = False,
get_messages_to_redact_func=None,
database=None,
sleep_time: float = 0.1,
logger=None,
) -> Dict:
"""Ban a user from a list of rooms.
Args:
@@ -149,8 +157,14 @@ async def ban_user_from_rooms(client, user: str, roomlist: List[str], reason: st
return ban_event_map
async def user_permitted(client, user_id: UserID, parent_room: str, min_level: int = 50,
room_id: str = None, logger=None) -> bool:
async def user_permitted(
client,
user_id: UserID,
parent_room: str,
min_level: int = 50,
room_id: str = None,
logger=None,
) -> bool:
"""Check if a user has sufficient power level in a room.
Args:
@@ -169,6 +183,7 @@ async def user_permitted(client, user_id: UserID, parent_room: str, min_level: i
# First check if user has unlimited power (creator in modern room versions)
from .room_utils import user_has_unlimited_power
if await user_has_unlimited_power(client, user_id, target_room):
return True
@@ -196,4 +211,5 @@ async def user_has_unlimited_power(client, user_id: str, room_id: str) -> bool:
bool: True if user has unlimited power
"""
from .room_utils import user_has_unlimited_power as room_user_has_unlimited_power
return await room_user_has_unlimited_power(client, user_id, room_id)