import os, requests, time
X = os.environ["X_BEARER_TOKEN"]; MV = os.environ["MAVERA_API_KEY"]
X_BASE = "https://api.x.com/2"; MV_BASE = "https://app.mavera.io/api/v1"
X_H = {"Authorization": f"Bearer {X}"}
MV_H = {"Authorization": f"Bearer {MV}", "Content-Type": "application/json"}
QUERY = '"Your Brand" OR @yourbrand -is:retweet'
tweets, next_token = [], None
# 1. Paginated search
for _ in range(3):
params = {"query": QUERY, "max_results": 100,
"tweet.fields": "created_at,public_metrics,author_id",
"expansions": "author_id", "user.fields": "name,username,public_metrics"}
if next_token: params["next_token"] = next_token
r = requests.get(f"{X_BASE}/tweets/search/recent", headers=X_H, params=params)
if r.status_code == 429:
time.sleep(int(r.headers.get("x-rate-limit-reset", time.time()+60)) - int(time.time()))
r = requests.get(f"{X_BASE}/tweets/search/recent", headers=X_H, params=params)
r.raise_for_status(); data = r.json()
users = {u["id"]: u for u in data.get("includes",{}).get("users",[])}
for t in data.get("data",[]):
a = users.get(t.get("author_id"),{})
m = t.get("public_metrics",{})
tweets.append({"text": t["text"], "username": a.get("username",""),
"followers": a.get("public_metrics",{}).get("followers_count",0),
"likes": m.get("like_count",0), "retweets": m.get("retweet_count",0)})
next_token = data.get("meta",{}).get("next_token")
if not next_token: break
time.sleep(1)
print(f"Collected {len(tweets)} brand mentions")
# 2. Mavera Chat analysis
block = "\n\n".join(f"@{t['username']} ({t['followers']:,} fol) | {t['likes']}♥ {t['retweets']}🔁\n{t['text']}"
for t in sorted(tweets, key=lambda x: -(x["likes"]+x["retweets"]))[:50])
analysis = requests.post(f"{MV_BASE}/mave/chat", headers=MV_H, json={
"message": f"Brand sentiment analyst. Classify these {len(tweets)} tweets.\n\nTWEETS:\n{block}\n\n"
"Produce:\n## Sentiment Distribution (count, %, themes)\n## Topic Clusters (ranked, with representative tweets)\n"
"## High-Impact Mentions (followers >10K or engagement >50)\n## Emerging Issues (3+ negative mentions)\n## Recommended Actions"
}).json()
print(analysis.get("content","")[:2000])