# 🎵 TikTok Scraper & Downloader Library



[![logo tt scrapenya](https://github.com/Habibzz01/XbibzAssets-/releases/download/Nexo444/ttscraper.png)](https://tiktok.com/@xbibzofficiall)

<h2 style="background: linear-gradient(120deg, #ff0050, #00f2ea); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 2.5em; margin: 20px 0;">
@xbibzlibrary/tiktokscrap
</h2>

<p style="font-size: 1.2em; color: #666; max-width: 600px; margin: 0 auto;">
🚀 Powerful, Modern & Feature-Rich TikTok Scraping & Downloading Library Built with TypeScript
</p>

<div style="margin: 30px 0;">
  <img src="https://img.shields.io/badge/TypeScript-007ACC?style=for-the-badge&logo=typescript&logoColor=white" alt="TypeScript">
  <img src="https://img.shields.io/badge/Node.js-339933?style=for-the-badge&logo=nodedotjs&logoColor=white" alt="Node.js">
  <img src="https://img.shields.io/badge/npm-CB3837?style=for-the-badge&logo=npm&logoColor=white" alt="npm">
  <img src="https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge" alt="License">
</div>

<div style="display: flex; justify-content: center; gap: 15px; margin: 20px 0;">
  <a href="#installation" style="text-decoration: none;">
    <img src="https://img.shields.io/badge/📦_Installation-blue?style=flat-square" alt="Installation">
  </a>
  <a href="#usage" style="text-decoration: none;">
    <img src="https://img.shields.io/badge/📖_Usage-green?style=flat-square" alt="Usage">
  </a>
  <a href="#api-documentation" style="text-decoration: none;">
    <img src="https://img.shields.io/badge/📚_API_Docs-orange?style=flat-square" alt="API Docs">
  </a>
  <a href="#examples" style="text-decoration: none;">
    <img src="https://img.shields.io/badge/💡_Examples-purple?style=flat-square" alt="Examples">
  </a>
</div>

</div>

---

## ✨ Features

<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin: 30px 0;">

<div style="padding: 20px; border-left: 4px solid #ff0050; background: #f9f9f9; border-radius: 8px;">
  <h3>🎬 Video Scraping</h3>
  <ul style="list-style: none; padding-left: 0;">
    <li>✓ Scrape by URL or ID</li>
    <li>✓ Get trending videos</li>
    <li>✓ Recommended videos</li>
    <li>✓ Full metadata extraction</li>
  </ul>
</div>

<div style="padding: 20px; border-left: 4px solid #00f2ea; background: #f9f9f9; border-radius: 8px;">
  <h3>📸 Photo Scraping</h3>
  <ul style="list-style: none; padding-left: 0;">
    <li>✓ Multi-photo post support</li>
    <li>✓ High-quality images</li>
    <li>✓ Photo trends & recommendations</li>
    <li>✓ Complete metadata</li>
  </ul>
</div>

<div style="padding: 20px; border-left: 4px solid #69c9d0; background: #f9f9f9; border-radius: 8px;">
  <h3>👤 User Scraping</h3>
  <ul style="list-style: none; padding-left: 0;">
    <li>✓ Profile information</li>
    <li>✓ User posts & likes</li>
    <li>✓ Follower statistics</li>
    <li>✓ Feed pagination</li>
  </ul>
</div>

<div style="padding: 20px; border-left: 4px solid #ee1d52; background: #f9f9f9; border-radius: 8px;">
  <h3>#️⃣ Hashtag Scraping</h3>
  <ul style="list-style: none; padding-left: 0;">
    <li>✓ Hashtag feed</li>
    <li>✓ Trending hashtags</li>
    <li>✓ Challenge data</li>
    <li>✓ View count & stats</li>
  </ul>
</div>

<div style="padding: 20px; border-left: 4px solid #ff6b6b; background: #f9f9f9; border-radius: 8px;">
  <h3>⬇️ Smart Downloading</h3>
  <ul style="list-style: none; padding-left: 0;">
    <li>✓ Video & photo downloads</li>
    <li>✓ Progress tracking</li>
    <li>✓ Custom output paths</li>
    <li>✓ Batch downloads</li>
  </ul>
</div>

<div style="padding: 20px; border-left: 4px solid #4ecdc4; background: #f9f9f9; border-radius: 8px;">
  <h3>🛠️ Advanced Features</h3>
  <ul style="list-style: none; padding-left: 0;">
    <li>✓ Proxy support</li>
    <li>✓ Retry mechanism</li>
    <li>✓ Error handling</li>
    <li>✓ Custom headers</li>
  </ul>
</div>

</div>

---

## 📦 Installation

```bash
# Using npm
npm install @xbibzlibrary/tiktokscrap

# Using yarn
yarn add @xbibzlibrary/tiktokscrap

# Using pnpm
pnpm add @xbibzlibrary/tiktokscrap
```

---

## 🚀 Quick Start

```typescript
import TikTokScrap from '@xbibzlibrary/tiktokscrap';

// Initialize the library
const tiktok = new TikTokScrap();

// Get video information
const video = await tiktok.getVideoByUrl('https://www.tiktok.com/@username/video/1234567890');

if (video.success) {
  console.log('📹 Video Title:', video.data.text);
  console.log('👤 Author:', video.data.author.nickname);
  console.log('❤️ Likes:', video.data.stats.digg);
  
  // Download the video
  await tiktok.downloadVideo(video.data, {
    outputDir: './downloads',
    progressCallback: (progress) => console.log(`⏬ Progress: ${progress}%`)
  });
}
```

---

## 📖 Usage

### 🎬 Video Operations

<details open>
<summary><b>Get Video by URL</b></summary>

```typescript
const result = await tiktok.getVideoByUrl('https://www.tiktok.com/@user/video/123456');

if (result.success) {
  console.log('Video Data:', result.data);
  // Access: id, text, author, music, stats, videoMeta, hashtags, etc.
}
```

</details>

<details>
<summary><b>Get Video by ID</b></summary>

```typescript
const result = await tiktok.getVideoById('1234567890123456789');

if (result.success) {
  const video = result.data;
  console.log(`Title: ${video.text}`);
  console.log(`Duration: ${video.videoMeta.duration}s`);
  console.log(`Views: ${video.stats.play}`);
}
```

</details>

<details>
<summary><b>Get Trending Videos</b></summary>

```typescript
const trending = await tiktok.getVideoTrends(20); // Get top 20

if (trending.success) {
  trending.data.forEach(video => {
    console.log(`🔥 ${video.text} - ${video.stats.play} views`);
  });
}
```

</details>

<details>
<summary><b>Get Recommended Videos</b></summary>

```typescript
const recommended = await tiktok.getRecommendedVideos('videoId', 10);

if (recommended.success) {
  console.log(`Found ${recommended.data.length} recommended videos`);
}
```

</details>

### 📸 Photo Operations

<details>
<summary><b>Get Photo by URL</b></summary>

```typescript
const result = await tiktok.getPhotoByUrl('https://www.tiktok.com/@user/photo/123456');

if (result.success) {
  const photo = result.data;
  console.log(`Photos in post: ${photo.covers.length}`);
  photo.covers.forEach((cover, i) => {
    console.log(`Photo ${i + 1}: ${cover.url}`);
  });
}
```

</details>

<details>
<summary><b>Download Photos</b></summary>

```typescript
const photoResult = await tiktok.getPhotoByUrl('https://www.tiktok.com/@user/photo/123456');

if (photoResult.success) {
  const downloaded = await tiktok.downloadPhoto(photoResult.data, {
    outputDir: './photos',
    filename: 'my-tiktok-photo',
    progressCallback: (progress) => {
      console.log(`📥 Downloading: ${progress}%`);
    }
  });
  
  if (downloaded.success) {
    console.log(`✅ Downloaded ${downloaded.data.length} photos!`);
  }
}
```

</details>

### 👤 User Operations

<details>
<summary><b>Get User Profile</b></summary>

```typescript
const user = await tiktok.getUserByUsername('@username');

if (user.success) {
  const profile = user.data;
  console.log(`Name: ${profile.nickname}`);
  console.log(`Followers: ${profile.fans}`);
  console.log(`Following: ${profile.following}`);
  console.log(`Total Likes: ${profile.heart}`);
  console.log(`Videos: ${profile.video}`);
}
```

</details>

<details>
<summary><b>Get User Videos</b></summary>

```typescript
const videos = await tiktok.getUserVideos('@username', 0, 30);

if (videos.success) {
  videos.data.forEach(video => {
    console.log(`📹 ${video.text}`);
    console.log(`   ❤️ ${video.stats.digg} | 💬 ${video.stats.comment}`);
  });
}
```

</details>

<details>
<summary><b>Get User Feed (Videos & Photos)</b></summary>

```typescript
const feed = await tiktok.getUserFeed({
  username: '@username',
  cursor: 0,
  count: 20,
  type: 'post' // or 'like'
});

if (feed.success) {
  console.log(`Found ${feed.data.length} posts`);
}
```

</details>

### #️⃣ Hashtag Operations

<details>
<summary><b>Get Hashtag Info</b></summary>

```typescript
const hashtag = await tiktok.getHashtagByName('#fyp');

if (hashtag.success) {
  const tag = hashtag.data;
  console.log(`Title: ${tag.title}`);
  console.log(`Views: ${tag.viewCount}`);
  console.log(`Description: ${tag.description}`);
}
```

</details>

<details>
<summary><b>Get Hashtag Videos</b></summary>

```typescript
const videos = await tiktok.getHashtagVideos('#dance', 0, 50);

if (videos.success) {
  console.log(`Found ${videos.data.length} videos with #dance`);
}
```

</details>

<details>
<summary><b>Get Trending Hashtags</b></summary>

```typescript
const trending = await tiktok.getTrendingHashtags(10);

if (trending.success) {
  trending.data.forEach((tag, i) => {
    console.log(`${i + 1}. #${tag.name} - ${tag.viewCount} views`);
  });
}
```

</details>

### ⬇️ Download Operations

<details>
<summary><b>Download Video</b></summary>

```typescript
const video = await tiktok.getVideoByUrl('https://www.tiktok.com/@user/video/123');

if (video.success) {
  const download = await tiktok.downloadVideo(video.data, {
    outputDir: './downloads',
    filename: 'my-video.mp4',
    progressCallback: (progress) => {
      console.log(`⏬ ${progress}%`);
    }
  });
  
  if (download.success) {
    console.log(`✅ Saved to: ${download.data}`);
  }
}
```

</details>

<details>
<summary><b>Download Video by URL (Direct)</b></summary>

```typescript
const download = await tiktok.downloadVideoByUrl(
  'https://www.tiktok.com/@user/video/123',
  {
    outputDir: './downloads',
    progressCallback: (progress) => console.log(`${progress}%`)
  }
);
```

</details>

<details>
<summary><b>Batch Download</b></summary>

```typescript
const videos = await tiktok.getUserVideos('@username', 0, 10);

if (videos.success) {
  for (const video of videos.data) {
    await tiktok.downloadVideo(video, {
      outputDir: './batch-downloads',
      filename: `${video.id}.mp4`
    });
  }
}
```

</details>

---

## 🎯 API Documentation

### Constructor Options

```typescript
interface TikTokScrapOptions {
  timeout?: number;           // Request timeout (default: 30000ms)
  retries?: number;           // Retry attempts (default: 3)
  userAgent?: string;         // Custom user agent
  proxy?: {                   // Proxy configuration
    host: string;
    port: number;
    auth?: {
      username: string;
      password: string;
    };
  };
  headers?: Record<string, string>; // Custom headers
}

// Usage
const tiktok = new TikTokScrap({
  timeout: 60000,
  retries: 5,
  proxy: {
    host: '127.0.0.1',
    port: 8080
  }
});
```

### Response Structure

```typescript
interface TikTokScrapResult<T> {
  success: boolean;    // Request success status
  data?: T;           // Response data (if successful)
  error?: string;     // Error message (if failed)
  message?: string;   // Status message
}
```

### Video Data Structure

```typescript
interface TikTokVideo {
  id: string;                    // Video ID
  text: string;                  // Video caption/description
  createTime: number;            // Upload timestamp
  author: TikTokUser;            // Author information
  music: {                       // Music information
    id: string;
    title: string;
    author: string;
    playUrl: string;
  };
  stats: {                       // Video statistics
    digg: number;                // Likes
    share: number;               // Shares
    comment: number;             // Comments
    play: number;                // Views
  };
  videoMeta: {                   // Video metadata
    width: number;
    height: number;
    duration: number;
    cover: string;               // Cover image URL
  };
  downloadAddr: string;          // Direct download URL
  hashtags: Array<{}>;           // Hashtags used
  // ... more fields
}
```

---

## 💡 Advanced Examples

### 🔄 Error Handling

```typescript
try {
  const video = await tiktok.getVideoByUrl('invalid-url');
  
  if (!video.success) {
    console.error('Error:', video.error);
    console.error('Message:', video.message);
  }
} catch (error) {
  console.error('Exception:', error.message);
}
```

### 🔁 Pagination

```typescript
let cursor = 0;
let allVideos = [];

while (cursor < 100) {
  const result = await tiktok.getUserVideos('@username', cursor, 20);
  
  if (!result.success || result.data.length === 0) break;
  
  allVideos.push(...result.data);
  cursor += 20;
  
  // Rate limiting
  await new Promise(resolve => setTimeout(resolve, 1000));
}

console.log(`Total videos collected: ${allVideos.length}`);
```

### 📊 Statistics Collection

```typescript
const user = await tiktok.getUserByUsername('@username');

if (user.success) {
  const videos = await tiktok.getUserVideos('@username', 0, 100);
  
  if (videos.success) {
    const totalLikes = videos.data.reduce((sum, v) => sum + v.stats.digg, 0);
    const totalViews = videos.data.reduce((sum, v) => sum + v.stats.play, 0);
    const avgLikes = totalLikes / videos.data.length;
    
    console.log(`📊 Statistics for @${user.data.uniqueId}`);
    console.log(`Total Videos: ${videos.data.length}`);
    console.log(`Total Likes: ${totalLikes.toLocaleString()}`);
    console.log(`Total Views: ${totalViews.toLocaleString()}`);
    console.log(`Average Likes: ${avgLikes.toFixed(0)}`);
  }
}
```

### 🎯 Custom Configuration

```typescript
const tiktok = new TikTokScrap({
  timeout: 60000,
  retries: 5,
  headers: {
    'Accept-Language': 'id-ID,id;q=0.9',
    'Custom-Header': 'value'
  }
});

// Update configuration later
tiktok.updateOptions({
  timeout: 45000,
  retries: 3
});

// Get current configuration
const config = tiktok.getOptions();
console.log('Current config:', config);
```

### 🎨 Progress Bar Example

```typescript
import cliProgress from 'cli-progress';

const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);

