Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import requests | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| from datetime import datetime | |
| from dotenv import load_dotenv | |
| import os | |
| # Load API token from .env | |
| load_dotenv() | |
| BEARER_TOKEN = os.getenv("TWITTER_BEARER_TOKEN") | |
| # Streamlit setup | |
| st.set_page_config(page_title="ZKGM Tracker", layout="wide") | |
| st.title("ZKGM Tweet Tracker") | |
| username = st.text_input("Enter Twitter Username (without @):", "elonmusk") | |
| # Headers for Twitter API | |
| headers = {"Authorization": f"Bearer {BEARER_TOKEN}"} | |
| # Get Twitter User ID from username | |
| def get_user_id(username): | |
| url = f"https://api.twitter.com/2/users/by/username/{username}" | |
| response = requests.get(url, headers=headers) | |
| if response.status_code == 200: | |
| return response.json()["data"]["id"] | |
| else: | |
| st.warning(f"Failed to fetch user ID. Status: {response.status_code}") | |
| st.code(response.text) | |
| return None | |
| # Search user's tweets for "zkgm" (case-insensitive) | |
| def get_zkgm_mentions(user_id, max_results=500): | |
| tweets = [] | |
| pagination_token = None | |
| url = f"https://api.twitter.com/2/users/{user_id}/tweets" | |
| while len(tweets) < max_results: | |
| params = { | |
| "max_results": 100, | |
| "tweet.fields": "created_at", | |
| } | |
| if pagination_token: | |
| params["pagination_token"] = pagination_token | |
| response = requests.get(url, headers=headers, params=params) | |
| if response.status_code != 200: | |
| st.error(f"Twitter API error: {response.status_code}") | |
| st.code(response.text) | |
| break | |
| data = response.json() | |
| for tweet in data.get("data", []): | |
| if "zkgm" in tweet["text"].lower(): | |
| tweets.append(tweet) | |
| pagination_token = data.get("meta", {}).get("next_token") | |
| if not pagination_token: | |
| break | |
| return tweets | |
| # Main app logic | |
| if st.button("Count Mentions and Show Chart"): | |
| with st.spinner("Fetching tweets..."): | |
| user_id = get_user_id(username) | |
| if not user_id: | |
| st.error("User not found or invalid username.") | |
| else: | |
| zkgm_tweets = get_zkgm_mentions(user_id) | |
| count = len(zkgm_tweets) | |
| st.success(f"β @{username} has mentioned 'ZKGM' {count} time(s).") | |
| if count > 0: | |
| df = pd.DataFrame(zkgm_tweets) | |
| df["created_at"] = pd.to_datetime(df["created_at"]) | |
| df["month"] = df["created_at"].dt.to_period("M") | |
| counts_by_month = df.groupby("month").size() | |
| # Bar chart | |
| st.subheader("π Monthly Mentions") | |
| fig, ax = plt.subplots() | |
| counts_by_month.plot(kind="bar", ax=ax, color="#4e79a7") | |
| ax.set_ylabel("Mentions") | |
| ax.set_xlabel("Month") | |
| st.pyplot(fig) | |