some-project-4aeu9v/helpers/message_helpers.py
2025-03-27 16:05:50 +00:00

76 lines
1.8 KiB
Python

from typing import Dict, Optional, Union
from pydantic import BaseModel, ValidationError
from datetime import datetime
def validate_message_text(text: str) -> bool:
"""
Validate message text is not empty and within length limits.
Args:
text: The message text to validate
Returns:
bool: True if text is valid, False otherwise
"""
if not text or len(text.strip()) == 0:
return False
if len(text) > 1000: # Max length validation
return False
return True
def format_message_response(text: str) -> Dict[str, str]:
"""
Format message text into standard response format.
Args:
text: Message text to format
Returns:
Dict containing formatted message response
"""
return {
"message": text,
"timestamp": datetime.utcnow().isoformat()
}
def sanitize_message_text(text: str) -> str:
"""
Sanitize message text by removing extra whitespace and special characters.
Args:
text: Text to sanitize
Returns:
Sanitized text string
"""
# Remove extra whitespace
text = " ".join(text.split())
# Remove special characters if needed
text = text.strip()
return text
def create_message_safely(text: str) -> Union[Dict[str, str], Dict[str, str]]:
"""
Create a new message with validation and error handling.
Args:
text: Message text
Returns:
Success response dict or error dict
"""
if not validate_message_text(text):
return {"error": "Invalid message text"}
sanitized_text = sanitize_message_text(text)
return format_message_response(sanitized_text)
def get_default_message() -> str:
"""
Get the default message text.
Returns:
Default message string
"""
return "let's goo"