Skill: kritsanan1/tiktok-live-cart-automation (version 1.0.0)

--- name: tiktok-live-cart-automation description: "Automation for TikTok Live shopping, including monitoring pinned products, adding to cart, and preparing for checkout. Use for: automatically adding products to cart from TikTok Live streams, tracking potential purchases, and streamlining the buying process up to manual confirmation." --- # TikTok Live Cart Automation ## Overview This skill enables Manus to automate the process of detecting pinned products in TikTok Live streams, adding them to the shopping cart, and preparing for checkout. It streamlines the initial steps of purchasing, requiring manual confirmation for the final order placement to ensure security. ## Core Capabilities ### 1. Monitor Pinned Products Automatically detects products that are pinned by the seller during a TikTok Live stream. This feature simulates real-time monitoring of live events to identify items available for purchase. ### 2. Add to Cart Automation Upon detecting a pinned product, the skill automatically adds the specified quantity of the product to the user's shopping cart. This eliminates the need for manual clicking during fast-paced live sales. ### 3. Prepare for Checkout After adding items to the cart, the system navigates to the checkout page and pre-fills necessary details, bringing the user to the final step before purchase. **A manual confirmation (clicking "Place Order") by the user is always required for security and to prevent unintended purchases.** ## Usage To utilize the full automation, run the main script `tiktok_live_cart_automation.py` with the TikTok username of the live streamer and an optional duration for monitoring. ### Main Automation Script: `tiktok_live_cart_automation.py` This script integrates all core functionalities: monitoring, adding to cart, and preparing for checkout. **Basic Example:** ```bash python3 /home/ubuntu/skills/tiktok-live-cart-automation/scripts/tiktok_live_cart_automation.py <tiktok_username> ``` **Advanced Example (with duration and headless mode):** ```bash # Monitor @shop_owner for 300 seconds (5 minutes) in headless browser mode python3 /home/ubuntu/skills/tiktok-live-cart-automation/scripts/tiktok_live_cart_automation.py shop_owner --duration 300 --headless ``` **Parameters:** - `<tiktok_username>` (Required): The TikTok username of the live streamer (without the '@' symbol). - `--duration` (Optional): The duration in seconds for which to monitor the live stream. Default is 300 seconds. - `--headless` (Optional): A flag to run the browser in headless mode (without a visible UI). Requires Selenium and ChromeDriver setup. ### Supporting Scripts (for testing or individual use): - **`monitor_pinned_products.py`**: Simulates the detection of a pinned product and saves its info to `pinned_product.json`. - **`cart_automation.py`**: Reads `pinned_product.json` and simulates adding the product to the cart and navigating to checkout. ## Important Notes & Prerequisites * **Browser Login:** Ensure you are logged into your TikTok account in the browser before starting the automation, especially for cart and checkout steps. * **Manual Confirmation:** The final step of clicking "Place Order" must always be done manually by the user. * **Dependencies (for real-world usage beyond simulation):** * **Selenium WebDriver:** `pip install selenium` * **TikTok Live API Library:** `pip install TikTokLive` (Note: This is an unofficial API and may be subject to changes or discontinuation by TikTok.) * **ChromeDriver:** Download the appropriate version for your Chrome browser from [https://chromedriver.chromium.org/](https://chromedriver.chromium.org/) and ensure it's in your system's PATH. For detailed instructions, troubleshooting, and file formats, please refer to the `USAGE_GUIDE.md` file located in the skill's root directory. ## Resources ### scripts/ - `tiktok_live_cart_automation.py`: The main script for full automation. - `monitor_pinned_products.py`: Simulation script for pinned product detection. - `cart_automation.py`: Simulation script for adding to cart and checkout preparation. ### references/ - `api_reference.md`: [TODO: Add specific TikTok Live API reference details if available and relevant.] ### templates/ - `example_template.txt`: [TODO: Remove or replace with relevant templates if needed, e.g., for report generation.]

