### Start Development Server with API Routing (JavaScript) Source: https://context7.com/duolaamengweb3/polyelon/llms.txt This code snippet illustrates how to start a local development server using npm. It highlights dynamic API routing, where requests to /api/* endpoints trigger corresponding module imports, and static file serving from the root directory. Environment variables for Supabase, Twitter, and other services are also detailed. ```javascript // Start development server // npm run serve // Server configuration in dev-server.js const port = process.env.PORT || 3000; // API routes are dynamically loaded // /api/polymarket -> imports ./api/polymarket.js // /api/alerts -> imports ./api/alerts.js // Static files served from root directory // / -> index.html // /logoduolai.png -> logoduolai.png // Environment setup // Create .env file with: // SUPABASE_URL=https://your-project.supabase.co // SUPABASE_ANON_KEY=your-anon-key // SUPABASE_SERVICE_KEY=your-service-key // TWITTER_API_KEY=your-twitter-api-key // CRON_SECRET=random-secret-string // Example local development workflow: // 1. Copy .env.example to .env // 2. Fill in environment variables // 3. npm install // 4. npm run serve // 5. Open http://localhost:3000 // 6. Frontend automatically calls /api/* endpoints ``` -------------------------------- ### GET /api/market-history Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Retrieves historical tweet counts for past and active market periods. This endpoint returns detailed information about market cycles, including their status, tweet counts, and progress. ```APIDOC ## GET /api/market-history ### Description Retrieves historical tweet counts for past and active market periods. This endpoint returns detailed information about market cycles, including their status, tweet counts, and progress. ### Method GET ### Endpoint /api/market-history ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example GET /api/market-history ### Response #### Success Response (200) - **markets** (array) - An array of market objects, each containing id, title, startDate, endDate, status, actualCount, and progress. - **summary** (object) - An object containing summary statistics like totalMarkets, settledMarkets, avgTweetsPerWeek, and totalTweets. - **dailyCounts** (object) - An object mapping dates to the number of tweets on that day. #### Response Example ```json { "markets": [ { "id": "nov21-28", "title": "Nov 21 - 28", "startDate": "2025-11-21", "endDate": "2025-11-28", "status": "settled", "actualCount": 42, "progress": null }, { "id": "nov25-dec2", "title": "Nov 25 - Dec 2", "startDate": "2025-11-25", "endDate": "2025-12-02", "status": "active", "actualCount": 15, "progress": { "elapsedDays": 5, "remainingDays": 2, "totalDays": 7, "projected": 21 } }, { "id": "nov28-dec5", "title": "Nov 28 - Dec 5", "status": "ending_today", "actualCount": 38, "progress": { "elapsedDays": 7, "remainingDays": 0, "totalDays": 7 } } ], "summary": { "totalMarkets": 6, "settledMarkets": 4, "avgTweetsPerWeek": 38, "totalTweets": 500 }, "dailyCounts": { "2025-11-21": 5, "2025-11-22": 7, "2025-11-23": 6 } } ``` ``` -------------------------------- ### Fetch Event Calendar Data (JavaScript) Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Retrieves upcoming and past events from the Event Calendar API. It combines data from SpaceX and manually curated events. The API response includes event details such as type, title, date, source, and historical impact on tweet activity. Frontend examples demonstrate how to render this data. ```javascript // GET /api/events // Combines SpaceX API data with manually curated events const response = await fetch('/api/events'); const events = await response.json(); console.log(events); // Response structure: // { // "upcoming": [ // { // "type": "spacex", // "title": "Starship Flight 6", // "date": "2025-12-15T10:00:00.000Z", // "description": "Rocket launch", // "source": "SpaceX API", // "icon": "๐Ÿš€", // "impactLevel": "high", // "historicalImpact": "+35% tweet activity on launch days" // }, // { // "type": "tesla", // "title": "Tesla Q4 2024 Earnings Call", // "date": "2025-01-29T22:00:00Z", // "description": "Quarterly earnings report and investor call", // "source": "Tesla IR", // "icon": "๐Ÿ“ˆ", // "impactLevel": "high", // "historicalImpact": "+40% tweet activity on earnings days" // } // ], // "past": [ // { // "type": "politics", // "title": "Trump Inauguration", // "date": "2025-01-20T17:00:00.000Z", // "icon": "๐Ÿ‡บ๐Ÿ‡ธ", // "impactLevel": "high" // } // ], // "lastUpdated": "2025-11-30T06:00:00.000Z" // } // Frontend rendering example events.upcoming.forEach(event => { const dateStr = new Date(event.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }); console.log(`${event.icon} ${event.title} - ${dateStr}`); console.log(`Impact: ${event.historicalImpact}`); }); ``` -------------------------------- ### GET Market History API Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Retrieves historical tweet counts for past and active market periods. This API endpoint returns a JSON object containing detailed market data, summary statistics, and daily tweet counts. It is essential for analyzing market performance and tweet volume over time. ```javascript // GET /api/market-history // Returns actual tweet counts for each market cycle const response = await fetch('/api/market-history'); const history = await response.json(); console.log(history); // Response structure: // { // "markets": [ // { // "id": "nov21-28", // "title": "Nov 21 - 28", // "startDate": "2025-11-21", // "endDate": "2025-11-28", // "status": "settled", // "actualCount": 42, // "progress": null // }, // { // "id": "nov25-dec2", // "title": "Nov 25 - Dec 2", // "startDate": "2025-11-25", // "endDate": "2025-12-02", // "status": "active", // "actualCount": 15, // "progress": { // "elapsedDays": 5, // "remainingDays": 2, // "totalDays": 7, // "projected": 21 // } // }, // { // "id": "nov28-dec5", // "title": "Nov 28 - Dec 5", // "status": "ending_today", // "actualCount": 38, // "progress": { "elapsedDays": 7, "remainingDays": 0, "totalDays": 7 } // } // ], // "summary": { // "totalMarkets": 6, // "settledMarkets": 4, // "avgTweetsPerWeek": 38, // "totalTweets": 500 // }, // "dailyCounts": { // "2025-11-21": 5, // "2025-11-22": 7, // "2025-11-23": 6 // } // } // Calculate projection accuracy const activeMarket = history.markets.find(m => m.status === 'active'); if (activeMarket?.progress?.projected) { const dailyRate = activeMarket.actualCount / activeMarket.progress.elapsedDays; console.log(`Current pace: ${dailyRate.toFixed(1)} tweets/day`); console.log(`Projected total: ${activeMarket.progress.projected} tweets`); } ``` -------------------------------- ### Frontend Data Loading and Visualization (JavaScript) Source: https://context7.com/duolaamengweb3/polyelon/llms.txt This JavaScript code demonstrates the frontend data flow for the PolyElon application. It includes fetching real-time data from the /api/polymarket endpoint, loading historical tweets, rendering charts using a charting library, and aggregating data from multiple API endpoints in parallel. It also shows how to implement auto-refresh functionality. ```javascript // Main data loading flow from index.html // 1. Load Polymarket real-time data async function loadPolymarketData() { const response = await fetch('/api/polymarket'); const marketData = await response.json(); // Select active market const activeMarket = marketData.currentMarket; // Update UI with market info document.getElementById('marketTitle').textContent = activeMarket.title; document.getElementById('marketVolume').textContent = formatMoney(activeMarket.volume); // Render odds distribution chart const ctx = document.getElementById('oddsChart').getContext('2d'); new Chart(ctx, { type: 'bar', data: { labels: activeMarket.outcomes.map(o => o.range), datasets: [{ label: 'Probability (%)', data: activeMarket.outcomes.map(o => o.yesPrice * 100) }] } }); } // 2. Load historical tweet data async function loadHistoricalData() { const response = await fetch('elon_november_tweets.json'); const data = await response.json(); // Calculate daily counts const dailyCount = {}; data.tweets.forEach(tweet => { const date = parseDate(tweet.createdAt); dailyCount[date] = (dailyCount[date] || 0) + 1; }); // Render trend chart renderTrendChart(dailyCount); } // 3. Load all analytics in parallel Promise.all([ loadPolymarketData(), loadHistoricalData(), fetch('/api/events').then(r => r.json()), fetch('/api/alerts').then(r => r.json()), fetch('/api/keywords').then(r => r.json()), fetch('/api/market-history').then(r => r.json()) ]).then(([markets, history, events, alerts, keywords, marketHistory]) => { // All data loaded, update UI renderAllDashboards(markets, history, events, alerts, keywords, marketHistory); }); // 4. Auto-refresh every minute setInterval(loadPolymarketData, 60000); setInterval(() => fetch('/api/alerts').then(r => r.json()).then(renderAlerts), 60000); ``` -------------------------------- ### Supabase Database Functions Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Provides access to core database operations and queries for tweet analytics using SQL. ```APIDOC ## Supabase Database Functions ### Description Provides access to core database operations and queries for tweet analytics using SQL. ### Method SQL ### Endpoint N/A (Direct database access) ### Functions #### `get_full_stats()` **Description**: Retrieves comprehensive statistics about tweets. **Example Usage**: ```sql SELECT get_full_stats(); ``` **Response Example**: ```json { "total": 500, "original": 320, "replies": 150, "retweets": 20, "quotes": 10, "prediction_count": 42, "today_count": 5, "total_likes": 15000000, "total_views": 500000000, "last_updated": "2025-11-30T06:00:00.000Z", "last_tweet_at": "2025-11-30T05:45:00.000Z" } ``` #### `daily_stats` (View) **Description**: Queries daily statistics including tweet count, total likes, and total views. **Example Usage**: ```sql SELECT * FROM daily_stats WHERE date >= '2025-11-01' ORDER BY date DESC; ``` **Response Example**: ``` date | tweet_count | total_likes | total_views | weekday 2025-11-30 | 15 | 500000 | 20000000 | 6 2025-11-29 | 18 | 600000 | 25000000 | 5 ``` #### `hourly_stats` (View) **Description**: Provides tweet distribution by hour. **Example Usage**: ```sql SELECT * FROM hourly_stats; ``` **Response Example**: ``` hour | tweet_count 0 | 26 1 | 44 14 | 42 ``` #### `weekday_stats` (View) **Description**: Shows average tweet counts per weekday. **Example Usage**: ```sql SELECT * FROM weekday_stats; ``` **Response Example**: ``` weekday | total_count | day_count | avg_count 0 | 45 | 4 | 11.3 5 | 120 | 4 | 30.0 ``` ``` -------------------------------- ### Polymarket Real-Time Market Data API Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Fetches and aggregates live prediction market data for Elon Musk tweet count markets from Polymarket Gamma API. ```APIDOC ## GET /api/polymarket ### Description Fetches multiple Polymarket markets in parallel related to Elon Musk's tweet count and returns structured data. ### Method GET ### Endpoint /api/polymarket ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```javascript const response = await fetch('/api/polymarket'); const data = await response.json(); console.log(data); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **timestamp** (string) - The timestamp of the data retrieval. - **totalMarkets** (integer) - The total number of markets available. - **activeMarkets** (integer) - The number of currently active markets. - **markets** (array) - An array of market objects. - **id** (string) - The unique identifier for the market. - **title** (string) - The title of the market. - **slug** (string) - A URL-friendly version of the market title. - **startDate** (string) - The start date of the market. - **endDate** (string) - The end date of the market. - **volume** (integer) - The total trading volume for the market. - **liquidity** (integer) - The total liquidity in the market. - **active** (boolean) - Whether the market is currently active. - **closed** (boolean) - Whether the market has been closed. - **volume24hr** (integer) - The trading volume in the last 24 hours. - **estimatedMinTweets** (integer) - Estimated minimum number of tweets for the market outcome. - **outcomes** (array) - An array of possible outcomes for the market. - **range** (string) - The range for the outcome (e.g., "20-39"). - **threshold** (integer) - The threshold associated with the outcome. - **yesPrice** (float) - The probability of the "yes" outcome. - **noPrice** (float) - The probability of the "no" outcome. - **volume** (integer) - The trading volume for this specific outcome. - **liquidity** (integer) - The liquidity for this specific outcome. - **question** (string) - The question defining this outcome. - **slug** (string) - A URL-friendly version of the outcome. - **polymarketUrl** (string) - The URL to the market on Polymarket. - **currentMarket** (object) - The recommended active market. #### Response Example ```json { "success": true, "timestamp": "2025-11-30T06:00:00.000Z", "totalMarkets": 3, "activeMarkets": 2, "markets": [ { "id": "0x123...", "title": "Elon Musk # tweets November 21-28, 2025?", "slug": "elon-musk-of-tweets-november-21-november-28", "startDate": "2025-11-21T00:00:00.000Z", "endDate": "2025-11-28T23:59:59.000Z", "volume": 45000, "liquidity": 12000, "active": true, "closed": false, "volume24hr": 5000, "estimatedMinTweets": 40, "outcomes": [ { "range": "20-39", "threshold": 1, "yesPrice": 0.15, "noPrice": 0.85, "volume": 5000, "liquidity": 1200, "question": "Will Elon tweet 20-39 times?", "slug": "elon-20-39" } ], "polymarketUrl": "https://polymarket.com/event/elon-musk-of-tweets-november-21-november-28" } ], "currentMarket": { /* recommended active market */ } } ``` #### Error Handling If `success` is false, an `error` field may be present in the response. ``` -------------------------------- ### Supabase Database Functions for Tweet Analytics Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Provides SQL functions and views for querying tweet analytics from Supabase. These include comprehensive statistics, daily and hourly distributions, and weekday averages, enabling detailed analysis of tweet activity. ```sql -- Get comprehensive statistics SELECT get_full_stats(); -- Returns JSON: -- { -- "total": 500, -- "original": 320, -- "replies": 150, -- "retweets": 20, -- "quotes": 10, -- "prediction_count": 42, -- "today_count": 5, -- "total_likes": 15000000, -- "total_views": 500000000, -- "last_updated": "2025-11-30T06:00:00.000Z", -- "last_tweet_at": "2025-11-30T05:45:00.000Z" -- } -- Query daily statistics view SELECT * FROM daily_stats WHERE date >= '2025-11-01' ORDER BY date DESC; -- Returns: -- date | tweet_count | total_likes | total_views | weekday -- 2025-11-30 | 15 | 500000 | 20000000 | 6 -- 2025-11-29 | 18 | 600000 | 25000000 | 5 -- Query hourly distribution SELECT * FROM hourly_stats; -- Returns: -- hour | tweet_count -- 0 | 26 -- 1 | 44 -- 14 | 42 -- Query weekday averages SELECT * FROM weekday_stats; -- Returns: -- weekday | total_count | day_count | avg_count -- 0 | 45 | 4 | 11.3 -- 5 | 120 | 4 | 30.0 ``` -------------------------------- ### Tweet Activity Alert System API Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Analyzes recent tweet patterns and generates alerts for unusual activity levels based on historical data and real-time analysis. ```APIDOC ## GET /api/alerts ### Description Analyzes recent tweet patterns and generates alerts for unusual activity levels, providing baseline statistics and anomaly detection. ### Method GET ### Endpoint /api/alerts ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```javascript const response = await fetch('/api/alerts'); const alerts = await response.json(); console.log(alerts); ``` ### Response #### Success Response (200) - **alerts** (array) - A list of detected activity alerts. - **type** (string) - The type of alert (e.g., "high_activity", "burst"). - **level** (string) - The severity level of the alert (e.g., "warning", "alert"). - **message** (string) - A human-readable message describing the alert. - **icon** (string) - An emoji icon representing the alert. - **timestamp** (string) - The timestamp when the alert condition was met. - **baseline** (object) - Baseline statistical data for tweet activity. - **avgDailyTweets** (integer) - Average number of tweets per day. - **avgHourlyTweets** (string) - Average number of tweets per hour. - **avgDailyLikes** (integer) - Average number of likes per day. - **trend** (string) - The overall trend of tweet activity (e.g., "increasing"). - **prediction** (object) - Predictive insights based on current data. - **expectedDailyTweets** (integer) - Expected number of tweets for the day. - **confidence** (string) - The confidence level of the prediction (e.g., "medium"). - **factors** (array) - Factors influencing the prediction. - **recentActivity** (object) - Details on recent tweet activity. - **today** (object) - Statistics for the current day. - **count** (integer) - Number of tweets today. - **likes** (integer) - Number of likes today. - **views** (integer) - Number of views today. - **hourly** (array) - Activity breakdown by hour. - **hour** (string) - The hour of the day (e.g., "14:00"). - **date** (string) - The date for the hourly data. - **count** (integer) - Number of tweets during that hour. - **likes** (integer) - Number of likes during that hour. #### Response Example ```json { "alerts": [ { "type": "high_activity", "level": "warning", "message": "ไปŠๆ—ฅๆŽจๆ–‡ๆ•ฐ (25) ้ซ˜ไบŽๅนณๅ‡ (18)", "icon": "๐Ÿ”ฅ", "timestamp": "2025-11-30T06:00:00.000Z" }, { "type": "burst", "level": "alert", "message": "14:00 ๆ—ถๆฎต็ˆ†ๅ‘: 8 ๆกๆŽจๆ–‡", "icon": "โšก", "timestamp": "2025-11-30T14:00:00" } ], "baseline": { "avgDailyTweets": 18, "avgHourlyTweets": "0.8", "avgDailyLikes": 150000 }, "trend": "increasing", "prediction": { "expectedDailyTweets": 20, "confidence": "medium", "factors": ["ๅ‘จๆœซ้€šๅธธๆŽจๆ–‡่พƒๅฐ‘"] }, "recentActivity": { "today": { "count": 25, "likes": 200000, "views": 5000000 }, "hourly": [ { "hour": "14:00", "date": "2025-11-30", "count": 8, "likes": 50000 } ] } } ``` ``` -------------------------------- ### Fetch Keyword Analysis Data (JavaScript) Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Retrieves categorized tweet data and engagement metrics from the Keyword Analysis API. The API response includes total tweet counts, category breakdowns (with keywords, counts, percentages, and engagement metrics), daily trends, and a summary of the most discussed and highest engagement topics. Custom keyword categories are also defined. ```javascript // GET /api/keywords // Analyzes tweet content and categorizes by predefined keywords const response = await fetch('/api/keywords'); const keywords = await response.json(); console.log(keywords); // Response structure: // { // "totalTweets": 500, // "categories": [ // { // "key": "spacex", // "icon": "๐Ÿš€", // "label": "SpaceX", // "keywords": ["spacex", "starship", "falcon", "starlink", "rocket"], // "count": 120, // "percentage": "24.0", // "avgLikes": 45000, // "avgViews": 2000000, // "totalLikes": 5400000, // "totalViews": 240000000, // "topTweets": [ // { // "text": "Starship is ready for launch...", // "likes": 150000, // "views": 5000000, // "date": "2025-11-25T10:30:00.000Z" // } // ] // }, // { // "key": "tesla", // "icon": "๐Ÿš—", // "label": "Tesla", // "count": 85, // "percentage": "17.0", // "avgLikes": 38000 // } // ], // "dailyTrend": [ // { "date": "2025-11-30", "spacex": 5, "tesla": 3, "ai": 2 } // ], // "summary": { // "mostDiscussed": "SpaceX", // "highestEngagement": "SpaceX" // } // } // Custom keyword categories (from keywords.js) const categories = { tesla: ['tesla', 'cybertruck', 'model', 'fsd', 'autopilot'], spacex: ['spacex', 'starship', 'falcon', 'starlink', 'rocket'], ai: ['ai', 'grok', 'xai', 'chatgpt', 'openai'], politics: ['trump', 'doge', 'government', 'congress', 'senate'] }; ``` -------------------------------- ### Fetch Polymarket Real-Time Market Data API (JavaScript) Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Fetches and aggregates live prediction market data for Elon Musk tweet count markets from Polymarket Gamma API. This endpoint is designed to be called from a browser or serverless function. It returns structured data including market details, volume, liquidity, and outcome predictions. Error handling for failed requests is included. ```javascript const response = await fetch('/api/polymarket'); const data = await response.json(); console.log(data); // Response structure: // { // "success": true, // "timestamp": "2025-11-30T06:00:00.000Z", // "totalMarkets": 3, // "activeMarkets": 2, // "markets": [ // { // "id": "0x123...", // "title": "Elon Musk # tweets November 21-28, 2025?", // "slug": "elon-musk-of-tweets-november-21-november-28", // "startDate": "2025-11-21T00:00:00.000Z", // "endDate": "2025-11-28T23:59:59.000Z", // "volume": 45000, // "liquidity": 12000, // "active": true, // "closed": false, // "volume24hr": 5000, // "estimatedMinTweets": 40, // "outcomes": [ // { // "range": "20-39", // "threshold": 1, // "yesPrice": 0.15, // "noPrice": 0.85, // "volume": 5000, // "liquidity": 1200, // "question": "Will Elon tweet 20-39 times?", // "slug": "elon-20-39" // } // ], // "polymarketUrl": "https://polymarket.com/event/elon-musk-of-tweets-november-21-november-28" // } // ], // "currentMarket": { /* recommended active market */ } // } // Error handling if (!data.success) { console.error('API Error:', data.error); } ``` -------------------------------- ### POST /api/fetch-tweets Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Protected endpoint for fetching and storing daily tweets. Requires authentication via Vercel Cron header or Bearer token. This endpoint runs twice daily. ```APIDOC ## POST /api/fetch-tweets ### Description Protected endpoint for fetching and storing daily tweets. Requires authentication via Vercel Cron header or Bearer token. This endpoint runs twice daily. ### Method POST ### Endpoint /api/fetch-tweets ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const response = await fetch('/api/fetch-tweets', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.CRON_SECRET}` } }); ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the tweet fetching was successful. - **date** (string) - The date for which tweets were fetched. - **fetched** (integer) - The number of tweets fetched. - **saved** (integer) - The number of tweets saved to the database. #### Response Example ```json { "success": true, "date": "2025-11-30", "fetched": 15, "saved": 15 } ``` ### Error Handling - **401 Unauthorized**: If the `CRON_SECRET` is missing or the `x-vercel-cron` header is not provided. - **Error Object**: If the fetch operation fails, the response will contain an `error` field describing the issue. ``` -------------------------------- ### Analyze Tweet Activity and Generate Alerts (JavaScript) Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Analyzes recent tweet patterns and generates alerts for unusual activity levels. This endpoint provides a baseline of tweet statistics, anomaly detection, and predictions. The response includes an array of alerts, baseline metrics, trend analysis, and recent activity data. Designed for serverless execution. ```javascript const response = await fetch('/api/alerts'); const alerts = await response.json(); console.log(alerts); // Response structure: // { // "alerts": [ // { // "type": "high_activity", // "level": "warning", // "message": "ไปŠๆ—ฅๆŽจๆ–‡ๆ•ฐ (25) ้ซ˜ไบŽๅนณๅ‡ (18)", // "icon": "๐Ÿ”ฅ", // "timestamp": "2025-11-30T06:00:00.000Z" // }, // { // "type": "burst", // "level": "alert", // "message": "14:00 ๆ—ถๆฎต็ˆ†ๅ‘: 8 ๆกๆŽจๆ–‡", // "icon": "โšก", // "timestamp": "2025-11-30T14:00:00" // } // ], // "baseline": { // "avgDailyTweets": 18, // "avgHourlyTweets": "0.8", // "avgDailyLikes": 150000 // }, // "trend": "increasing", // "prediction": { // "expectedDailyTweets": 20, // "confidence": "medium", // "factors": ["ๅ‘จๆœซ้€šๅธธๆŽจๆ–‡่พƒๅฐ‘"] // }, // "recentActivity": { // "today": { "count": 25, "likes": 200000, "views": 5000000 }, // "hourly": [ // { "hour": "14:00", "date": "2025-11-30", "count": 8, "likes": 50000 } // ] // } // } ``` -------------------------------- ### POST Protected Tweet Fetching Endpoint Source: https://context7.com/duolaamengweb3/polyelon/llms.txt An automated endpoint for fetching and storing daily tweets, requiring authentication via Vercel Cron header or Bearer token. This endpoint is designed to run twice daily and provides feedback on the success of the fetch and save operations. ```javascript // POST /api/fetch-tweets // Protected by Vercel Cron header or Bearer token // Runs twice daily: US noon and evening // Manual trigger with authentication const response = await fetch('/api/fetch-tweets', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.CRON_SECRET}` } }); const result = await response.json(); console.log(result); // Response: // { // "success": true, // "date": "2025-11-30", // "fetched": 15, // "saved": 15 // } // Vercel Cron configuration (vercel.json): // { // "crons": [{ // "path": "/api/fetch-tweets", // "schedule": "0 12,22 * * *" // }] // } // Error handling if (response.status === 401) { console.error('Unauthorized: Missing CRON_SECRET or x-vercel-cron header'); } else if (!result.success) { console.error('Fetch failed:', result.error); } // Data stored in Supabase tweets table with structure: // { // tweet_id: "1234567890", // text: "Tweet content...", // created_at: "2025-11-30T12:00:00.000Z", // like_count: 5000, // retweet_count: 1000, // reply_count: 500, // view_count: 100000, // is_reply: false, // is_retweet: false, // is_quote: false, // raw_data: { /* full API response */ } // } ``` -------------------------------- ### Keyword Analysis API Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Categorizes tweets by topic and calculates engagement metrics for each category. This endpoint analyzes tweet content based on predefined keywords and provides insights into tweet volume and engagement. ```APIDOC ## GET /api/keywords ### Description Analyzes tweet content, categorizes tweets by predefined keywords, and calculates various engagement metrics for each category. It also provides daily trends and a summary of the most discussed and highest engagement categories. ### Method GET ### Endpoint /api/keywords ### Parameters #### Query Parameters None ### Request Example None (GET request) ### Response #### Success Response (200) - **totalTweets** (integer) - The total number of tweets analyzed. - **categories** (array) - An array of objects, where each object represents a keyword category. - **key** (string) - The unique identifier for the category (e.g., "spacex", "tesla"). - **icon** (string) - An emoji representing the category. - **label** (string) - The display name for the category. - **keywords** (array of strings, optional) - A list of keywords associated with this category. - **count** (integer) - The number of tweets in this category. - **percentage** (string) - The percentage of total tweets that belong to this category. - **avgLikes** (integer, optional) - The average number of likes for tweets in this category. - **avgViews** (integer, optional) - The average number of views for tweets in this category. - **totalLikes** (integer, optional) - The total number of likes for all tweets in this category. - **totalViews** (integer, optional) - The total number of views for all tweets in this category. - **topTweets** (array of objects, optional) - A list of the top tweets in this category. - **text** (string) - The content of the tweet. - **likes** (integer) - The number of likes the tweet received. - **views** (integer) - The number of views the tweet received. - **date** (string) - The date and time the tweet was posted. - **dailyTrend** (array) - An array of objects showing tweet counts per category on a daily basis. - **date** (string) - The date of the trend. - **[category_key]** (integer) - The count of tweets for a specific category on that date. - **summary** (object) - A summary of the analysis. - **mostDiscussed** (string) - The category with the highest tweet count. - **highestEngagement** (string) - The category with the highest engagement (based on available metrics). #### Response Example ```json { "totalTweets": 500, "categories": [ { "key": "spacex", "icon": "๐Ÿš€", "label": "SpaceX", "keywords": ["spacex", "starship", "falcon", "starlink", "rocket"], "count": 120, "percentage": "24.0", "avgLikes": 45000, "avgViews": 2000000, "totalLikes": 5400000, "totalViews": 240000000, "topTweets": [ { "text": "Starship is ready for launch...", "likes": 150000, "views": 5000000, "date": "2025-11-25T10:30:00.000Z" } ] }, { "key": "tesla", "icon": "๐Ÿš—", "label": "Tesla", "count": 85, "percentage": "17.0", "avgLikes": 38000 } ], "dailyTrend": [ { "date": "2025-11-30", "spacex": 5, "tesla": 3, "ai": 2 } ], "summary": { "mostDiscussed": "SpaceX", "highestEngagement": "SpaceX" } } ``` ``` -------------------------------- ### Event Calendar API Source: https://context7.com/duolaamengweb3/polyelon/llms.txt Aggregates upcoming and past events (SpaceX launches, Tesla earnings, political events) that may impact tweet activity. This endpoint combines data from the SpaceX API with manually curated events. ```APIDOC ## GET /api/events ### Description Retrieves a list of upcoming and past events that could influence tweet activity. The data is aggregated from sources like the SpaceX API and curated event data. ### Method GET ### Endpoint /api/events ### Parameters #### Query Parameters None ### Request Example None (GET request) ### Response #### Success Response (200) - **upcoming** (array) - A list of upcoming events. - **type** (string) - The category of the event (e.g., "spacex", "tesla", "politics"). - **title** (string) - The title of the event. - **date** (string) - The date and time of the event in ISO 8601 format. - **description** (string, optional) - A brief description of the event. - **source** (string, optional) - The source of the event information. - **icon** (string) - An emoji representing the event category. - **impactLevel** (string) - The potential impact level on tweet activity (e.g., "high"). - **historicalImpact** (string, optional) - Description of the event's historical impact on tweet activity. - **past** (array) - A list of past events. - **type** (string) - The category of the event. - **title** (string) - The title of the event. - **date** (string) - The date and time of the event in ISO 8601 format. - **icon** (string) - An emoji representing the event category. - **impactLevel** (string) - The potential impact level on tweet activity. - **lastUpdated** (string) - The timestamp when the event data was last updated. #### Response Example ```json { "upcoming": [ { "type": "spacex", "title": "Starship Flight 6", "date": "2025-12-15T10:00:00.000Z", "description": "Rocket launch", "source": "SpaceX API", "icon": "๐Ÿš€", "impactLevel": "high", "historicalImpact": "+35% tweet activity on launch days" }, { "type": "tesla", "title": "Tesla Q4 2024 Earnings Call", "date": "2025-01-29T22:00:00Z", "description": "Quarterly earnings report and investor call", "source": "Tesla IR", "icon": "๐Ÿ“ˆ", "impactLevel": "high", "historicalImpact": "+40% tweet activity on earnings days" } ], "past": [ { "type": "politics", "title": "Trump Inauguration", "date": "2025-01-20T17:00:00.000Z", "icon": "๐Ÿ‡บ๐Ÿ‡ธ", "impactLevel": "high" } ], "lastUpdated": "2025-11-30T06:00:00.000Z" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.