#!/usr/bin/env python3 # /// script # requires-python = ">=3.11" # dependencies = ["apify-client>=3.3,<4"] # /// """Post new job openings at your target accounts to Slack, leadership hires first. Runs agentsgearbox/company-jobs-scraper on Apify. The actor remembers the job IDs it already delivered per careers board, in a key-value store in your Apify account, so each run returns only postings you have not seen and this script keeps no state. Schedule it every weekday 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 re 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/company-jobs-scraper" RUN_INPUT = { "companies": ["airbnb.com", "notion.so", "lever:palantir"], # domains, careers URLs or board shorthands "keywords": [], # e.g. ["engineer", "data"]; empty means every role "departments": [], # e.g. ["Engineering", "Sales"] "locations": [], # e.g. ["United States", "Remote"] "postedAfter": "30d", # first run or lost checkpoint: reach back 30 days at most "maxJobsPerCompany": 100, "includeDescription": False, # titles, teams, locations and salaries are enough for a signal "onlyNewSinceLastRun": True, "checkpointStoreName": "hiring-signals-target-accounts", # one store per watchlist } MAX_CHARGE_USD = Decimal("1.00") # hard cap per run; a normal morning costs a few cents SHOWN = 6 # roles listed per company; the rest are counted and linked CONSOLE = "https://console.apify.com" # A senior hire says more about an account than ten junior ones: these titles go first, marked. SENIOR = re.compile(r"\b(head of|vp\b|vice president|director|chief|founding|cto|cfo|cmo|coo|cro|general manager|principal)\b", re.I) 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.""" companies, problems, jobs = {}, [], defaultdict(list) for row in rows: if row.get("type") == "company": companies[row.get("boardUrl") or row["query"]] = row problems += company_problems(row) elif row.get("type") == "error": problems.append(f"{row.get('query')}: {row['error']}") elif row.get("jobId"): jobs[row.get("boardUrl") or row["query"]].append(row) total = sum(len(group) for group in jobs.values()) senior = sum(1 for group in jobs.values() for job in group if SENIOR.search(job.get("title") or "")) if not total and not problems: return [] noun = "role" if total == 1 else "roles" headline = f"{total} new {noun} at your target accounts" if senior: headline += f", {senior} senior" header = [ {"type": "header", "text": {"type": "plain_text", "text": headline}}, context(f"Since the last check · <{run_url(run)}|Apify run>"), ] busiest_first = sorted(jobs.items(), key=lambda item: -len(item[1])) sections = [company_blocks(companies.get(key, {}), group, run) for key, group 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=headline) def company_problems(c): who = c.get("companyName") or c["query"] if c.get("stoppedBy") == "chargeLimit": yield f"{who}: stopped at the ${MAX_CHARGE_USD} cap; raise MAX_CHARGE_USD" if c.get("status") == "ERROR": yield f"{who}: {c.get('note') or 'lookup failed'}" def company_blocks(company, group, run): name = company.get("companyName") or group[0].get("company") or "?" name = esc(name.capitalize() if name.islower() else name) # boards without a company name give their slug facts = [f"{len(group)} new"] if company.get("jobsOnBoard"): facts.append(f"{company['jobsOnBoard']} open on the board") teams = [f"{d['name']} {d['count']}" for d in (company.get("departments") or [])[:3] if d.get("name")] if teams: facts.append(", ".join(teams)) blocks = [section(f"*{name}*"), context(" · ".join(facts))] ordered = sorted(group, key=lambda job: (not SENIOR.search(job.get("title") or ""), job.get("postedAt") or ""), reverse=False) ordered = [job for job in ordered if SENIOR.search(job.get("title") or "")] + sorted( [job for job in ordered if not SENIOR.search(job.get("title") or "")], key=lambda job: job.get("postedAt") or "", reverse=True) blocks += [section(job_line(job)) for job 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 job_line(job): """One line per role: a marker for senior titles, team, where, pay when stated, link.""" mark = "🔺 " if SENIOR.search(job.get("title") or "") else "• " parts = [f"{mark}*{esc(clip(job.get('title') or '?', 90))}*"] where = job.get("location") or ("Remote" if job.get("remote") else None) if job.get("remote") and where and "remote" not in where.lower(): where += " (remote)" for value in (job.get("department") or job.get("team"), 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>" if job.get("postedAt"): line += f"\n_posted {job['postedAt'][:10]}_" return line def pack(header, sections, fallback, limit=50): """Slack takes at most 50 blocks per message: split between companies, 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 hiring_signals.py") if __name__ == "__main__": main()