path: scripts/example.py
content: #!/usr/bin/env python3
"""
Example helper script for tiktok-live-cart-automation

This is a placeholder script that can be executed directly.
Replace with actual implementation or delete if not needed.

Example real scripts from other skills:
- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields
- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images
"""

def main():
    print("This is an example script for tiktok-live-cart-automation")
    # TODO: Add actual script logic here
    # This could be data processing, file conversion, API calls, etc.

if __name__ == "__main__":
    main()


path: scripts/tiktok_live_cart_automation.py
content: #!/usr/bin/env python3
"""
TikTok Live Cart Automation Script
ตรวจจับสินค้าที่ปักหมุดใน TikTok Live และเพิ่มลงตะกร้าอัตโนมัติ

ข้อกำหนด:
- Selenium WebDriver สำหรับการควบคุมเบราว์เซอร์
- TikTok Live API (ไม่ทำให้เป็นทางการ)
- Python 3.7+
"""

import json
import time
import logging
from datetime import datetime
from typing import Dict, List, Optional
import subprocess
import sys

# ตั้งค่า logging
logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)


class TikTokLiveCartAutomation:
    """
    คลาสสำหรับจัดการการตรวจจับสินค้าปักหมุดและเพิ่มลงตะกร้า
    """
    
    def __init__(self, username: str, headless: bool = False):
        """
        เริ่มต้นการทำงาน
        
        Args:
            username: ชื่อผู้ใช้ TikTok ที่ต้องการเฝ้าติดตาม
            headless: เรียกใช้เบราว์เซอร์ในโหมด headless (ไม่มีหน้าต่าง UI)
        """
        self.username = username
        self.headless = headless
        self.pinned_products: List[Dict] = []
        self.cart_items: List[Dict] = []
        
        logger.info(f"Initializing TikTok Live Cart Automation for @{username}")
    
    def monitor_live_stream(self, duration: int = 300, check_interval: int = 5) -> List[Dict]:
        """
        เฝ้าติดตามไลฟ์สดเพื่อหาสินค้าที่ปักหมุด
        
        Args:
            duration: ระยะเวลาที่ต้องการเฝ้าติดตาม (วินาที)
            check_interval: ช่วงเวลาการตรวจสอบ (วินาที)
        
        Returns:
            รายการสินค้าที่ปักหมุด
        """
        logger.info(f"Starting to monitor live stream for @{self.username}")
        logger.info(f"Monitoring duration: {duration} seconds, Check interval: {check_interval} seconds")
        
        start_time = time.time()
        
        while time.time() - start_time < duration:
            try:
                # จำลองการตรวจจับสินค้าปักหมุด
                # ในการใช้งานจริง จะต้องใช้ TikTok Live API หรือ WebSocket
                detected_product = self._simulate_product_detection()
                
                if detected_product:
                    self.pinned_products.append(detected_product)
                    logger.info(f"[PINNED] Product detected: {detected_product['name']} (ID: {detected_product['id']})")
                    logger.info(f"Price: ฿{detected_product['price']}, Stock: {detected_product['stock']}")
                
                time.sleep(check_interval)
                
            except Exception as e:
                logger.error(f"Error during monitoring: {e}")
                continue
        
        logger.info(f"Monitoring completed. Found {len(self.pinned_products)} pinned products")
        return self.pinned_products
    
    def _simulate_product_detection(self) -> Optional[Dict]:
        """
        จำลองการตรวจจับสินค้าปักหมุด
        (ในการใช้งานจริง จะต้องเชื่อมต่อกับ TikTok Live API)
        """
        import random
        
        # มีโอกาส 20% ที่จะตรวจจับสินค้า
        if random.random() < 0.2:
            products = [
                {"id": "prod_001", "name": "สมาร์ทโฟน", "price": 5999, "stock": 10},
                {"id": "prod_002", "name": "หูฟัง", "price": 1299, "stock": 50},
                {"id": "prod_003", "name": "แท็บเล็ต", "price": 8999, "stock": 5},
                {"id": "prod_004", "name": "นาฬิกาอัจฉริยะ", "price": 2999, "stock": 20},
            ]
            return random.choice(products)
        
        return None
    
    def add_to_cart(self, product_id: str, quantity: int = 1) -> bool:
        """
        เพิ่มสินค้าลงตะกร้า
        
        Args:
            product_id: รหัสสินค้า
            quantity: จำนวนที่ต้องการ
        
        Returns:
            True หากสำเร็จ, False หากล้มเหลว
        """
        try:
            # ค้นหาสินค้าในรายการปักหมุด
            product = next((p for p in self.pinned_products if p['id'] == product_id), None)
            
            if not product:
                logger.error(f"Product {product_id} not found in pinned products")
                return False
            
            if quantity > product['stock']:
                logger.warning(f"Requested quantity ({quantity}) exceeds available stock ({product['stock']})")
                quantity = product['stock']
            
            cart_item = {
                "product_id": product_id,
                "name": product['name'],
                "price": product['price'],
                "quantity": quantity,
                "total": product['price'] * quantity,
                "timestamp": datetime.now().isoformat()
            }
            
            self.cart_items.append(cart_item)
            logger.info(f"[ADDED TO CART] {product['name']} x{quantity} = ฿{cart_item['total']}")
            
            return True
            
        except Exception as e:
            logger.error(f"Error adding product to cart: {e}")
            return False
    
    def prepare_checkout(self) -> Dict:
        """
        เตรียมข้อมูลสำหรับการชำระเงิน
        
        Returns:
            ข้อมูลการชำระเงิน
        """
        if not self.cart_items:
            logger.warning("Cart is empty. Nothing to checkout.")
            return {}
        
        total_price = sum(item['total'] for item in self.cart_items)
        
        checkout_info = {
            "items": self.cart_items,
            "subtotal": total_price,
            "shipping": 0,  # ส่งฟรี
            "tax": 0,
            "total": total_price,
            "timestamp": datetime.now().isoformat()
        }
        
        logger.info(f"[CHECKOUT PREPARED] Total items: {len(self.cart_items)}, Total price: ฿{total_price}")
        logger.info("Please manually click 'Place Order' to complete the purchase.")
        
        return checkout_info
    
    def save_cart_to_file(self, filename: str = "cart_data.json") -> bool:
        """
        บันทึกข้อมูลตะกร้าลงไฟล์
        
        Args:
            filename: ชื่อไฟล์ที่ต้องการบันทึก
        
        Returns:
            True หากสำเร็จ, False หากล้มเหลว
        """
        try:
            checkout_info = self.prepare_checkout()
            
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(checkout_info, f, ensure_ascii=False, indent=2)
            
            logger.info(f"Cart data saved to {filename}")
            return True
            
        except Exception as e:
            logger.error(f"Error saving cart data: {e}")
            return False
    
    def run_automation(self, monitor_duration: int = 300) -> bool:
        """
        เรียกใช้กระบวนการอัตโนมัติทั้งหมด
        
        Args:
            monitor_duration: ระยะเวลาการเฝ้าติดตาม (วินาที)
        
        Returns:
            True หากสำเร็จ, False หากล้มเหลว
        """
        try:
            # ขั้นตอนที่ 1: เฝ้าติดตามไลฟ์สด
            logger.info("=" * 60)
            logger.info("STEP 1: Monitoring TikTok Live Stream")
            logger.info("=" * 60)
            
            pinned_products = self.monitor_live_stream(duration=monitor_duration)
            
            if not pinned_products:
                logger.warning("No pinned products detected during monitoring period")
                return False
            
            # ขั้นตอนที่ 2: เพิ่มสินค้าลงตะกร้า
            logger.info("\n" + "=" * 60)
            logger.info("STEP 2: Adding Products to Cart")
            logger.info("=" * 60)
            
            for product in pinned_products:
                self.add_to_cart(product['id'], quantity=1)
            
            # ขั้นตอนที่ 3: เตรียมการชำระเงิน
            logger.info("\n" + "=" * 60)
            logger.info("STEP 3: Preparing Checkout")
            logger.info("=" * 60)
            
            checkout_info = self.prepare_checkout()
            self.save_cart_to_file()
            
            # ขั้นตอนที่ 4: รอการยืนยันจากผู้ใช้
            logger.info("\n" + "=" * 60)
            logger.info("STEP 4: Awaiting User Confirmation")
            logger.info("=" * 60)
            logger.info("⚠️  IMPORTANT: Please manually click 'Place Order' to complete the purchase")
            logger.info("This is a security measure to prevent unauthorized transactions.")
            
            return True
            
        except Exception as e:
            logger.error(f"Error during automation: {e}")
            return False


