#!/usr/bin/env python3 """ nostr-spam-meter — measure how much of a Nostr relay is actually human. python nostr-spam-meter.py wss://nos.lol wss://relay.primal.net It pulls the recent global feed from each relay, scores every note, and prints what fraction is automated. I wrote it because I kept trying to have a conversation on relays and kept talking to airdrop bots. Heuristics (deliberately blunt, cheap, no model calls): - known scam vocabulary / lookalike unicode / link-stuffed - burst posting: one pubkey dominating the sample - machine templates: identical prefix across many authors - payload notes: base64-ish blobs, no whitespace, no punctuation Not a moderation tool. A measurement tool. Numbers first, policy second. """ from __future__ import annotations import base64 import binascii import json import re import sys import time from collections import Counter try: import websocket except ImportError: sys.exit("pip install websocket-client") SCAM = re.compile( r"(airdrop|airdr[oо]p|claim now|free ?eth|giveaway|" r"t\.me/|\bpresale\b|connect wallet|double your)", re.I) LOOKALIKE = set("ΑΒΕΖΗΙΚΜΝΟΡΤΧΥаеорсухѕԁӀ") TEMPLATE_KEYS = ["🚀", "🪂", "🔥", "🎁", "🚨", "💰", "👀", "1 ET", "1 ETH"] def conn(url, timeout=10): kw = {"timeout": timeout, "enable_multithread": False} try: import winreg k = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion" r"\Internet Settings") if winreg.QueryValueEx(k, "ProxyEnable")[0]: s = winreg.QueryValueEx(k, "ProxyServer")[0] if "=" in s: d = dict(p.split("=", 1) for p in s.split(";") if "=" in p) s = d.get("https") or d.get("http") or s h, _, p = s.partition(":") kw.update(http_proxy_host=h, http_proxy_port=int(p or 8080), proxy_type="http") except Exception: pass return websocket.create_connection(url, **kw) def fetch(url, limit=200): try: ws = conn(url) except Exception as e: print(f" {url} unreachable ({type(e).__name__})") return [] ws.send(json.dumps(["REQ", "m", {"kinds": [1], "limit": limit}])) ws.settimeout(4) out, t0 = [], time.time() while time.time() - t0 < 14: try: m = json.loads(ws.recv()) except Exception: continue if isinstance(m, list) and m and m[0] == "EVENT": out.append(m[2]) elif isinstance(m, list) and m and m[0] == "EOSE": break try: ws.send(json.dumps(["CLOSE", "m"])) ws.close() except Exception: pass return out def looks_like_payload(c: str) -> bool: s = c.strip() if len(s) < 40 or " " in s: return False try: base64.b64decode(s + "=" * (-len(s) % 4), validate=True) return True except (binascii.Error, ValueError): return False def score(note, author_counts, template_counts): c = note["content"] reasons = [] if SCAM.search(c): reasons.append("scam-vocab") if sum(1 for ch in c if ch in LOOKALIKE) > 2: reasons.append("lookalike-unicode") if c.count("http") >= 2: reasons.append("link-stuffed") if author_counts[note["pubkey"]] > 5: reasons.append("burst-poster") key = c[:12] if template_counts[key] >= 4: reasons.append("template-clone") if looks_like_payload(c): reasons.append("payload") return reasons def main(argv): relays = argv[1:] or ["wss://nos.lol", "wss://relay.primal.net"] grand_total = grand_spam = 0 for url in relays: notes = fetch(url) if not notes: continue authors = Counter(n["pubkey"] for n in notes) templates = Counter(n["content"][:12] for n in notes) flagged, histogram = 0, Counter() for n in notes: r = score(n, authors, templates) if r: flagged += 1 for x in r: histogram[x] += 1 pct = 100 * flagged / len(notes) grand_total += len(notes) grand_spam += flagged print(f"\n{url}") print(f" notes sampled : {len(notes)}") print(f" unique authors: {len(authors)}") print(f" scored spam : {flagged} ({pct:.1f}%)") print(f" top reasons : {', '.join(f'{k}={v}' for k, v in histogram.most_common(5))}") if grand_total: print(f"\nTOTAL: {grand_spam}/{grand_total} = {100*grand_spam/grand_total:.1f}% automated") return 0 if __name__ == "__main__": sys.exit(main(sys.argv))