nostr_tools.find_ws_urls

nostr_tools.find_ws_urls(text)[source]

Find and validate all WebSocket URLs in the given text.

This function searches for valid WebSocket URLs (ws:// or wss://) in text, validates them according to RFC 3986 URI standards, and returns normalized URLs. It supports both clearnet domains and Tor .onion hidden services. All URLs are normalized to use the wss:// (secure WebSocket) scheme.

Validation includes: - WebSocket scheme (ws:// or wss://) - Valid domain name or IP address - Valid port range (0-65535) if specified - Proper .onion address format for Tor (16 or 56 char base32) - Valid TLD for clearnet domains

Parameters:

text (str) – The text to search for WebSocket relay URLs. Can contain multiple URLs mixed with other text.

Returns:

List of valid WebSocket URLs found in the text.

All URLs are normalized to use wss:// scheme and lowercase domains. Returns empty list if no valid URLs found.

Return type:

list[str]

Examples

Extract relay URLs from text:

>>> text = "Connect to wss://relay.damus.io or ws://relay.nostr.band"
>>> urls = find_ws_urls(text)
>>> print(urls)
['wss://relay.damus.io', 'wss://relay.nostr.band']

Normalize URLs to wss:

>>> text = "Use ws://relay.example.com:8080"
>>> urls = find_ws_urls(text)
>>> print(urls)
['wss://relay.example.com:8080']

Extract Tor relay:

>>> text = "Tor relay: wss://somevalidonionaddress.onion"
>>> urls = find_ws_urls(text)

Filter invalid URLs:

>>> text = "wss://relay.damus.io https://example.com ws://invalid..domain"
>>> urls = find_ws_urls(text)
>>> print(urls)
['wss://relay.damus.io']  # Only WebSocket URLs with valid format

Parse relay configuration:

>>> config_text = '''
... Primary: wss://relay.damus.io
... Backup: wss://nostr.wine
... '''
>>> relays = find_ws_urls(config_text)
>>> for url in relays:
...     relay = Relay(url)