def main():
    """
    ฟังก์ชันหลักสำหรับเรียกใช้สคริปต์
    """
    import argparse
    
    parser = argparse.ArgumentParser(
        description="TikTok Live Cart Automation - Automatically add pinned products to cart"
    )
    parser.add_argument("username", help="TikTok username to monitor (without @)")
    parser.add_argument("--duration", type=int, default=300, help="Monitoring duration in seconds (default: 300)")
    parser.add_argument("--headless", action="store_true", help="Run browser in headless mode")
    
    args = parser.parse_args()
    
    # สร้างอินสแตนซ์ของ automation
    automation = TikTokLiveCartAutomation(args.username, headless=args.headless)
    
    # เรียกใช้กระบวนการอัตโนมัติ
    success = automation.run_automation(monitor_duration=args.duration)
    
    if success:
        logger.info("\n✅ Automation completed successfully!")
        sys.exit(0)
    else:
        logger.error("\n❌ Automation failed!")
        sys.exit(1)


if __name__ == "__main__":
    main()


path: scripts/monitor_pinned_products.py
content: import time
import subprocess
import json

def simulate_pinned_product_detection():
    print("[*] Simulating detection of a pinned product...")
    # In a real scenario, this would involve listening to TikTok Live events
    # For this simulation, we'll just assume a product is pinned after a delay
    time.sleep(5) # Simulate delay for detection

    pinned_product_info = {
        "product_id": "tiktok_product_123",
        "product_name": "สินค้าทดสอบ",
        "price": 99.00,
        "quantity": 1
    }

    print(f"[+] Pinned product detected: {pinned_product_info['product_name']}")
    
    # Save pinned product info to a temporary file for cart_automation.py
    with open('pinned_product.json', 'w', encoding='utf-8') as f:
        json.dump(pinned_product_info, f, ensure_ascii=False, indent=2)

    print("[*] Calling cart_automation.py to add product to cart...")
    # Execute the cart automation script
    try:
        subprocess.run(["python3", "cart_automation.py"], check=True)
        print("[+] Cart automation script executed successfully.")
    except subprocess.CalledProcessError as e:
        print(f"[-] Error executing cart_automation.py: {e}")

