""" Keyword Rank Tracker — checks where our domains appear in DuckDuckGo search results for a curated keyword list, records daily positions in GCS (rank_tracker.json), sends a Telegram summary with change alerts, and exposes the latest table to /analytics via latest_positions(). No paid APIs: DuckDuckGo's HTML endpoint tolerates a handful of well-paced queries from datacenter IPs (Google blocks those hard). DDG results are powered by Bing and correlate loosely with Google — good enough to watch brand-term rankings and catch SEO regressions. """ import json import os import re import time import urllib.parse import urllib.request import urllib.error from datetime import datetime, timezone, timedelta from modules.storage import load_json, save_json from modules.telegram_alert import send_telegram_message HISTORY_FILE = "rank_tracker.json" MAX_HISTORY = 90 FETCH_TIMEOUT = 30 # DuckDuckGo trips its "anomaly" bot-check after a handful of rapid # queries — pace hard (one query every ~15s keeps a daily 10-keyword run # under the anomaly threshold). PAUSE_SECONDS_DDG = 15.0 # Brave Search API free tier allows 1 query/sec. PAUSE_SECONDS_BRAVE = 1.5 # (keyword, [target domains]) — brand and discovery terms for every # site in the family. Positions are 1-based; None = not in top results. KEYWORDS = [ ("flask factory", ["flaskfactory.ai"]), ("flaskfactory", ["flaskfactory.ai"]), ("flask development service", ["flaskfactory.ai"]), ("zojax", ["zojax.com", "www.zojax.com"]), ("django zojax", ["django.zojax.com"]), ("wordpress zojax", ["wordpress.zojax.com"]), ("blind monkeys", ["blindmonkeys.org"]), ("blind monkeys crypto", ["blindmonkeys.org"]), ("crypto grid scanner", ["blindmonkeys.org"]), ("gyumri coffee", ["gyumri.coffee"]), ] _RESULT_A = re.compile( r']+class="result__a"[^>]*href="([^"]+)"|' r']+href="([^"]+)"[^>]*class="result__a"') def _now_iso(): return datetime.now(timezone.utc).isoformat(timespec="seconds") def _fetch_page(form): """POST one query page to DuckDuckGo's HTML endpoint, return URLs in order.""" data = urllib.parse.urlencode(form).encode("utf-8") req = urllib.request.Request( "https://html.duckduckgo.com/html/", data=data, headers={ "User-Agent": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/131.0.0.0 Safari/537.36"), "Content-Type": "application/x-www-form-urlencoded", "Accept": "text/html", }) with urllib.request.urlopen(req, timeout=FETCH_TIMEOUT) as resp: html = resp.read().decode("utf-8", "replace") urls = [] for m in _RESULT_A.finditer(html): href = m.group(1) or m.group(2) or "" if "uddg=" in href: qs = urllib.parse.parse_qs(urllib.parse.urlparse(href).query) url = urllib.parse.unquote(qs.get("uddg", [""])[0]) elif href.startswith("http"): url = href else: continue urls.append(url) return urls def _fetch_result_urls(query, pages=1): """Fetch up to `pages` result pages (~10 results each) in rank order.""" ordered, seen = [], set() for i in range(pages): try: page = _fetch_page({"q": query, "s": i * 30, "dc": i * 30}) except Exception: break fresh = 0 for u in page: if u not in seen: seen.add(u) ordered.append(u) fresh += 1 if not fresh: break time.sleep(1.0) return ordered def _brave_search(query, count=20): """Brave Search API (free tier: 2,000 queries/month). Returns result URLs in rank order, or None if no BRAVE_API_KEY is configured.""" key = os.environ.get("BRAVE_API_KEY", "").strip() if not key: return None req = urllib.request.Request( "https://api.search.brave.com/res/v1/web/search?" + urllib.parse.urlencode({"q": query, "count": count}), headers={"X-Subscription-Token": key, "Accept": "application/json"}) with urllib.request.urlopen(req, timeout=FETCH_TIMEOUT) as resp: data = json.loads(resp.read().decode("utf-8")) urls = [] for w in (data.get("web") or {}).get("results") or []: u = w.get("url") or "" if u.startswith("http"): urls.append(u) return urls def _find_position(urls, domain): """1-based position of the first result hosted on domain (or subdomain).""" dom = domain.lower() for i, u in enumerate(urls, 1): try: host = urllib.parse.urlparse(u).netloc.lower().split(":")[0] except Exception: continue if host == dom or host.endswith("." + dom): return i return None def latest_positions(): """Latest snapshot for the analytics API.""" history = load_json(HISTORY_FILE, default=[]) if not history: return {"checked_at": None, "keywords": []} last = history[-1] prev = history[-2] if len(history) >= 2 else None out = [] for kw, domains in KEYWORDS: cur = (last.get("results") or {}).get(kw) or {} pre = ((prev or {}).get("results") or {}).get(kw) or {} rows = [] for dom in domains: pos = cur.get(dom) old = pre.get(dom) change = None if pos is not None and old is not None: change = old - pos # positive = moved up rows.append({"domain": dom, "position": pos, "change": change}) out.append({"keyword": kw, "rows": rows}) return {"checked_at": last.get("checked_at"), "keywords": out, "error": last.get("error")} def _summary_lines(results, prev_results): """Telegram body: one line per keyword, with change markers.""" lines = [] for kw, domains in KEYWORDS: cur = results.get(kw) or {} pre = (prev_results or {}).get(kw) or {} parts = [] for dom in domains: pos = cur.get(dom) old = pre.get(dom) mark = "" if pos is not None and old is not None: if pos < old: mark = " ▲%d" % (old - pos) elif pos > old: mark = " ▼%d" % (pos - old) parts.append("%s #%s%s" % (dom, pos if pos is not None else "—", mark)) lines.append("%s: %s" % (kw, " · ".join(parts))) return lines def run_rank_check(): """Fetch current rankings, store them, alert Telegram. Returns summary.""" history = load_json(HISTORY_FILE, default=[]) prev_results = (history[-1] or {}).get("results") if history else None engine = "brave" if os.environ.get("BRAVE_API_KEY", "").strip() else "duckduckgo" pause = PAUSE_SECONDS_BRAVE if engine == "brave" else PAUSE_SECONDS_DDG results, errors = {}, [] for kw, domains in KEYWORDS: try: if engine == "brave": urls = _brave_search(kw) or [] else: urls = _fetch_result_urls(kw) results[kw] = {d: _find_position(urls, d) for d in domains} if not urls: errors.append(kw) except Exception: errors.append(kw) results[kw] = {} time.sleep(pause) entry = {"checked_at": _now_iso(), "engine": engine, "results": results, "error": ", ".join(errors) if errors else None} history.append(entry) save_json(HISTORY_FILE, history[-MAX_HISTORY:]) body = _summary_lines(results, prev_results) header = "📈 Rank Tracker (DuckDuckGo)" if errors: body.append("(no results returned for: %s)" % ", ".join(errors)) send_telegram_message("\n".join([header] + body)) ranked = sum(1 for kw in KEYWORDS for d in results.get(kw, {}).values() if d is not None) return {"ok": not errors, "keywords": len(KEYWORDS), "ranked": ranked, "errors": errors}