CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tiktok-src

A tool for downloading TikTok videos with or without watermarks and automatically uploading them to Facebook Reels

Pending
Overview
Eval results
Files

telegram-bot.mddocs/

Telegram Bot

Complete Telegram bot implementation providing remote control interface for TikTok video downloading and Facebook Reels uploading. Features user rate limiting, download statistics tracking, and command handling for seamless remote operation.

Capabilities

Bot Initialization

Setup and configuration for the Telegram bot instance.

/**
 * Create and configure Telegram bot instance
 * Requires BOT_TOKEN environment variable
 */
const bot = new TeleBot({
  token: process.env.BOT_TOKEN
});

/**
 * Start the bot and begin listening for messages
 */
bot.start(): void;

Usage Examples:

import TeleBot from 'telebot';
import dotenv from 'dotenv';

dotenv.config();

// Initialize bot with token from environment
const bot = new TeleBot({
  token: process.env.BOT_TOKEN
});

// Start bot
bot.start();
console.log('Bot is running...');

User Statistics Management

Track user download activity and enforce daily limits.

/**
 * Update download statistics for a user
 * @param userId - Telegram user ID
 */
function updateUserStats(userId: number): void;

/**
 * Check if user can download (within daily limit)
 * @param userId - Telegram user ID
 * @returns Boolean indicating if user can download
 */
function canUserDownload(userId: number): boolean;

/** Maximum downloads allowed per user per day */
const MAX_DOWNLOADS_PER_DAY: number = 5;

/** User statistics storage */
const userStats: Map<number, UserStats>;

interface UserStats {
  /** Date of downloads (string format) */
  date: string;
  /** Number of downloads on this date */
  count: number;
}

Usage Examples:

// Check if user can download
const userId = 12345;
if (canUserDownload(userId)) {
  // Process download
  await handleTikTokUrl(msg, url);
  updateUserStats(userId);
} else {
  await bot.sendMessage(msg.chat.id, `You've reached the daily limit of ${MAX_DOWNLOADS_PER_DAY} downloads.`);
}

// Check user statistics
const stats = userStats.get(userId);
if (stats) {
  console.log(`User ${userId} has ${stats.count} downloads on ${stats.date}`);
}

Bot Commands

Available bot commands and their handlers.

/**
 * Handle start and help commands
 * Shows welcome message and usage instructions
 */
bot.on(['/start', '/help'], (msg) => void);

/**
 * Handle stats command
 * Shows user's download statistics for current day
 */
bot.on('/stats', (msg) => void);

/**
 * Handle text messages
 * Processes TikTok URLs automatically
 */
bot.on('text', async (msg) => void);

Usage Examples:

// User sends: /start
// Bot responds with:
`Welcome to TikTok Downloader Bot!

Commands:
/start or /help - Show this help message
/stats - Show your download statistics

To download a TikTok video, simply send the TikTok URL to the bot.

Note: You can download up to 5 videos per day.`

// User sends: /stats  
// Bot responds with:
`Today (2023-09-05) you've downloaded 3 videos.`
// or
`You haven't downloaded any videos today.`

Video Download Handling

Core functionality for processing TikTok URLs sent via bot messages.

/**
 * Download TikTok video with progress tracking and visual progress bar
 * @param url - TikTok video URL
 * @param outputPath - Local file path to save video
 * @returns Promise resolving when download completes
 * @throws Error if TikTok API fails or video unavailable
 */
async function downloadTikTokVideo(url: string, outputPath: string): Promise<void>;

/**
 * Complete workflow for processing TikTok URL from Telegram message
 * Includes rate limiting, download, upload, and cleanup
 * @param msg - Telegram message object containing user and chat info
 * @param url - Extracted TikTok URL to process
 * @returns Promise resolving when processing completes
 */
async function handleTikTokUrl(msg: TelegramMessage, url: string): Promise<void>;

Usage Examples:

// Complete workflow when user sends TikTok URL: https://vm.tiktok.com/ZSFxxxxxx/
// Bot automatically:
// 1. Checks user download limit (5 per day)
// 2. Sends "Processing..." reply message
// 3. Calls TiktokDL to get video metadata
// 4. Downloads video with progress bar using axios stream
// 5. Calls ReelsUpload with video filename and extracted caption
// 6. Sends success/failure message to user
// 7. Updates user statistics
// 8. Cleans up temporary files with fs.unlinkSync

