"""Counts, from the web server's own log, who finds BitAddy without a browser script being able to see it: search engines, AI crawlers, AI assistants opening a page for someone, link previews made by chat apps, and how many people arrive from an AI assistant, a search engine or a social site. Only COUNTS are written (per day: a name like "GPTBot", a kind of page, a referring site like "ChatGPT"). Never an IP address, never the name of anyone's page or link. Runs on the server every half hour, reads only the lines added since last time. python3 ba_logcount.py --log /var/log/nginx/bitaddy.access.log --out /var/lib/side-console/bitaddy.com/ai-visits.json [--owner user] """ import json, os, re, sys, time from datetime import datetime, timedelta, timezone KEEP_DAYS = 400 # name inside the User-Agent -> (kind, who, what it is). Kinds: live = opening a page for a person right now; answers = AI search; # learn = collecting pages for AI models; search = ordinary search engines; share = a link preview after someone pasted a link. AGENTS = { "ChatGPT-User": ("live", "OpenAI", "ChatGPT opening a page for someone"), "Claude-User": ("live", "Anthropic", "Claude opening a page for someone"), "Perplexity-User": ("live", "Perplexity", "Perplexity opening a page for someone"), "MistralAI-User": ("live", "Mistral", "Le Chat opening a page for someone"), "meta-externalfetcher": ("live", "Meta", "Meta AI opening a page for someone"), "DuckAssistBot": ("live", "DuckDuckGo", "DuckDuckGo AI answers"), "Gemini-Deep-Research": ("live", "Google", "Gemini researching for someone"), "OAI-SearchBot": ("answers", "OpenAI", "ChatGPT search"), "Claude-SearchBot": ("answers", "Anthropic", "Claude search"), "PerplexityBot": ("answers", "Perplexity", "Perplexity search"), "meta-webindexer": ("answers", "Meta", "Meta AI search"), "YouBot": ("answers", "You.com", "You.com search"), "GPTBot": ("learn", "OpenAI", "collects pages for OpenAI models"), "ClaudeBot": ("learn", "Anthropic", "collects pages for Claude"), "anthropic-ai": ("learn", "Anthropic", "collects pages for Claude"), "meta-externalagent": ("learn", "Meta", "collects pages for Meta AI"), "Amazonbot": ("learn", "Amazon", "Alexa and Amazon AI"), "Bytespider": ("learn", "ByteDance", "collects pages for ByteDance AI"), "CCBot": ("learn", "Common Crawl", "open web archive many AI models learn from"), "PetalBot": ("learn", "Huawei", "Petal search and AI"), "Diffbot": ("learn", "Diffbot", "reads pages into a knowledge base"), "cohere-ai": ("learn", "Cohere", "collects pages for Cohere models"), "AI2Bot": ("learn", "Allen AI", "research crawler"), "Timpibot": ("learn", "Timpi", "search index"), "ImagesiftBot": ("learn", "Hive", "image crawler"), "Googlebot": ("search", "Google", "Google Search (also feeds Gemini answers)"), "GoogleOther": ("search", "Google", "other Google crawling"), "bingbot": ("search", "Microsoft", "Bing (also feeds Copilot)"), "Applebot": ("search", "Apple", "Siri and Spotlight"), "DuckDuckBot": ("search", "DuckDuckGo", "DuckDuckGo search"), "YandexBot": ("search", "Yandex", "Yandex search"), "Baiduspider": ("search", "Baidu", "Baidu search"), "Bravebot": ("search", "Brave", "Brave Search"), "Twitterbot": ("share", "X", "link preview on X"), "facebookexternalhit": ("share", "Meta", "link preview on Facebook, Instagram or Messenger"), "TelegramBot": ("share", "Telegram", "link preview in Telegram"), "Discordbot": ("share", "Discord", "link preview in Discord"), "Slackbot": ("share", "Slack", "link preview in Slack"), "WhatsApp": ("share", "WhatsApp", "link preview in WhatsApp"), "LinkedInBot": ("share", "LinkedIn", "link preview on LinkedIn"), "redditbot": ("share", "Reddit", "link preview on Reddit"), "Mastodon": ("share", "Mastodon", "link preview on Mastodon"), "Bluesky": ("share", "Bluesky", "link preview on Bluesky"), "SkypeUriPreview": ("share", "Microsoft", "link preview in Skype or Teams"), "Iframely": ("share", "Iframely", "link preview service"), } KINDS = {"live": "AI assistants opening a page for a person", "answers": "AI search and answer engines", "learn": "Collecting pages for AI models", "search": "Search engines", "share": "Link previews (someone pasted a link in a chat or post)"} # the site a person came from -> (kind, name) AI_REF = {"chatgpt.com": "ChatGPT", "chat.openai.com": "ChatGPT", "perplexity.ai": "Perplexity", "claude.ai": "Claude", "gemini.google.com": "Gemini", "bard.google.com": "Gemini", "copilot.microsoft.com": "Copilot", "copilot.cloud.microsoft": "Copilot", "chat.deepseek.com": "DeepSeek", "grok.com": "Grok", "you.com": "You.com", "chat.mistral.ai": "Le Chat", "meta.ai": "Meta AI", "duck.ai": "Duck.ai", "phind.com": "Phind", "poe.com": "Poe", "chat.qwen.ai": "Qwen", "kimi.com": "Kimi", "kimi.moonshot.cn": "Kimi"} AI_UTM = {"chatgpt.com": "ChatGPT", "chatgpt": "ChatGPT", "openai": "ChatGPT", "perplexity": "Perplexity", "perplexity.ai": "Perplexity", "claude.ai": "Claude", "claude": "Claude", "copilot.com": "Copilot", "copilot": "Copilot", "gemini": "Gemini", "grok": "Grok", "grok.com": "Grok"} SEARCH_REF = (("google.", "Google"), ("bing.com", "Bing"), ("duckduckgo.com", "DuckDuckGo"), ("search.brave.com", "Brave Search"), ("yandex.", "Yandex"), ("baidu.com", "Baidu"), ("ecosia.org", "Ecosia"), ("startpage.com", "Startpage"), ("search.yahoo.com", "Yahoo"), ("kagi.com", "Kagi"), ("qwant.com", "Qwant")) SOCIAL_REF = (("t.co", "X"), ("x.com", "X"), ("twitter.com", "X"), ("reddit.com", "Reddit"), ("facebook.com", "Facebook"), ("instagram.com", "Instagram"), ("t.me", "Telegram"), ("telegram.org", "Telegram"), ("youtube.com", "YouTube"), ("linkedin.com", "LinkedIn"), ("discord.com", "Discord"), ("tiktok.com", "TikTok"), ("threads.net", "Threads"), ("threads.com", "Threads"), ("bsky.app", "Bluesky"), ("github.com", "GitHub")) OTHER_BOT = re.compile(r"bot\b|bot/|crawl|spider|slurp|headless|preview|fetch|monitor|curl|wget|python|scrapy|lighthouse|go-http|okhttp|java/|libwww|" r"httpclient|axios|node-fetch|undici|scan|check|zgrab|nmap|masscan|censys|semrush|ahrefs|mj12|dotbot|dataforseo", re.I) LINE = re.compile(r'^\S+ \S+ \S+ \[([^\]]+)\] "([A-Z]+) (\S+)[^"]*" (\d{3}) \S+ "([^"]*)" "([^"]*)"') KEY_FILES = {"/llms.txt": "llms.txt", "/robots.txt": "robots.txt", "/sitemap.xml": "sitemap.xml", "/openapi.json": "openapi.json", "/api/v1/openapi.json": "openapi.json", "/.well-known/mcp.json": "MCP card", "/.well-known/mcp/server-card.json": "MCP card", "/agents/": "For AI agents page", "/agents": "For AI agents page"} SITE_PAGES = {"/": "Home", "/pricing/": "Free & paid", "/topup/": "Top up", "/edit/": "My links", "/wallets/": "Need a wallet?", "/tip/": "Tip", "/source/": "Source code", "/privacy/": "Privacy", "/terms/": "Terms", "/agents/": "For AI agents"} MONTHS = {m: i + 1 for i, m in enumerate("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split())} def day_of(stamp): """'03/Dec/2026:01:45:12 +0100' -> '2026-12-03' in UTC.""" try: d, mon, rest = stamp.split("/", 2) y, hh, mm, ss = rest[:4], rest[5:7], rest[8:10], rest[11:13] off = rest[14:19] t = datetime(int(y), MONTHS[mon], int(d), int(hh), int(mm), int(ss), tzinfo=timezone.utc) if off and off[0] in "+-" and off[1:].isdigit(): delta = timedelta(hours=int(off[1:3]), minutes=int(off[3:5])) t = t - delta if off[0] == "+" else t + delta return t.strftime("%Y-%m-%d") except Exception: return None def agent_of(ua): """The known agent named first in the User-Agent (Telegram's says "TelegramBot (like TwitterBot)": that is Telegram, not X).""" low = ua.lower() best = None for name in AGENTS: i = low.find(name.lower()) if i >= 0 and (best is None or i < best[0]): best = (i, name) return best[1] if best else None def host_of(ref): m = re.match(r"^[a-z]+://([^/:?#]+)", ref or "", re.I) h = m.group(1).lower() if m else "" return h[4:] if h.startswith("www.") else h def came_from(ref, query): """-> (kind, name) for a person arriving from an AI assistant, a search engine or a social site; else None.""" host = host_of(ref) m = re.search(r"(?:^|&)utm_source=([^&]+)", query or "") if m and m.group(1).lower() in AI_UTM: return "ai", AI_UTM[m.group(1).lower()] if not host: return None for h, name in AI_REF.items(): if host == h or host.endswith("." + h): return "ai", name for needle, name in SEARCH_REF: if host == needle or host.endswith("." + needle) or (needle.endswith(".") and (host.startswith(needle) or ("." + needle) in host)): return "search", name for h, name in SOCIAL_REF: if host == h or host.endswith("." + h): return "social", name return None def page_kind(path): """A short, safe label for what was asked for. Never the name of someone's page or link.""" if path in KEY_FILES: return KEY_FILES[path] if path in SITE_PAGES: return SITE_PAGES[path] if path == "/mcp" or path.startswith("/api/"): return "API or MCP" if path.startswith(("/_b/", "/_c/")) or re.search(r"\.(js|css|png|jpg|jpeg|webp|svg|ico|woff2?|txt|xml|json|map)$", path): return None # the site's own files: not a visit if path.startswith("/source/"): return "Source code" if re.fullmatch(r"/[A-Za-z0-9-]{3,30}/?", path): return "Someone's page or link" return "Something else" def count_line(line, days): m = LINE.match(line) if not m: return stamp, method, target, status, ref, ua = m.groups() day = day_of(stamp) if not day: return path, _, query = target.partition("?") d = days.setdefault(day, {}) agent = agent_of(ua) if agent: b = d.setdefault("bots", {}) b[agent] = b.get(agent, 0) + 1 kind = page_kind(path) if kind: w = d.setdefault("read", {}).setdefault(AGENTS[agent][0], {}) w[kind] = w.get(kind, 0) + 1 if path in KEY_FILES: f = d.setdefault("files", {}).setdefault(KEY_FILES[path], {}) f[agent] = f.get(agent, 0) + 1 if status == "404": x = d.setdefault("dead", {}) x[agent] = x.get(agent, 0) + 1 return if method != "GET" or status not in ("200", "304") or not ua or ua == "-" or OTHER_BOT.search(ua): return kind = page_kind(path) if not kind or kind in ("API or MCP",) or path in ("/llms.txt", "/robots.txt", "/sitemap.xml", "/openapi.json"): return src = came_from(ref, query) if src: s = d.setdefault("sent", {}).setdefault(src[0], {}) s[src[1]] = s.get(src[1], 0) + 1 if kind == "Someone's page or link": t = d.setdefault("sent_to_pages", {}) t[src[0]] = t.get(src[0], 0) + 1 def read_new(path, inode, offset, days): """Counts the lines of `path` from `offset` (when it is still the file with `inode`), else from the start. -> (inode, new offset).""" try: st = os.stat(path) except OSError: return inode, offset start = offset if (st.st_ino == inode and st.st_size >= offset) else 0 with open(path, "rb") as f: f.seek(start) data = f.read() end = start + len(data) if data and not data.endswith(b"\n"): # a line still being written: leave it for next time cut = data.rfind(b"\n") + 1 end = start + cut data = data[:cut] for line in data.decode("utf-8", "replace").splitlines(): count_line(line, days) return st.st_ino, end def run(log, out, owner=None): try: with open(out) as f: data = json.load(f) except Exception: data = {} days, state = data.get("days") or {}, data.get("state") or {} inode, offset = state.get("inode"), int(state.get("offset") or 0) try: cur = os.stat(log).st_ino except OSError: cur = None if inode and cur and cur != inode: # the log was rotated: finish the old file first (it is now .1) try: if os.stat(log + ".1").st_ino == inode: read_new(log + ".1", inode, offset, days) except OSError: pass offset = 0 inode, offset = read_new(log, cur, offset if cur == inode else 0, days) cut = (datetime.now(timezone.utc) - timedelta(days=KEEP_DAYS)).strftime("%Y-%m-%d") days = {k: v for k, v in days.items() if k >= cut} tmp = out + ".tmp" with open(tmp, "w") as f: json.dump({"updated": int(time.time()), "state": {"inode": inode, "offset": offset}, "days": days}, f, separators=(",", ":")) os.chmod(tmp, 0o640) if owner: import pwd p = pwd.getpwnam(owner) os.chown(tmp, p.pw_uid, p.pw_gid) os.replace(tmp, out) if __name__ == "__main__": a = sys.argv[1:] opt = {a[i]: a[i + 1] for i in range(0, len(a) - 1, 2)} if "--log" not in opt or "--out" not in opt: sys.exit(__doc__) run(opt["--log"], opt["--out"], opt.get("--owner"))