import os, requests, time
TT = os.environ["TIKTOK_ACCESS_TOKEN"]
ADV = os.environ["TIKTOK_ADVERTISER_ID"]
MV = os.environ["MAVERA_API_KEY"]
TT_BASE = "https://business-api.tiktok.com/open_api/v1.3"
MV_BASE = "https://app.mavera.io/api/v1"
TT_H = {"Access-Token": TT}
MV_H = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
BRAND_CONTEXT = """
Brand: [Your Brand] — B2C wellness/fitness product
Audience: 18-34, health-conscious, active lifestyle
Tone: Energetic, authentic, educational. Avoid: clinical, preachy, overly polished.
Topics: Fitness routines, nutrition tips, mental health, product demos.
Avoid topics: Politics, religion, controversy, competitor bashing.
"""
# 1. Discover trending hashtags via Research API
trending = requests.post(f"{TT_BASE}/research/hashtag/trending/",
headers=TT_H,
json={
"advertiser_id": ADV,
"country_code": "US",
"period": 7,
"limit": 20,
})
if trending.status_code != 200 or trending.json().get("code") != 0:
# Fallback: query top-performing hashtags from your own campaigns
trending_data = requests.post(f"{TT_BASE}/reports/integrated/get/",
headers=TT_H,
json={
"advertiser_id": ADV, "report_type": "BASIC",
"data_level": "AUCTION_AD", "dimensions": ["ad_id"],
"metrics": ["ad_name", "clicks", "impressions"],
"start_date": "2025-11-01", "end_date": "2025-12-31",
"page_size": 10, "page": 1,
}).json()
hashtags = [{"name": f"trending_fallback_{i}", "views": 0} for i in range(5)]
else:
hashtags = [{"name": h.get("hashtag_name", ""), "views": h.get("video_views", 0)}
for h in trending.json().get("data", {}).get("list", [])]
# 2. Brand alignment check via Mave
aligned_trends = []
for tag in hashtags[:10]:
check = requests.post(f"{MV_BASE}/mave/chat", headers=MV_H, json={
"message": f"""Evaluate whether this TikTok trend aligns with our brand.
TREND: #{tag['name']} ({tag['views']:,} views in 7 days)
BRAND CONTEXT:
{BRAND_CONTEXT}
Score 1-10 for brand alignment. Explain why or why not.
If aligned (7+): suggest an angle that connects the trend to our product.
If not aligned: explain the risk."""
}).json()
content = check.get("content", "")
score_line = [l for l in content.split("\n") if "score" in l.lower() or "/10" in l]
try:
score = int("".join(c for c in (score_line[0] if score_line else "0") if c.isdigit())[:2])
except (ValueError, IndexError):
score = 0
if score >= 7:
aligned_trends.append({"tag": tag["name"], "views": tag["views"], "score": score, "angle": content[:300]})
print(f"Trends checked: {min(len(hashtags), 10)} | Aligned: {len(aligned_trends)}")
# 3. Generate TikTok scripts for aligned trends
for trend in aligned_trends[:5]:
script = requests.post(f"{MV_BASE}/generations", headers=MV_H, json={
"prompt": f"""Write a TikTok video script for the trend #{trend['tag']}.
BRAND ANGLE: {trend['angle'][:200]}
Requirements:
- 15-30 second duration
- Hook in first 1.5 seconds (text overlay + spoken)
- Include trending audio suggestion
- End with clear CTA
- Write in a shooting-script format: [VISUAL] / [AUDIO] / [TEXT OVERLAY]
Make it feel native to TikTok, not like an ad.""",
}).json()
print(f"\n{'='*50}")
print(f"TREND: #{trend['tag']} | Alignment: {trend['score']}/10 | Views: {trend['views']:,}")
print(f"{'='*50}")
print(script.get("output", script.get("content", ""))[:500])