#!/usr/bin/env python3 # /// script # requires-python = ">=3.11" # dependencies = ["apify-client>=3.3,<4"] # /// """Post new 1- and 2-star App Store and Google Play reviews to Slack. Runs agentsgearbox/app-store-reviews-scraper on Apify. The actor keeps a checkpoint per app, store and country in a key-value store in your Apify account, so each run returns only reviews it has not returned before and this script keeps no state. Schedule it once a day. Environment: APIFY_TOKEN Apify API token (Console > Settings > API & Integrations) SLACK_WEBHOOK_URL Slack incoming webhook DRY_RUN=1 print the Slack messages instead of posting them REPLAY_RUN_ID=... format an earlier run again instead of starting a new one """ import json import os import sys import time import urllib.error import urllib.request from collections import Counter, defaultdict from datetime import timedelta from decimal import Decimal from apify_client import ApifyClient ACTOR = "agentsgearbox/app-store-reviews-scraper" RUN_INPUT = { "apps": [ "https://apps.apple.com/us/app/whatsapp-messenger/id310633997", # App Store "com.whatsapp", # Google Play: package name or store URL ], "countries": ["us", "gb"], # App Store storefronts to watch "language": "en", # Google Play reviews come by language, not by storefront "minScore": 1, "maxScore": 2, "onlyNewSinceLastRun": True, "checkpointStoreName": "review-digest-whatsapp", # one store per digest "reviewedAfter": "3d", # first run or lost checkpoint: reach back 3 days at most "maxReviewsPerApp": 200, "includeAppDetails": True, # one record per app and storefront: rating, version } MAX_CHARGE_USD = Decimal("0.50") # hard cap per run; a normal day costs under a cent QUOTED = 5 # reviews quoted per group; the rest are counted and linked STORES = {"app-store": "App Store", "google-play": "Google Play"} CONSOLE = "https://console.apify.com" def fetch(client): """Starts the actor and waits, or loads an earlier run. Returns run and rows.""" replay = os.environ.get("REPLAY_RUN_ID") if replay: run = client.run(replay).get() else: run = client.actor(ACTOR).call( run_input=RUN_INPUT, max_total_charge_usd=MAX_CHARGE_USD, run_timeout=timedelta(minutes=15), ) if run is None: sys.exit(f"Run {replay} not found") if run.status != "SUCCEEDED": sys.exit(f"Actor run ended {run.status}: {run_url(run)}") return run, list(client.dataset(run.default_dataset_id).iterate_items(clean=True)) def run_url(run): return f"{CONSOLE}/actors/{run.act_id}/runs/{run.id}" def scope(row): """App Store reviews differ per storefront. Google Play serves the same reviews to every storefront of a language, so a Play app gets one group per language.""" if row.get("store") == "google-play": return "google-play", row.get("appId"), RUN_INPUT["language"] return row.get("store"), row.get("appId"), row.get("country") def build_messages(run, rows): """Turns dataset rows into Slack Block Kit messages; [] when there is nothing new.""" apps, summaries, problems, groups, seen = {}, {}, [], defaultdict(list), set() for row in rows: if row["type"] == "app": apps.setdefault(scope(row), row) elif row["type"] == "summary": summaries.setdefault(scope(row), row) problems += summary_problems(row) elif row["type"] == "error": store = STORES.get(row.get("store"), "Input") problems.append(f"{store} {row.get('appId')} ({row.get('country') or '-'}): " f"{row['error']}") elif row["type"] == "review" and (row["store"], row["reviewId"]) not in seen: seen.add((row["store"], row["reviewId"])) # Play repeats it per storefront groups[scope(row)].append(row) total = sum(len(reviews) for reviews in groups.values()) if not total and not problems: return [] noun = "review" if total == 1 else "reviews" header = [ {"type": "header", "text": {"type": "plain_text", "text": f"{total} new 1–2★ {noun}"}}, context(f"Since the last digest · <{run_url(run)}|Apify run>"), ] busiest_first = sorted(groups.items(), key=lambda item: -len(item[1])) sections = [group_blocks(key, reviews, apps.get(key, {}), summaries.get(key, {}), run) for key, reviews in busiest_first] if problems: # a context block holds at most 10 elements notes = [mrkdwn("⚠️ " + esc(clip(p, 280))) for p in problems[:10]] sections.append([{"type": "context", "elements": notes}]) return pack(header, sections, fallback=f"{total} new 1–2★ app {noun}") def summary_problems(s): where = f"{STORES.get(s['store'], s['store'])} {s['appId']} ({s['country']})" if s.get("stoppedBy") == "chargeLimit": yield f"{where}: stopped at the ${MAX_CHARGE_USD} cap; raise MAX_CHARGE_USD" if s.get("stoppedBy") == "scanLimit": yield f"{where}: scan limit reached before the checkpoint; run more often" if s.get("stuckPages"): pages = ", ".join(map(str, s["stuckPages"])) yield f"{where}: Apple's feed skipped page(s) {pages}" def group_blocks(key, reviews, app, summary, run): store, app_id, where = key place = f"{flag(where)} {where.upper()}" if store == "app-store" else f"· {where}" title = f"*{esc(app.get('title') or app_id)}* · {STORES[store]} {place}" if app.get("score"): title += f" · ★ {app['score']:.2f}" if app.get("version"): title += f" · v{esc(app['version'])}" facts = [f"{len(reviews)} new"] low, other = summary.get("reviewsScraped", 0), summary.get("reviewsFilteredOut", 0) if low + other: facts.append(f"{round(100 * low / (low + other))}% of all new reviews are 1–2★") versions = Counter(r["appVersion"] for r in reviews if r.get("appVersion")) if versions and versions.most_common(1)[0][1] > 1: version, count = versions.most_common(1)[0] facts.append(f"{count} on v{esc(version)}") blocks = [section(title), context(" · ".join(facts))] blocks += [section(review_text(r)) for r in reviews[:QUOTED]] if len(reviews) > QUOTED: dataset = f"{CONSOLE}/storage/datasets/{run.default_dataset_id}" more = len(reviews) - QUOTED blocks.append(context(f"+{more} more in the <{dataset}|run's dataset>")) return blocks def review_text(r): score = int(r.get("score") or 0) head = "★" * score + "☆" * (5 - score) if r.get("title"): head += f" *{esc(clip(r['title'], 120))}*" if r.get("appVersion"): head += f" · v{esc(r['appVersion'])}" head += f" · <{r['url']}|open>" body = clip((r.get("text") or "").strip(), 400) quote = "\n".join(f">{esc(line)}" for line in body.splitlines() if line.strip()) return f"{head}\n{quote}" if quote else head def pack(header, sections, fallback, limit=50): """Slack takes at most 50 blocks per message: split between groups, never inside.""" messages, blocks = [], list(header) for part in sections: if len(blocks) + len(part) > limit: messages.append(blocks) blocks = [] blocks += part messages.append(blocks) return [{"text": fallback, "blocks": b} for b in messages] def post(webhook, message): """Posts one message. Retries rate limits, server errors and network failures.""" data = json.dumps(message).encode() for attempt in range(4): request = urllib.request.Request( webhook, data=data, headers={"Content-Type": "application/json"} ) try: with urllib.request.urlopen(request, timeout=30): return except urllib.error.HTTPError as e: if (e.code != 429 and e.code < 500) or attempt == 3: reason = e.read().decode()[:200] raise RuntimeError(f"Slack answered HTTP {e.code}: {reason}") from None time.sleep(int(e.headers.get("Retry-After") or 2**attempt)) except urllib.error.URLError as e: if attempt == 3: raise RuntimeError(f"Slack unreachable: {e.reason}") from None time.sleep(2**attempt) def section(text): return {"type": "section", "text": mrkdwn(text)} def context(text): return {"type": "context", "elements": [mrkdwn(text)]} def mrkdwn(text): return {"type": "mrkdwn", "text": text} def esc(text): return str(text).replace("&", "&").replace("<", "<").replace(">", ">") def clip(text, limit): return text if len(text) <= limit else text[:limit].rsplit(" ", 1)[0] + " …" def flag(country): if len(country or "") != 2: return "" return "".join(chr(0x1F1E6 + ord(c) - ord("a")) for c in country) def main(): token, webhook, dry_run = (os.environ.get(k) for k in ("APIFY_TOKEN", "SLACK_WEBHOOK_URL", "DRY_RUN")) if not token or not (webhook or dry_run): # checked before paying for a run sys.exit("Set APIFY_TOKEN and SLACK_WEBHOOK_URL (or DRY_RUN=1) first.") run, rows = fetch(ApifyClient(token)) print(f"Apify run {run.id}: {len(rows)} rows", file=sys.stderr) # for REPLAY_RUN_ID messages = build_messages(run, rows) if not messages: print("No new 1-2 star reviews since the last run.") return if dry_run: print(json.dumps(messages, ensure_ascii=False, indent=2)) return try: for message in messages: post(webhook, message) except RuntimeError as e: sys.exit(f"{e}\nNothing is lost: rerun with REPLAY_RUN_ID={run.id} " "once Slack accepts messages again.") print(f"Posted {len(messages)} message(s) from run {run.id}.") if __name__ == "__main__": main()