Upload trending Tiktok to Youtube Shorts per API

gstreamer

Active Member
146
2018
74
6,120
Here a simple pyhton script to grab tiktok videos and upload to youtube shorts
python
pip install TikTokApi google-api-python-client google-auth-oauthlib requests

create script

Code:
import os
import requests
from TikTokApi import TikTokApi
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

# Configuration
CLIENT_SECRET_FILE = 'client_secret.json'
SCOPES = ['https://www.googleapis.com/auth/youtube.upload']
TIKTOK_SESSION_ID = "your_tiktok_session_id"  # Get from browser cookies

def get_tiktok_videos(count=10):
    """Fetch trending TikTok videos."""
    api = TikTokApi.get_instance()
    return api.by_trending(count=count)

def download_video(video_url, filename):
    """Download video from URL."""
    response = requests.get(video_url, stream=True)
    with open(filename, 'wb') as f:
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
    return filename

def get_no_watermark_url(video_id):
    """Get no-watermark URL (example; adjust as per API used)."""
    return f"https://api.tiktokv.com/aweme/v1/play/?video_id={video_id}"

def youtube_authenticate():
    """Authenticate with YouTube API."""
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
    creds = flow.run_local_server(port=0)
    return build('youtube', 'v3', credentials=creds)

def upload_youtube_short(youtube, file_path, title, description, tags):
    """Upload video to YouTube Shorts."""
    body = {
        'snippet': {
            'title': title,
            'description': description,
            'tags': tags,
            'categoryId': '24'
        },
        'status': {
            'privacyStatus': 'public'
        }
    }
    media = MediaFileUpload(file_path, chunksize=-1, resumable=True)
    request = youtube.videos().insert(part='snippet,status', body=body, media_body=media)
    return request.execute()

def main():
    # Fetch TikTok videos
    tiktok_videos = get_tiktok_videos(5)
    
    # Authenticate YouTube
    youtube = youtube_authenticate()
    
    for video in tiktok_videos:
        try:
            # Extract video details
            video_id = video['id']
            desc = video['desc']
            hashtags = [tag for tag in desc.split() if tag.startswith('#')]
            
            # Get no-watermark URL (adjust based on your method)
            video_url = get_no_watermark_url(video_id)
            
            # Download video
            filename = f"tiktok_{video_id}.mp4"
            download_video(video_url, filename)
            
            # Upload to YouTube
            response = upload_youtube_short(
                youtube,
                filename,
                title=f"TikTok Auto-Upload: {video_id}",
                description=desc + "\n" + " ".join(hashtags),
                tags=hashtags
            )
            print(f"Uploaded video ID: {response['id']}")
            
            # Cleanup
            os.remove(filename)
        except Exception as e:
            print(f"Error processing video {video_id}: {e}")

if __name__ == "__main__":
    main()

save it at .py file

Usage steps

  1. TikTok Download:

    • The get_no_watermark_url function is a placeholder. Use a reliable method (e.g., third-party API) to obtain no-watermark URLs, ensuring compliance with TikTok's policies.
    • Replace TIKTOK_SESSION_ID with your actual session cookie from TikTok.
  2. YouTube Upload:

    • Obtain client_secret.json from Google Cloud Console by creating an OAuth 2.0 Client ID.
    • Videos must be ≤60 seconds and vertical (9:16 aspect ratio) to qualify as Shorts
To use the google api

Create a Project in Google Cloud Console

  1. Go to the Google Cloud Console.
  2. Click the project dropdown (top left) → New Project.
  3. Name your project : TTtoYT Uploader→ Click Create.

Enable the YouTube Data API

  1. In your new project, go to APIs & Services → Library.
  2. Search for YouTube Data API v3 → Click Enable.

Configure OAuth Consent Screen

  1. Go to APIs & Services → OAuth Consent Screen.
  2. Select Internal (for personal use) or External (for public apps) → Click Create.
  3. Fill in:

    • App Name: Your app name (e.g., "TikTok to YouTube").
    • User Support Email: Your email.
    • Developer Contact Email: Your email.
  4. Click Save and Continue (skip optional scopes/fields for testing).

Create OAuth Client ID

  1. Go to APIs & Services → Credentials → Create Credentials → OAuth Client ID.
  2. For Application Type, select Desktop App.
  3. Give it a name (e.g., "YouTube Shorts Uploader").
  4. Click Create.

Download client_secret.json

  • After creating the OAuth Client ID, click the Download JSON button next to your new client ID.
  • Save the file as client_secret.json in your project folder.