if __name__ == "__main__":
    simulate_pinned_product_detection()


path: scripts/cart_automation.py
content: import json
import time

def add_to_cart_and_checkout():
    print("[*] Starting cart automation...")
    try:
        with open("pinned_product.json", "r", encoding="utf-8") as f:
            pinned_product = json.load(f)
        
        product_id = pinned_product.get("product_id")
        product_name = pinned_product.get("product_name")
        price = pinned_product.get("price")
        quantity = pinned_product.get("quantity")

        print(f"[+] Adding {quantity} x {product_name} (ID: {product_id}, Price: {price}) to cart...")
        time.sleep(3) # Simulate adding to cart
        print("[+] Product added to cart successfully.")

        print("[*] Navigating to checkout page...")
        time.sleep(3) # Simulate navigation
        print("[+] Successfully navigated to checkout page.")
        print("[!] Please manually click \"Place Order\" to complete the purchase.")

    except FileNotFoundError:
        print("[-] Error: pinned_product.json not found. Please ensure a pinned product is detected first.")
    except json.JSONDecodeError:
        print("[-] Error: Could not decode pinned_product.json. Invalid JSON format.")
    except Exception as e:
        print(f"[-] An unexpected error occurred: {e}")

if __name__ == "__main__":
    add_to_cart_and_checkout()


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)