import os, requests, time
LI = os.environ["LINKEDIN_ACCESS_TOKEN"]
MV = os.environ["MAVERA_API_KEY"]
LI_BASE = "https://api.linkedin.com/rest"
MV_BASE = "https://app.mavera.io/api/v1"
LI_H = {"Authorization": f"Bearer {LI}", "LinkedIn-Version": "202401", "X-Restli-Protocol-Version": "2.0.0"}
MV_H = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
CAMPAIGN_URN = "urn:li:sponsoredCampaign:200000001"
# 1. Pull analytics pivoted by industry
pivots = ["MEMBER_INDUSTRY", "MEMBER_JOB_FUNCTION", "MEMBER_SENIORITY"]
all_segments = []
for pivot in pivots:
r = requests.get(f"{LI_BASE}/adAnalytics",
headers=LI_H,
params={
"q": "analytics",
"pivot": pivot,
"dateRange.start.year": 2025, "dateRange.start.month": 1, "dateRange.start.day": 1,
"dateRange.end.year": 2025, "dateRange.end.month": 12, "dateRange.end.day": 31,
"timeGranularity": "ALL",
"campaigns[0]": CAMPAIGN_URN,
"fields": "impressions,clicks,costInLocalCurrency,externalWebsiteConversions",
})
if r.status_code == 429:
time.sleep(int(r.headers.get("Retry-After", 60)))
continue
r.raise_for_status()
for el in r.json().get("elements", []):
impressions = el.get("impressions", 0)
clicks = el.get("clicks", 0)
if impressions < 100:
continue
ctr = clicks / impressions if impressions else 0
conversions = el.get("externalWebsiteConversions", 0)
all_segments.append({
"pivot": pivot,
"value": el.get("pivotValue", "Unknown"),
"impressions": impressions,
"clicks": clicks,
"ctr": round(ctr * 100, 2),
"conversions": conversions,
"spend": el.get("costInLocalCurrency", 0),
})
time.sleep(0.5)
# 2. Rank by CTR, take top segments
top = sorted(all_segments, key=lambda x: -x["ctr"])[:6]
# 3. Generate content briefs via Mave
for seg in top:
brief = requests.post(f"{MV_BASE}/mave/chat", headers=MV_H, json={
"message": f"""Write a content brief for this high-performing LinkedIn audience segment.
SEGMENT: {seg['value']} ({seg['pivot'].replace('MEMBER_', '').replace('_', ' ').title()})
PERFORMANCE: {seg['impressions']:,} impressions | {seg['clicks']:,} clicks | CTR: {seg['ctr']}% | {seg['conversions']} conversions | ${seg['spend']:,.2f} spend
Produce:
1. Why this segment responds (hypotheses based on role/industry/seniority)
2. Content brief: topic, angle, format (whitepaper / blog / video / carousel)
3. Headline options (3)
4. Key messages and proof points to include
5. Distribution strategy (organic LinkedIn + paid amplification)
6. Recommended content length and CTA"""
}).json()
print(f"\n{'='*50}")
print(f"SEGMENT: {seg['value']} | CTR: {seg['ctr']}% | Clicks: {seg['clicks']:,}")
print(f"{'='*50}")
print(brief.get("content", "")[:600])