Add Test Users (For Internal Apps)

  1. Go to OAuth Consent Screen → Test Users.
  2. Add your Google account email as a test user (required for authentication).
  • Required Scopes: Ensure your OAuth client includes the https://www.googleapis.com/auth/youtube.upload scope (used in your script).
  • Security: Never share client_secret.json publicly (it contains sensitive credentials).
  • Errors: If you see "redirect_uri mismatch," ensure you selected Desktop App as the application type.

Troubleshooting

  • If the API returns "API not enabled," recheck Step 2.
  • If authentication fails, verify the client_secret.json file is in the correct folder and the scopes match.
For a web app, use Web Application instead of Desktop App and configure authorized redirect URIs.

Post automatically merged:

And for single videos

pip install requests beautifulsoup4 google-api-python-client google-auth-oauthlib

Code:
import os
import re
import requests
from bs4 import BeautifulSoup
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

# Configuration
CLIENT_SECRET_FILE = 'client_secret.json'
SCOPES = ['https://www.googleapis.com/auth/youtube.upload']
SNAPTIK_BASE_URL = "https://snaptik.app/"

def get_no_watermark_url(tiktok_url):
    """Get direct download URL without watermark using Snaptik"""
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "Referer": SNAPTIK_BASE_URL
    }
    
    # Get Snaptik page
    session = requests.Session()
    response = session.post(
        f"{SNAPTIK_BASE_URL}abc.php",
        data={"url": tiktok_url},
        headers=headers
    )
    
    if response.status_code != 200:
        raise Exception(f"Snaptik request failed: {response.status_code}")
    
    # Parse HTML for download link
    soup = BeautifulSoup(response.text, 'html.parser')
    download_section = soup.find('div', {'class': 'download-link'})
    
    if not download_section:
        raise Exception("No download link found - check if Snaptik's HTML structure changed")
    
    return download_section.find('a')['href']

def download_video(url, filename):
    """Download video from direct URL"""
    response = requests.get(url, stream=True)
    if response.status_code == 200:
        with open(filename, 'wb') as f:
            for chunk in response.iter_content(chunk_size=1024*1024):
                if chunk:
                    f.write(chunk)
        return filename
    raise Exception(f"Download failed: {response.status_code}")

def youtube_authenticate():
    """Authenticate with YouTube API"""
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
    creds = flow.run_local_server(port=0)
    return build('youtube', 'v3', credentials=creds)

def upload_youtube_short(youtube, file_path, title, description, tags):
    """Upload video to YouTube Shorts"""
    body = {
        'snippet': {
            'title': title,
            'description': description,
            'tags': tags,
            'categoryId': '24'
        },
        'status': {
            'privacyStatus': 'public'
        }
    }
    media = MediaFileUpload(file_path, chunksize=-1, resumable=True)
    request = youtube.videos().insert(part='snippet,status', body=body, media_body=media)
    return request.execute()

def extract_hashtags(text):
    """Extract hashtags from text"""
    return list(set(re.findall(r"#(\w+)", text)))

def main():
    # Input TikTok URL
    tiktok_url = "https://www.tiktok.com/@user/video/1234567890"  # Replace with actual URL
    
    try:
        # Step 1: Get no-watermark URL
        print("Fetching download URL from Snaptik...")
        download_url = get_no_watermark_url(tiktok_url)
        
        # Step 2: Download video
        print("Downloading video...")
        video_id = re.search(r'/video/(\d+)', tiktok_url).group(1)
        filename = f"tiktok_{video_id}.mp4"
        download_video(download_url, filename)
        
        # Step 3: YouTube upload
        print("Authenticating with YouTube...")
        youtube = youtube_authenticate()
        
        # Extract hashtags from original URL
        hashtags = extract_hashtags(tiktok_url)
        
        print("Uploading to YouTube Shorts...")
        response = upload_youtube_short(
            youtube,
            filename,
            title=f"TikTok Video {video_id}",
            description=f"Auto-uploaded TikTok video\nOriginal URL: {tiktok_url}\nHashtags: {' '.join(['#' + tag for tag in hashtags])}",
            tags=hashtags
        )
        
        print(f"Successfully uploaded! Video ID: {response['id']}")
        
    except Exception as e:
        print(f"Error: {str(e)}")
    finally:
        if 'filename' in locals() and os.path.exists(filename):
            os.remove(filename)

if __name__ == "__main__":
    main()

Tiktok URL form video must replace for every short before upload
 
Last edited:
1 comment
Back
Top