#!/usr/bin/env python3 # /// script # requires-python = ">=3.11" # dependencies = ["apify-client>=3.3,<4"] # /// """Post the new episodes of the podcasts you follow to Slack, with audio links. Runs agentsgearbox/apple-podcasts-scraper on Apify. The actor remembers the newest episode date per show in a key-value store in your Apify account, so each run returns only episodes it has not returned before and this script keeps no state. Schedule it once a morning. 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 defaultdict from datetime import timedelta from decimal import Decimal from apify_client import ApifyClient ACTOR = "agentsgearbox/apple-podcasts-scraper" RUN_INPUT = { "podcasts": [ # Apple IDs or Apple Podcasts URLs of the shows you follow "1434243584", # Lex Fridman Podcast "https://podcasts.apple.com/us/podcast/the-daily/id1200361736", "1406537385", # Practical AI ], "countries": ["us"], "includeEpisodes": True, "episodeSource": "apple", # latest 200 per show in one request "maxEpisodesPerPodcast": 10, "episodesAfter": "7d", # first run or lost checkpoint: reach back a week at most "includeReviews": False, "onlyNewSinceLastRun": True, "checkpointStoreName": "podcast-digest-shows", # one store per digest } MAX_CHARGE_USD = Decimal("0.50") # hard cap per run; a normal morning costs under a cent SHOWN = 4 # episodes listed per show; the rest are counted and linked 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 build_messages(run, rows): """Turns dataset rows into Slack Block Kit messages; [] when there is nothing new.""" shows, problems, episodes = {}, [], defaultdict(list) for row in rows: if row.get("type") == "podcast": shows[row["id"]] = row elif row.get("type") == "episode": episodes[row["podcastId"]].append(row) elif row.get("type") == "summary": problems += summary_problems(row) elif row.get("type") == "error": problems.append(f"{row.get('target')}: {row['error']}") total = sum(len(group) for group in episodes.values()) if not total and not problems: return [] hours = sum(e.get("durationSeconds") or 0 for g in episodes.values() for e in g) / 3600 noun = "episode" if total == 1 else "episodes" headline = f"{total} new {noun}" + (f", {hours:.1f} hours of listening" if hours >= 0.5 else "") header = [ {"type": "header", "text": {"type": "plain_text", "text": headline}}, context(f"Since the last digest · <{run_url(run)}|Apify run>"), ] newest_first = sorted(episodes.items(), key=lambda item: max(e.get("releaseDate") or "" for e in item[1]), reverse=True) sections = [show_blocks(shows.get(key, {}), group, run) for key, group in newest_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=headline) def summary_problems(s): if s.get("stoppedBy") == "chargeLimit": yield f"{s.get('target')}: stopped at the ${MAX_CHARGE_USD} cap; raise MAX_CHARGE_USD" if s.get("status") == "ERROR": yield f"{s.get('target')}: lookup failed" for p in s.get("podcasts") or []: if p.get("note"): yield f"{p.get('name')}: {p['note']}" def show_blocks(show, group, run): name = esc(show.get("name") or group[0].get("podcastName") or "?") title = f"*{name}*" if show.get("publisher"): title += f" · {esc(show['publisher'])}" blocks = [section(title)] ordered = sorted(group, key=lambda e: e.get("releaseDate") or "", reverse=True) blocks += [section(episode_text(e)) for e in ordered[:SHOWN]] if len(group) > SHOWN: dataset = f"{CONSOLE}/storage/datasets/{run.default_dataset_id}" blocks.append(context(f"+{len(group) - SHOWN} more in the <{dataset}|run's dataset>")) return blocks def episode_text(e): """Title, when, how long, where to listen; the first sentence of the description as a quote.""" head = f"🎧 *{esc(clip(e.get('title') or '?', 110))}*" facts = [] if e.get("releaseDate"): facts.append(e["releaseDate"][:10]) if e.get("durationSeconds"): m = round(e["durationSeconds"] / 60) facts.append(f"{m // 60} h {m % 60:02d} min" if m >= 60 else f"{m} min") links = [f"<{e['url']}|Apple>"] if e.get("url") else [] if e.get("audioUrl"): links.append(f"<{e['audioUrl']}|audio {esc(e.get('fileType') or '')}>".replace(" >", ">")) line = head + "\n" + " · ".join(facts + links) first = (e.get("description") or "").strip().split("\n")[0] if first: line += f"\n>{esc(clip(first, 220))}" return line def pack(header, sections, fallback, limit=50): """Slack takes at most 50 blocks per message: split between shows, 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 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)) messages = build_messages(run, rows) print(f"run {run.id}: {len(rows)} rows, {len(messages)} message(s)", file=sys.stderr) if dry_run: print(json.dumps(messages, indent=2, ensure_ascii=False)) return for message in messages: try: post(webhook, message) except RuntimeError as e: sys.exit(f"{e}\nNothing was skipped: REPLAY_RUN_ID={run.id} uv run episodes_digest.py") if __name__ == "__main__": main()