---
name: TikTok Trends
description: Fetch top trending TikTok videos for a given country and generate an engagement report with optional video downloads.
version: 2
author: pastilhas
tags:
  - social-media
  - tiktok
  - trends
  - apify
  - content-analysis
skills:
  - Apify
dependencies:
  - name: tiktok-trends-script
    description: The main script at $OFFICER_USER_ROOT/../resources/scripts/apify/tiktok-trends.ts
    check_command: test -f "$OFFICER_USER_ROOT/../resources/scripts/apify/tiktok-trends.ts"
    optional: false
  - name: bun
    description: Required to run the TypeScript script
    check_command: bun --version
    optional: false
  - name: yt-dlp
    description: Required only when download option is enabled. Downloads TikTok videos.
    check_command: yt-dlp --version
    optional: true
inputs:
  - name: country
    description: Country code to fetch trending videos for.
    type: select
    default: PT
    required: false
    options:
      - value: PT
        label: Portugal
      - value: US
        label: United States
      - value: BR
        label: Brazil
      - value: GB
        label: United Kingdom
      - value: ES
        label: Spain
      - value: FR
        label: France
      - value: DE
        label: Germany
      - value: IT
        label: Italy
      - value: NL
        label: Netherlands
      - value: BE
        label: Belgium
      - value: PL
        label: Poland
      - value: RO
        label: Romania
      - value: SE
        label: Sweden
      - value: AT
        label: Austria
      - value: CH
        label: Switzerland
      - value: IE
        label: Ireland
      - value: CA
        label: Canada
      - value: AU
        label: Australia
      - value: MX
        label: Mexico
      - value: AR
        label: Argentina
      - value: CO
        label: Colombia
      - value: CL
        label: Chile
      - value: JP
        label: Japan
      - value: KR
        label: South Korea
      - value: IN
        label: India
      - value: TR
        label: Turkey
      - value: SA
        label: Saudi Arabia
      - value: AE
        label: United Arab Emirates
      - value: ZA
        label: South Africa
      - value: NG
        label: Nigeria
  - name: limit
    description: Number of trending videos to fetch (1-100).
    type: number
    default: 20
    min: 1
    max: 100
    required: false
  - name: download
    description: Download video files using yt-dlp (requires yt-dlp to be installed).
    type: boolean
    default: false
    required: false
  - name: api_token
    description: Apify API token with access to actors. Get yours at https://console.apify.com/account/integrations
    type: string
    required: true
    sensitive: true
outputs:
  - name: engagement_report
    description: Markdown report with trending videos analysis, engagement metrics, top hashtags, sounds, and creators.
    path: tiktok_trends_<country>_<timestamp>/report-YYYY-MM-DD.md
  - name: raw_data
    description: Raw JSON data from Apify actor containing all video metadata.
    path: tiktok_trends_<country>_<timestamp>/raw-YYYY-MM-DD.json
  - name: execution_log
    description: Complete script execution log with stdout and stderr for debugging.
    path: tiktok_trends_<country>_<timestamp>/run.log
  - name: summary
    description: Human-readable summary of the run including cost analysis and file listing.
    path: tiktok_trends_<country>_<timestamp>/report.md
  - name: videos
    description: Downloaded video files with metadata (only present if download option was enabled).
    path: tiktok_trends_<country>_<timestamp>/videos/
    optional: true
config:
  timeout: 600
  retry_count: 0
---

# TikTok Trends

Fetch top trending TikTok videos for a given country and generate a comprehensive engagement report.

## Overview

This task uses the Apify `novi~fast-tiktok-scraper` actor to fetch trending videos from TikTok for a specified country. It generates:
- **Engagement metrics** (total/average views, likes, shares, comments)
- **Top hashtags** found in trending content
- **Popular sounds** being used
- **Creator analysis** (who appears multiple times in trending)
- **Complete video list** with links and stats

Optionally downloads videos using yt-dlp for offline analysis.

## Pre-execution Checks

1. **Validate inputs**:
   - `api_token` must be provided (required)
   - `country` must be a valid 2-letter country code
   - `limit` must be between 1-100
   
2. **Check dependencies**:
   - Verify script exists at `$OFFICER_USER_ROOT/../resources/scripts/apify/tiktok-trends.ts`
   - Verify bun is installed
   - If `download=true`, verify yt-dlp is installed

3. **Test Apify token**:
   - Make a test call to `GET https://api.apify.com/v2/users/me` to validate the token
   - Abort with clear error if token is invalid or account has no credits

## Execution

Run the script with the following command:

```bash
bun "$OFFICER_USER_ROOT/../resources/scripts/apify/tiktok-trends.ts" \
  --apikey "<api_token>" \
  --country "<country>" \
  --limit <limit> \
  --output "<output_dir>" \
  <download_flag>
```

Where:
- `<download_flag>` is `--download` if `download=true`, otherwise omitted
- `<output_dir>` is a timestamped directory created inside `$HOME/tiktok-trends/` (the logged-in user's home directory)

**Pipe output to log**:
```bash
<command_above> 2>&1 | tee "<output_dir>/run.log"
```

## Success Criteria

The task is considered successful when:
- Script exits with code 0
- `report-YYYY-MM-DD.md` exists and is non-empty
- `raw-YYYY-MM-DD.json` exists and contains valid JSON array
- (If download enabled) `videos/` directory exists with at least one file

## Error Handling

| Scenario | Action |
|----------|--------|
| Script exits non-zero | Check `run.log` for Apify/API errors. Common causes: invalid token, no credits, rate limits |
| Empty results | Report "No trending videos found" but mark as success if files were created |
| Partial results | Report success if at least 1 video returned, note the discrepancy |
| Timeout (>10 min) | Kill process, report timeout. Check Apify actor status in console |
| Download failures | Report which videos failed but mark task as success if main report generated |

## Post-execution

After successful execution:

1. **Verify outputs**:
   - Check all expected files exist
   - Validate JSON is parseable
   - If download enabled, count video files

2. **Generate summary** (`report.md`):
   ```markdown
   # TikTok Trends Run Summary

   ## Run Details
   - **Date**: YYYY-MM-DD
   - **Timestamp**: HH:MM:SS
   - **Apify Actor**: novi~fast-tiktok-scraper
   - **Country**: <country_name> (<country_code>)
   - **Requested**: <limit> videos
   - **Received**: <actual_count> videos
   - **Duration**: <X> minutes <Y> seconds

   ## Cost Analysis
   - **Apify Credits Used**: <cost> USD
   - **Cost per Video**: $<cost/actual_count>

   ## Key Findings
   - **Top Video**: @<creator> - <views> views
     <description_preview>
     URL: <url>
   
   - **Top Hashtag**: #<hashtag> (<count> occurrences)
   - **Top Sound**: <sound_name> (<count> uses)

   ## Output Files
   - `report-YYYY-MM-DD.md` (<size>) - Engagement report
   - `raw-YYYY-MM-DD.json` (<size>) - Raw API data
   - `run.log` (<size>) - Execution log
   - `videos/` (<count> files, <total_size>) - Downloaded videos (if enabled)

   ## Notes
   - <any_warnings_or_errors_from_log>
   ```

3. **Cleanup**:
   - Remove temporary files if any
   - Report final status to user

## Notes

- **Rate limiting**: The Apify actor may take 1-3 minutes depending on the limit
- **Costs**: Each run uses Apify compute units. Monitor usage at https://console.apify.com/billing
- **Data freshness**: Trends data is near real-time but may have slight delays
- **Video downloads**: Downloading many videos can take significant time and storage
- **Country availability**: Not all countries have sufficient trending data; some may return fewer results than requested