const video = await tiktok.getVideoByUrl('https://...');

if (video.success) {
  progressBar.start(100, 0);
  
  await tiktok.downloadVideo(video.data, {
    outputDir: './downloads',
    progressCallback: (progress) => {
      progressBar.update(progress);
    }
  });
  
  progressBar.stop();
  console.log('✅ Download complete!');
}
```

---

## 🏗️ Architecture

```
@xbibzlibrary/tiktokscrap
├── 🎬 Scrapers
│   ├── VideoScraper    → Video content scraping
│   ├── PhotoScraper    → Photo content scraping
│   ├── UserScraper     → User profile & feed
│   └── HashtagScraper  → Hashtag & trends
│
├── ⬇️ Downloaders
│   ├── VideoDownloader → Video file downloads
│   └── PhotoDownloader → Photo downloads
│
├── 🛠️ Utilities
│   ├── HttpClient      → HTTP requests & retries
│   ├── Parser          → HTML/JSON parsing
│   ├── Validator       → Input validation
│   └── Logger          → Logging system
│
└── 🎯 Core
    ├── Types           → TypeScript definitions
    └── Errors          → Custom error classes
```

---

## 🤝 Contributing

Contributions are welcome! Feel free to:

- 🐛 Report bugs
- 💡 Suggest new features
- 🔧 Submit pull requests
- 📖 Improve documentation

---

## 📄 License

This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.

---

## 👨‍💻 Author

<div align="center" style="margin: 40px 0;">

<img src="https://github.com/Habibzz01/XbibzAssets-/releases/download/Nexo444/mylogobulat.png" width="100" height="100" style="border-radius: 50%; border: 3px solid #ff0050;">

### Xbibz Official

<div style="margin: 20px 0;">
  <a href="https://t.me/XbibzOfficial" style="text-decoration: none;">
    <img src="https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white" alt="Telegram">
  </a>
  <a href="https://tiktok.com/@xbibzofficiall" style="text-decoration: none;">
    <img src="https://img.shields.io/badge/TikTok-000000?style=for-the-badge&logo=tiktok&logoColor=white" alt="TikTok">
  </a>
  <a href="https://ko-fi.com/XbibzOfficial" style="text-decoration: none;">
    <img src="https://img.shields.io/badge/Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white" alt="Ko-fi">
  </a>
</div>

<p style="color: #666; font-size: 0.9em;">
💖 If this library helps you, consider supporting me!
</p>

</div>

---

## ⚠️ Disclaimer

This library is for **educational purposes only**. Please respect TikTok's Terms of Service and use this library responsibly. The author is not responsible for any misuse of this library.

---

<div align="center" style="margin-top: 50px; padding: 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white;">

<h2 style="margin: 0;">🌟 Star this project if you find it useful! 🌟</h2>

<p style="margin: 20px 0 0 0; opacity: 0.9;">
Made with ❤️ by Xbibz Official
</p>

</div>

---

## 📊 Project Stats

<div align="center">

![GitHub stars](https://img.shields.io/github/stars/XbibzOfficial/tiktokscrap?style=social)
![GitHub forks](https://img.shields.io/github/forks/XbibzOfficial/tiktokscrap?style=social)
![GitHub issues](https://img.shields.io/github/issues/XbibzOfficial/tiktokscrap)
![npm downloads](https://img.shields.io/npm/dm/@xbibzlibrary/tiktokscrap)
![npm version](https://img.shields.io/npm/v/@xbibzlibrary/tiktokscrap)

</div>
