#!/usr/bin/env python3 # /// script # requires-python = ">=3.11" # dependencies = ["apify-client>=3.3,<4"] # /// """Post the new remote jobs that match your profile to Slack, every morning. Runs agentsgearbox/remote-jobs-scraper on Apify. The actor reads six remote job boards and the Hacker News "Who is hiring?" thread, applies your filters before charging, removes cross-board duplicates and remembers the job IDs it already delivered in a key-value store in your Apify account, so each run returns only jobs you have not seen and this script keeps no state. 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/remote-jobs-scraper" # Your profile. Every filter is applied inside the actor, before anything is charged. RUN_INPUT = { "keywords": ["python", "typescript", "backend"], # in the title or tags; [] = all "excludeKeywords": ["intern", "junior", "unpaid"], "categories": ["engineering", "devops", "data"], # see the actor's input for the list "locations": ["Worldwide", "Europe", "Germany"], # regions the job is open to "minSalary": 60000, # annual, posting's currency; no stated salary still passes "postedAfter": "7d", # first run or lost checkpoint: reach back a week at most "maxJobs": 200, "includeDescription": False, # title, company, regions, salary, link: enough "onlyNewSinceLastRun": True, "checkpointStoreName": "remote-jobs-digest", # one store per profile } MAX_CHARGE_USD = Decimal("0.50") # hard cap per run; a normal morning costs a few cents SHOWN = 8 # jobs listed per category; the rest are counted and linked CONSOLE = "https://console.apify.com" CATEGORY_NAMES = { "engineering": "Engineering", "devops": "DevOps", "data": "Data and AI", "security": "Security", "design": "Design", "product": "Product", "customer-support": "Support", "marketing": "Marketing", "sales": "Sales", "finance": "Finance", "hr": "HR", "legal": "Legal", "writing": "Writing", "education": "Education", "healthcare": "Healthcare", "operations": "Operations", "management": "Management", "other": "Other", } 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.""" boards, problems, jobs = [], [], defaultdict(list) for row in rows: if row.get("type") == "board": boards.append(row) problems += board_problems(row) elif row.get("type") == "error": problems.append(f"{row.get('boardName') or row.get('board')}: {row['error']}") elif row.get("jobId"): jobs[row.get("category") or "other"].append(row) total = sum(len(group) for group in jobs.values()) if not total and not problems: return [] with_pay = sum(1 for group in jobs.values() for job in group if job.get("salaryText")) noun = "job" if total == 1 else "jobs" headline = f"{total} new remote {noun} for your profile" if with_pay: headline += f", {with_pay} with a stated salary" read = sum(b.get("jobsFetched") or 0 for b in boards) header = [ {"type": "header", "text": {"type": "plain_text", "text": headline}}, context(f"Since the last check · {read:,} listings read on {len(boards)} boards" f" · <{run_url(run)}|Apify run>"), ] biggest_first = sorted(jobs.items(), key=lambda item: -len(item[1])) sections = [category_blocks(cat, group, run) for cat, group in biggest_first] if problems: # a context block holds at most 10 elements unique = list(dict.fromkeys(problems)) # a board error is reported once notes = [mrkdwn("⚠️ " + esc(clip(p, 280))) for p in unique[:10]] sections.append([{"type": "context", "elements": notes}]) return pack(header, sections, fallback=headline) def board_problems(b): who = b.get("boardName") or b["board"] if b.get("stoppedBy") == "chargeLimit": yield f"{who}: stopped at the ${MAX_CHARGE_USD} cap; raise MAX_CHARGE_USD" if b.get("status") == "ERROR": yield f"{who}: {b.get('note') or 'could not be read'}" def category_blocks(category, group, run): """One section per category: jobs with a stated salary first, then newest first.""" name = CATEGORY_NAMES.get(category, category.title()) blocks = [section(f"*{esc(name)}* · {len(group)} new")] paid = sorted([j for j in group if j.get("salaryText")], key=lambda j: j.get("salaryAnnualMax") or j.get("salaryAnnualMin") or 0, reverse=True) rest = sorted([j for j in group if not j.get("salaryText")], key=lambda j: j.get("postedAt") or "", reverse=True) blocks += [section(job_line(job)) for job in (paid + rest)[:SHOWN]] if len(group) > SHOWN: dataset = f"{CONSOLE}/storage/datasets/{run.default_dataset_id}" more = len(group) - SHOWN blocks.append(context(f"+{more} more in the <{dataset}|run's dataset>")) return blocks def job_line(job): """One job per line: title, company, regions, pay, type, link; board named below.""" mark = "💰 " if job.get("salaryText") else "• " parts = [f"{mark}*{esc(clip(job.get('title') or '?', 90))}*", esc(clip(job.get("company") or "?", 50))] regions = job.get("regions") or [] if job.get("worldwide"): where = "Worldwide" elif len(regions) > 3: where = f"{regions[0]}, {regions[1]} +{len(regions) - 2} more" else: where = ", ".join(regions) if regions else (job.get("location") or None) for value in (where, job.get("salaryText"), job.get("employmentType")): if value: parts.append(esc(clip(value, 60))) line = " · ".join(parts) if job.get("url"): line += f" · <{job['url']}|open>" board = job.get("boardName") or job.get("board") or "?" via = f"via {esc(board)}" # the boards ask to be named next to the link also = [a.get("boardName") for a in job.get("alsoOn") or [] if a.get("boardName")] if also: via += f", also on {esc(', '.join(also[:3]))}" posted = f"posted {job['postedAt'][:10]} · " if job.get("postedAt") else "" return line + f"\n_{posted}{via}_" def pack(header, sections, fallback, limit=50): """Slack takes at most 50 blocks per message: split between categories, not 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: " f"REPLAY_RUN_ID={run.id} uv run remote_jobs_digest.py") if __name__ == "__main__": main()