// Internal download implementation
const outputPath = './download/video123.mp4';
try {
  const result = await TiktokDL(url);
  const video = result.result.video[0]; // First video URL
  const response = await axios({
    url: video,
    method: 'GET',
    responseType: 'stream'
  });
  
  // Progress bar setup
  const totalLength = response.headers['content-length'];
  const progressBar = new ProgressBar(progressTemplate, {
    width: 40,
    complete: '<',
    incomplete: '•',
    total: parseInt(totalLength)
  });
  
  await downloadTikTokVideo(url, outputPath);
} catch (error) {
  console.error('Download failed:', error);
}

Message Processing

Automatic URL detection and processing from user messages.

/** Regular expression for detecting TikTok URLs in messages */
const tiktokRegex: RegExp = /https?:\/\/(?:m|www|vm|vt)?\.?tiktok\.com\/\S+/;

/** Configuration constants */
const MAX_DOWNLOADS_PER_DAY: number = 5;
const userStats: Map<number, UserStats>;

interface TelegramMessage {
  /** Message text content */
  text: string;
  /** Sender information */
  from: {
    id: number;
    // ... other Telegram user properties
  };
  /** Chat information */
  chat: {
    id: number;
    // ... other Telegram chat properties
  };
  /** Message ID for replies */
  message_id: number;
}

URL Detection Examples:

// Supported URL formats
const supportedUrls = [
  'https://www.tiktok.com/@user/video/123',
  'https://vm.tiktok.com/ZSFxxxxxx/',
  'https://vt.tiktok.com/ZSFxxxxxx/',
  'https://m.tiktok.com/v/123.html',
  'https://tiktok.com/@user/video/123'
];

// All formats are automatically detected and processed

Bot Workflow

Complete processing workflow when user sends TikTok URL:

  1. URL Detection: Extract TikTok URL from message using regex
  2. Rate Limit Check: Verify user hasn't exceeded daily download limit
  3. Processing Message: Send "Processing..." reply to user
  4. Video Download: Use TiktokDL to get video metadata and download file
  5. Facebook Upload: Upload video to Facebook Reels with extracted caption
  6. Result Notification: Send success/failure message to user
  7. Statistics Update: Increment user's daily download count
  8. Cleanup: Remove temporary video file

Configuration Requirements

Environment Variables

/** Bot token from BotFather */
process.env.BOT_TOKEN: string;

Required Files and Setup

Environment Configuration:

  • .env file with BOT_TOKEN=your_telegram_bot_token
  • config.json with {"tokenBOT": "your_token"} (alternative to .env)

Facebook Integration:

  • cookies.json with exported Facebook session cookies
  • Valid Facebook account with Reels creation permissions

File System:

  • download/ directory for temporary file storage (auto-created)
  • Write permissions for video file management

External Dependencies:

  • Chrome/Chromium browser for Puppeteer
  • FFmpeg installed for video conversion (if used)

Bot Setup Process:

  1. Create bot with @BotFather on Telegram
  2. Copy bot token to .env or config.json
  3. Export Facebook cookies using browser extension
  4. Run node telebot.js to start bot
  5. Send /start to bot to verify functionality

Error Handling

The bot includes comprehensive error handling for various scenarios:

Rate Limiting:

// User exceeds daily limit
`You've reached the daily limit of 5 downloads.`

Processing Errors:

// General processing failure
`An error occurred: ${error.message}`

// TikTok API failures
// When TiktokDL returns error status
if (result.status === 'error') {
  // Handle specific TikTok API errors
}

Upload Failures:

// Facebook upload fails
`Upload failed: ${upload.message}`

// Specific upload error messages (in Indonesian)
"Video Gagal di publish!"           // "Video failed to publish!"
"INFO: Session tidak ditemukan..."  // "INFO: Session not found..."

Network and File Errors:

// Download failures
"Error downloading video: ${error.message}"

// File system errors during cleanup
// fs.unlinkSync may throw if file doesn't exist or permissions issue
try {
  fs.unlinkSync(outputPath);
} catch (cleanupError) {
  // Non-critical cleanup failure
}

Bot Statistics

The bot maintains daily download statistics for each user:

  • Automatic reset at midnight
  • Per-user tracking via Telegram user ID
  • Configurable daily limits
  • Persistent across bot restarts (in-memory storage)

Install with Tessl CLI

npx tessl i tessl/npm-tiktok-src

docs

facebook-upload.md

index.md

telegram-bot.md

tiktok-api.md

video-processing.md

tile.json