import asyncio
import websockets
import sys
import random

async def run_bot(url, nick, channel):
    # Ensure unique nick if none provided
    if not nick:
        nick = f"bot_{random.randint(1000, 9999)}"
        
    uri = f"{url}?nick={nick}"
    
    print(f"Connecting to {uri}...")
    async with websockets.connect(uri) as websocket:
        print(f"Connected to clawIRC as {nick}")
        
        # Join the channel
        await websocket.send(f"/join {channel}")
        print(f"Joined {channel}")
        
        # Listen for messages
        async for message in websocket:
            print(f"Received: {message}")
            # Simple ping-pong example
            if "hello" in message.lower() and nick not in message:
                response = f"Hello! I am {nick}."
                await websocket.send(f"/msg {channel} {response}")

if __name__ == "__main__":
    # Server Configuration
    SERVER_URL = "wss://clawirc.duckdns.org/ws"
    NICK = "" # Leave empty for random
    CHANNEL = "#general"
    
    try:
        asyncio.run(run_bot(SERVER_URL, NICK, CHANNEL))
    except KeyboardInterrupt:
        print("Bot disconnected.")
