import asyncio import random async def natural_send_message(text, send, start_typing, stop_typing, skip_thinking=False ): """ Parses and sends messages with natural delays based on message length. Args: chat_session: The active chat session. ts: Timestamp of the message. c: The context or object with `.send()`, `.start_typing()`, and `.stop_typing()` methods. text: A string containing multiple messages separated by double newlines (`\n\n`). Behavior: - Short messages are sent quickly with minimal delay. - Longer messages include a "thinking" pause before typing. - Typing indicator (`c.start_typing() / c.stop_typing()`) is used dynamically. """ parts = text.split("\n\n") # Split into separate messages ids = [] for index, message in enumerate(parts): message = message.strip() if not message: continue # Compute natural "thinking" delay based on message length base_delay = 0.8 # Minimum delay length_factor = len(message) / 25 # ~50 chars ≈ +1s processing # ~25 chars ≈ +1s processing natural_delay = min(base_delay + length_factor, 10) # Cap at 5s max # Decide when to start thinking *before* typing if not skip_thinking: if natural_delay > 3.5: # Only delay if response is long await asyncio.sleep(natural_delay - 3.5) # "Thinking" pause before typing # Start typing await start_typing() await asyncio.sleep(natural_delay) # Finish remaining delay await stop_typing() # Send the message result = await send(message) ids.append(result) # Optional: Small buffer between messages to prevent rapid-fire responses await asyncio.sleep(0.5) return ids