π How to Automate TikTok Shorts Uploads from Linux: Playwright, Local AI (Ollama), and Systemd Without Getting Banned

Uploading vertical content consistently to social media platforms is one of the most tedious and exhausting tasks for any musician or content creator π₯. When you regularly record acoustic or electronic drum covers, mix multitrack sessions, render vertical cuts, and schedule daily clips, spending 30 minutes every single day filling out captions, picking hashtags, and clicking web buttons feels like a massive waste of valuable creative time ⏳.
Instagram allows automation via mobile private API clients like instagrapi, but TikTok is an entirely different battleground. ByteDance's platform enforces one of the most aggressive anti-bot security architectures in the web industry: dynamic request signatures, strict browser fingerprint validation, mandatory 3D puzzle CAPTCHAs, and instant account restrictions if you attempt direct console logins with raw usernames and passwords π‘️.
In this exhaustive technical guide, we will break down the exact architecture of a production-tested, ban-free automated uploader built specifically for Linux (CachyOS / Arch Linux / Ubuntu) π§. By following this guide, your autonomous Python bot will:
Upload videos silently in the background without paid third-party APIs or restricted corporate developer credentials.
Maintain persistent, secure login sessions using browser-exported Netscape cookies.
Automatically generate viral hooks and punchy captions locally using LLMs powered by Ollama (
qwen2.5) π€.Dynamically intercept and destroy TikTok Studio's floating onboarding tutorials (
react-joyride) via real-time DOM mutation observers π₯.Reliably sync state with Draft.js / React text editors by emulating native hardware keystrokes π.
Automatically bypass and accept TikTok's copyright checks and "Fast Content Check" dialog prompts ⚠️.
Run as an unprivileged, self-healing Systemd user timer that publishes your clips while you are practicing or working ⏰.
π ️ System Architecture
To guarantee longevity and prevent shadowbans or bot detection, this automation rests on four critical technical pillars:
[ Local Directory: /shortsOrionDrums/tiktok/ ]
│
▼
[ FFprobe Metadata Extraction ]
│
▼
[ Local Ollama AI: Qwen 2.5 ] ──► Generates Hook & Caption
│
▼
[ Playwright Chromium Engine ] ──► Injects Netscape Session Cookies
│
├──► [ MutationObserver ] ──► Destroys React-Joyride Overlays
├──► [ File Input Injection ] ──► Direct Video Upload
├──► [ Native Keystrokes ] ──► Writes to Draft.js / React
└──► [ Forced Modal Clicks ] ──► Bypasses Content Check Popups
│
▼
[ Upload Confirmed on TikTok Studio ]
│
▼
[ File Moved to Local /uploaded/ Folder ]
1. Persistent Cookie Authentication vs. Direct Login
Submitting credentials into form fields programmatically is an immediate trigger for verification puzzles. The reliable approach is logging in manually once via your desktop browser and exporting your active session tokens (sessionid, ttwid, sid_tt, odin_tt) into a clean Netscape text file. Playwright then launches Chromium with the exact security profile of an established, trusted desktop user.
2. Overcoming Draft.js & React Controlled Inputs
In modern web applications, a div[contenteditable="true"] field is rarely just plain HTML. It is managed by frameworks like Draft.js. If you inject text using JavaScript's .innerHTML or .innerText, the string appears on the screen, but React's internal state machine never captures the update. When you click "Post", the payload submits an empty description, forcing TikTok to fallback to the raw .mp4 filename. To fix this, Playwright simulates real physical hardware keystrokes (page.keyboard.type), triggering keydown, keypress, and input events that register properly in React's state tree.
3. Neutralizing react-joyride Overlays
TikTok Studio frequently serves interactive tutorials via react-joyride to highlight new timeline or editing features. These transparent overlays (.react-joyride__overlay) cover the entire screen and intercept all pointer clicks, throwing 30-second Playwright timeout exceptions. We neutralize them by injecting a native JavaScript MutationObserver that deletes these elements the millisecond they are added to the DOM.
π¦ Prerequisites and Linux Setup
Before executing the script, make sure your operating system has all the native multimedia and browser engine libraries installed.
1. System Dependencies (Arch Linux / CachyOS)
Playwright downloads dedicated headless builds of Chromium, but they depend on system-level shared libraries for rendering, audio, and font processing. In Arch-based systems, install them via pacman:
sudo pacman -S --needed \
nss \
nspr \
libdrm \
mesa \
alsa-lib \
atk \
at-spi2-atk \
at-spi2-core \
cups \
libxkbcommon \
libxcomposite \
libxdamage \
libxfixes \
libxrandr \
gtk3 \
pango \
cairo \
libx11 \
libxext \
libxcb \
libxss \
flite \
icu \
libxml2 \
ffmpeg
(If you are running Ubuntu or Debian, install the equivalents using sudo apt-get install -y libicu74 libxml2 libflite1 ffmpeg).
2. Python Environment and Playwright Setup
Install the necessary Python packages in your user space:
pip install playwright pytz --break-system-packages
python3 -m playwright install chromium
To confirm your headless Chromium setup is working without missing library warnings, run this one-line diagnostic check:
python3 -c "from playwright.sync_api import sync_playwright; p = sync_playwright().start(); browser = p.chromium.launch(headless=True); print('✅ Chromium headless OK'); browser.close(); p.stop()"
3. Local AI Engine (Ollama)
To craft unique, high-energy hooks without paying subscription API fees, run Ollama locally with the qwen2.5:latest model:
# Start Ollama service (if not already running as a daemon)
ollama serve
# Pull the model
ollama pull qwen2.5:latest
πͺ Exporting and Sanitizing Your TikTok Cookies
Proper cookie extraction ensures Playwright avoids cross-domain authentication conflicts:
Open your standard browser (Brave, Chrome, or Firefox) where your TikTok account is active.
Install the open-source extension "Get cookies.txt LOCALLY".
Navigate to
and confirm you are fully logged in.https://www.tiktok.com Click the extension icon, ensure the TikTok domain tab is selected, and click Export.
Save the file to your project directory as:
/home/julioc/Automatizaciones/shortsOrionDrums/tiktok/tiktok_cookies.txt
Filtering Out Unrelated Cookies
Browsers often export third-party cookies along with TikTok's data. Run this quick terminal filter to keep only lines belonging to .tiktok.com and secure the file permissions:
grep -E "tiktok\.com" /home/julioc/Automatizaciones/shortsOrionDrums/tiktok/tiktok_cookies.txt > /home/julioc/Automatizaciones/shortsOrionDrums/tiktok/tiktok_cookies_clean.txt && mv /home/julioc/Automatizaciones/shortsOrionDrums/tiktok/tiktok_cookies_clean.txt /home/julioc/Automatizaciones/shortsOrionDrums/tiktok/tiktok_cookies.txt
chmod 600 /home/julioc/Automatizaciones/shortsOrionDrums/tiktok/tiktok_cookies.txt
A sanitized cookie file should look similar to this:
.tiktok.com TRUE / TRUE 1807910779 sessionid 5492d405b494cc095cdd284a3eef5fd8
.tiktok.com TRUE / TRUE 1807910779 sid_tt 5492d405b494cc095cdd284a3eef5fd8
.tiktok.com TRUE / TRUE 1807996832 ttwid 1%7CV5erKgzgMF447tzpmyfKn6TS...
.tiktok.com TRUE / FALSE 1807997673 odin_tt 409b555754e1cc97b7841e614d4d77d7...
π» Full Source Code: autopostV2Tiktok.py
Save this file as /home/julioc/Automatizaciones/shortsOrionDrums/tiktok/autopostV2Tiktok.py:
#!/usr/bin/env python3
# ==============================================================================
# Automated TikTok Shorts Uploader for Drummers and Video Creators
# Project: OrionDrums Autonomous Pipeline
# Platform: Linux (CachyOS / Arch Linux / Ubuntu)
# Stack: Playwright Headless + Ollama Local AI + Systemd Timers
# ==============================================================================
import os
import sys
import json
import shutil
import subprocess
import datetime
import re
import time
import argparse
import urllib.request
import urllib.error
from datetime import timezone, timedelta
import pytz
try:
from playwright.sync_api import sync_playwright
except ImportError:
print("⚠️ 'playwright' module not found.")
print("Install it with: pip install playwright --break-system-packages")
print("Followed by: python3 -m playwright install chromium")
sys.exit(1)
# ==============================================================================
# GLOBAL DIRECTORIES AND PIPELINE SETTINGS
# ==============================================================================
INPUT_DIR = "/home/julioc/Automatizaciones/shortsOrionDrums/tiktok"
UPLOADED_DIR = os.path.join(INPUT_DIR, "uploaded")
CACHE_FILE_TIKTOK = os.path.join(INPUT_DIR, "schedule_cache_drum_tiktok.json")
COOKIES_FILE = os.path.join(INPUT_DIR, "tiktok_cookies.txt")
# Local AI Configuration (Ollama)
USE_OLLAMA_FOR_TITLES = True
OLLAMA_API_URL = "http://localhost:11434/api/generate"
OLLAMA_MODEL_TEXT = "qwen2.5:latest"
TIMEOUT_OLLAMA = 300
VIDEO_EXTS = (".mp4", ".mov", ".mkv")
TIMEZONE = "America/Mazatlan"
LOOKBACK_DAYS = 1
AUTO_SHUTDOWN = False
LOG_TO_FILE = True
LOG_FILE = os.path.join(INPUT_DIR, "uploader_drums_tiktok.log")
# Fallback drum hooks in case the local LLM is unreachable
DRUM_HOOKS = [
"That drum fill you can't get out of your head π₯π₯",
"Pure adrenaline behind the kit ⚡π₯",
"When the kick and snare lock in tight π―π₯",
"Turning up the volume on the drum mix π§π₯",
"One of the most addictive grooves I've played π₯✨",
"The undeniable power of a solid beat ⚡π₯",
"Crushing the tempo with pure precision π₯",
"Who else loves this classic drum groove? π₯π€",
"Unleashing raw energy on the cymbals π₯⚡",
"That exact moment the pocket takes over π₯π₯",
"Speed, accuracy, and heavy hits π―π₯",
"One of the most fun tracks to tear through π₯π₯",
"When the double bass calls for pure speed ⚡π",
"Snare roll cutting straight through the mix π₯π₯",
"The energy only a heavy beat can deliver π§π₯"
]
def log(msg):
"""Outputs timestamps to console and appends to persistent log."""
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
output = f"[{ts}] {msg}"
print(output)
if LOG_TO_FILE:
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(output + "\n")
def load_cache(filepath):
"""Loads historical scheduling state from disk."""
if os.path.exists(filepath):
try:
with open(filepath, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception:
return {}
return {}
def save_cache(cache, filepath):
"""Persists slot scheduling state to JSON."""
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(cache, f, indent=2)
def get_or_set_campaign_start(cache, filepath, proposed_start_date):
"""Sets or retrieves the baseline start date for publication scaling."""
if "campaign_start_date" not in cache:
cache["campaign_start_date"] = proposed_start_date.isoformat()
save_cache(cache, filepath)
return datetime.date.fromisoformat(cache["campaign_start_date"])
def mark_slot_as_occupied(cache, filepath, date_str, slot_iso, video_name):
"""Records a publication timestamp to prevent duplicate posting."""
if date_str not in cache:
cache[date_str] = {"slots": [], "count": 0}
if slot_iso not in cache[date_str]["slots"]:
cache[date_str]["slots"].append(slot_iso)
cache[date_str]["count"] += 1
save_cache(cache, filepath)
def get_daily_target_hours(target_date, campaign_start_date):
"""
Algorithmic progressive scaling strategy:
- Weeks 1-2: 1 clip/day (18:00 hrs)
- Weeks 3-4: 2 clips/day (13:00 and 19:30 hrs)
- Month 2+: 3 clips/day (12:00, 17:00, and 21:00 hrs)
"""
days_elapsed = (target_date - campaign_start_date).days
if days_elapsed < 0:
days_elapsed = 0
if days_elapsed < 14:
return [datetime.time(18, 0)]
elif days_elapsed < 28:
return [datetime.time(13, 0), datetime.time(19, 30)]
else:
return [datetime.time(12, 0), datetime.time(17, 0), datetime.time(21, 0)]
def is_date_full_dynamic(cache, date_str, target_count):
if date_str in cache:
return cache[date_str]["count"] >= target_count
return False
def generate_free_slots_for_date(target_date, campaign_start_date, occupied_slots):
tz = pytz.timezone(TIMEZONE)
target_hours = get_daily_target_hours(target_date, campaign_start_date)
all_slots = []
for t in target_hours:
local_dt = tz.localize(datetime.datetime.combine(target_date, t))
slot_utc = local_dt.astimezone(timezone.utc).replace(second=0, microsecond=0)
all_slots.append(slot_utc)
return [s for s in all_slots if s not in occupied_slots]
def get_occupied_slots_for_date(target_date, cache):
occupied = []
date_str = target_date.isoformat()
if date_str in cache:
for slot in cache[date_str]["slots"]:
if slot not in occupied:
occupied.append(slot)
return [datetime.datetime.fromisoformat(s) for s in occupied]
def find_next_available_slot(campaign_start_date, check_from_date, cache, max_days=90):
for offset in range(max_days):
check_date = check_from_date + timedelta(days=offset)
date_str = check_date.isoformat()
target_hours = get_daily_target_hours(check_date, campaign_start_date)
max_for_day = len(target_hours)
if is_date_full_dynamic(cache, date_str, max_for_day):
continue
occupied = get_occupied_slots_for_date(check_date, cache)
free_slots = generate_free_slots_for_date(check_date, campaign_start_date, occupied)
if free_slots:
return check_date, free_slots[0]
return None, None
def extract_existing_metadata(video_path):
"""Extracts internal container metadata via ffprobe."""
tags = {}
try:
result = subprocess.run([
'ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', str(video_path)
], capture_output=True, text=True)
if result.returncode == 0:
data = json.loads(result.stdout)
raw_tags = data.get('format', {}).get('tags', {})
tags = {k.lower(): v for k, v in raw_tags.items()}
except Exception as e:
log(f"Error extracting metadata from {video_path}: {e}")
return tags
def parse_song_details(filename):
"""Extracts artist and title from standard file naming conventions."""
base = os.path.splitext(filename)[0]
base = re.sub(r'(?i)\b(drum\s*cover|cover\s*bateria|cover|reels?|shorts?|tiktok)\b', '', base)
base = base.replace("_", " ").strip()
if "-" in base:
parts = [p.strip() for p in base.split("-", 1)]
return parts[0], parts[1]
return None, base.strip()
def generar_titulo_con_ollama(info_cancion, metadatos_desc=None):
"""Generates an engaging, viral hook using the local Ollama LLM."""
if not USE_OLLAMA_FOR_TITLES:
return None
try:
contexto = f"Song reference: '{info_cancion}'."
if metadatos_desc:
contexto += f" Extra details: '{metadatos_desc}'."
prompt = (
f"You are a professional drummer and viral TikTok content creator. "
f"{contexto} "
f"Generate a short, high-energy hook line (maximum 6 words) in Spanish or English. "
f"Do not apologize, do not explain anything, do not include quotes or hashtags. "
f"Output the clean text only."
)
payload = {
"model": OLLAMA_MODEL_TEXT,
"prompt": prompt,
"stream": False
}
req = urllib.request.Request(
OLLAMA_API_URL,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=TIMEOUT_OLLAMA) as response:
res_data = json.loads(response.read().decode("utf-8"))
titulo = res_data.get("response", "").strip().strip('"').strip("'")
# Guardrail against conversational apologetic filler from LLMs
refusal_patterns = ["sorry", "i cannot", "apologize", "lo siento", "disculpa", "as an ai"]
if titulo and not any(r in titulo.lower() for r in refusal_patterns):
return titulo.splitlines()[0]
except Exception as e:
log(f" [!] Ollama generation notice ({e}). Using heuristic fallback.")
return None
def clean_hashtag(tag):
tag = tag.encode('ascii', 'ignore').decode('ascii')
tag = re.sub(r'[^a-zA-Z0-9#]', '', tag)
if len(tag) > 30:
tag = tag[:30]
if not tag.startswith('#'):
tag = '#' + tag
return tag
def generate_tiktok_metadata(video_name, video_path):
"""Builds optimized TikTok descriptions, line breaks, and hashtags."""
tags = extract_existing_metadata(video_path)
meta_desc = tags.get('description') or tags.get('synopsis') or ""
meta_title = tags.get('title') or ""
artist, song = parse_song_details(video_name)
display_song = f"{artist} - {song}" if artist and song else (song or "Drum Cover")
chosen_hook = None
if USE_OLLAMA_FOR_TITLES:
info_tema = meta_title if meta_title else display_song
titulo_ia = generar_titulo_con_ollama(info_tema, meta_desc)
if titulo_ia:
chosen_hook = titulo_ia
log(f" π€ AI Hook Generated: \"{chosen_hook}\"")
if not chosen_hook:
if meta_title and len(meta_title) > 4:
chosen_hook = meta_title
elif artist and song:
chosen_hook = f"Cover: {artist} – {song}"
else:
idx = abs(hash(video_name)) % len(DRUM_HOOKS)
chosen_hook = DRUM_HOOKS[idx]
headline = f"π₯⚡ {chosen_hook}"
info_line = f"π΅ {display_song}" if (artist and song) else ""
hashtags = [
"#DrumCover", "#Baterista", "#Bateria", "#DrumTok", "#Drums",
"#MusicosEnTikTok", "#DrumLife", "#DrumSolo", "#Rock", "#Viral"
]
if artist:
hashtags.append(clean_hashtag(f"#{artist.replace(' ', '')}"))
hashtags = [clean_hashtag(h) for h in hashtags if h]
hashtags = list(dict.fromkeys(hashtags))
tags_str = " ".join(hashtags)
lines = [headline]
if info_line:
lines.append(info_line)
lines.append("π§ Use headphones to catch the full kick-drum punch π₯")
lines.append(tags_str)
description = "\n".join(lines).strip()
return {"title": headline, "description": description}
def upload_tiktok_video(video_path, description):
"""
Core Playwright orchestrator for DOM manipulation, typing emulation,
and post execution.
"""
log(f"π± [TikTok] Uploading video with direct Playwright engine: {os.path.basename(video_path)}")
if not os.path.exists(COOKIES_FILE):
log(f"❌ Missing cookies file: {COOKIES_FILE}")
return False
# Parse standard Netscape/cURL formatted cookies
cookies = []
try:
with open(COOKIES_FILE, 'r', encoding='utf-8') as f:
for line in f:
if line.startswith('#') or not line.strip():
continue
parts = line.strip().split('\t')
if len(parts) >= 7:
domain, flag, path, secure, expires, name, value = parts[:7]
cookies.append({
'name': name,
'value': value,
'domain': domain,
'path': path,
'secure': secure.upper() == 'TRUE',
'expires': int(expires) if expires.isdigit() else -1
})
except Exception as e:
log(f"❌ Failed to parse Netscape cookie file: {e}")
return False
# Headless mode: Set to True for silent Systemd background execution
use_headless = True
with sync_playwright() as p:
browser = p.chromium.launch(
headless=use_headless,
args=[
"--disable-blink-features=AutomationControlled",
"--no-sandbox"
]
)
context = browser.new_context(
viewport={"width": 1280, "height": 800},
user_agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
)
context.add_cookies(cookies)
page = context.new_page()
try:
log("π Navigating to TikTok Creator Center...")
page.goto("https://www.tiktok.com/creator-center/upload?from=upload", timeout=60000)
# Inject real-time DOM MutationObserver to instantly strip react-joyride overlays
page.add_init_script("""
const observer = new MutationObserver(() => {
document.querySelectorAll('.react-joyride__overlay, #react-joyride-portal, [data-test-id="overlay"]').forEach(el => el.remove());
});
observer.observe(document.body, { childList: true, subtree: true });
""")
time.sleep(3)
log("π Injecting video file into input node...")
file_input = page.locator('input[type="file"]')
file_input.set_input_files(video_path)
log("⏳ Waiting for player to process file and mount the caption editor...")
editor = page.locator('div[contenteditable="true"]').first
editor.wait_for(state="visible", timeout=45000)
time.sleep(4)
# Disable 'Fast Content Check' switch if active
try:
page.evaluate("""
const switches = document.querySelectorAll('input[type="checkbox"], [role="switch"]');
switches.forEach(s => {
const parentText = s.closest('div')?.innerText || '';
if (parentText.includes('rΓ‘pida') || parentText.includes('ComprobaciΓ³n') || parentText.includes('Fast')) {
if (s.checked || s.getAttribute('aria-checked') === 'true') {
s.click();
}
}
});
""")
log("⚡ Fast Content Check verified/disabled.")
except Exception as e:
log(f"βΉ️ Content switches check skipped: {e}")
# Strip any remaining overlay remnants before interacting with the field
page.evaluate("""
document.querySelectorAll('.react-joyride__overlay, #react-joyride-portal, [data-test-id="overlay"]').forEach(el => el.remove());
""")
# Emulate physical keyboard strokes to update React/Draft.js internal state
log("π Typing caption directly into TikTok editor...")
editor.click(force=True)
page.keyboard.press("Control+A")
page.keyboard.press("Backspace")
time.sleep(1)
for line in description.splitlines():
if line.strip():
page.keyboard.type(line, delay=10)
page.keyboard.press("Shift+Enter")
time.sleep(2)
# Final overlay sweep before pressing the post button
page.evaluate("""
document.querySelectorAll('.react-joyride__overlay, #react-joyride-portal, [data-test-id="overlay"]').forEach(el => el.remove());
""")
log("π Submitting post button...")
post_button = page.locator('button:has-text("Post"), button:has-text("Publicar")').last
post_button.click(force=True)
# Handle copyright and review warning modal ("Post now")
try:
publish_now_btn = page.locator('button:has-text("Publicar ahora"), button:has-text("Post now")').first
if publish_now_btn.is_visible(timeout=8000):
log("⚡ Review confirmation modal detected. Clicking 'Post now'...")
publish_now_btn.click(force=True)
except Exception:
pass
log("⏳ Waiting for TikTok servers to finalize and confirm post...")
try:
page.wait_for_url("**/content**", timeout=40000)
log("π Navigation confirmed: Video successfully published on TikTok Studio.")
except Exception:
time.sleep(15)
browser.close()
log("✅ [TikTok] Drum Cover published successfully.")
return True
except Exception as e:
log(f"❌ Critical exception during Playwright automation: {e}")
try:
browser.close()
except:
pass
return False
def main():
parser = argparse.ArgumentParser(description="Autonomous TikTok Drum Cover Uploader")
parser.add_argument('--start-date', '-s', type=str, default=None, help='Campaign start date YYYY-MM-DD')
parser.add_argument('--reset-campaign', action='store_true', help='Reset TikTok scheduling campaign cache')
parser.add_argument('--now', '-n', action='store_true', help='Bypass calendar schedules and post immediately')
parser.add_argument('--test', '-t', type=int, nargs='?', const=5, default=None,
help='Interactive live test mode: wait N minutes with real-time countdown.')
parser.add_argument('--test-slot', type=int, default=None,
help='Systemd testing mode: injects a test slot N minutes into the future.')
args = parser.parse_args()
log("="*60)
log("π₯ CHECKING PIPELINE: TIKTOK AUTO UPLOADER")
log("="*60)
if not os.path.exists(INPUT_DIR):
log(f"π Creating input folder: {INPUT_DIR}")
os.makedirs(INPUT_DIR, exist_ok=True)
os.makedirs(UPLOADED_DIR, exist_ok=True)
cache_tiktok = load_cache(CACHE_FILE_TIKTOK)
tz = pytz.timezone(TIMEZONE)
today_local = datetime.datetime.now(tz).date()
now_utc = datetime.datetime.now(timezone.utc)
if args.test_slot is not None:
target_test_dt = datetime.datetime.now(tz) + timedelta(minutes=args.test_slot)
slot_test_utc = target_test_dt.astimezone(timezone.utc).replace(second=0, microsecond=0)
cache_tiktok["test_slot"] = slot_test_utc.isoformat()
save_cache(cache_tiktok, CACHE_FILE_TIKTOK)
log(f"π§ͺ [TEST-SLOT] Test slot established for {target_test_dt.strftime('%Y-%m-%d %H:%M:%S')}")
return
if args.reset_campaign and "campaign_start_date" in cache_tiktok:
del cache_tiktok["campaign_start_date"]
if "test_slot" in cache_tiktok:
del cache_tiktok["test_slot"]
save_cache(cache_tiktok, CACHE_FILE_TIKTOK)
log("π TikTok campaign schedule reset.")
if args.start_date:
try:
start_date = datetime.datetime.strptime(args.start_date, "%Y-%m-%d").date()
except ValueError:
log("❌ Error: Invalid date format. Please use YYYY-MM-DD")
sys.exit(1)
else:
start_date = today_local
campaign_start_tiktok = get_or_set_campaign_start(cache_tiktok, CACHE_FILE_TIKTOK, start_date)
if args.start_date:
check_from_date = max(start_date, today_local)
else:
earliest_check = today_local - timedelta(days=LOOKBACK_DAYS)
check_from_date = max(campaign_start_tiktok, earliest_check)
videos = [f for f in os.listdir(INPUT_DIR) if f.lower().endswith(VIDEO_EXTS)]
if not videos:
log(f"π No pending videos found in: {INPUT_DIR}")
return
videos.sort()
is_interactive_test = args.test is not None
test_target_date = None
test_slot_utc = None
if is_interactive_test:
test_minutes = args.test
target_dt = datetime.datetime.now(tz) + timedelta(minutes=test_minutes)
test_slot_utc = target_dt.astimezone(timezone.utc).replace(second=0, microsecond=0)
test_target_date = target_dt.date()
log(f"π§ͺ LIVE TEST MODE ACTIVATED (--test {test_minutes}m)")
log(f"π― Target upload time: {target_dt.strftime('%H:%M:%S')} (in {test_minutes} minutes)")
log("⏳ Waiting with active countdown...\n")
try:
while True:
remaining = (target_dt - datetime.datetime.now(tz)).total_seconds()
if remaining <= 0:
break
mins, secs = divmod(int(remaining), 60)
sys.stdout.write(f"\r⏱️ Time remaining until publication: {mins:02d}:{secs:02d}...")
sys.stdout.flush()
time.sleep(1)
print()
log("π Target time reached! Triggering TikTok upload sequence...")
except KeyboardInterrupt:
print()
log("⏹️ Live test cancelled by user.")
return
for video_name in videos:
video_path = os.path.join(INPUT_DIR, video_name)
if is_interactive_test:
target_date_tt = test_target_date
slot_utc_tt = test_slot_utc
elif "test_slot" in cache_tiktok:
slot_utc_tt = datetime.datetime.fromisoformat(cache_tiktok["test_slot"])
target_date_tt = slot_utc_tt.astimezone(tz).date()
else:
target_date_tt, slot_utc_tt = find_next_available_slot(campaign_start_tiktok, check_from_date, cache_tiktok)
if not target_date_tt or not slot_utc_tt:
log(f"⚠️ No scheduling slots available for {video_name}")
continue
local_slot_dt = slot_utc_tt.astimezone(tz)
local_slot_str = local_slot_dt.strftime('%Y-%m-%d %H:%M:%S')
if not args.now and not is_interactive_test and now_utc < slot_utc_tt:
log(f"⏳ Next TikTok Short scheduled for {local_slot_str}. Exiting...")
break
elif args.now:
log("⚡ FORCED MODE (--now): Uploading immediately without waiting for scheduled slot.")
elif not is_interactive_test:
log(f"⏰ Target slot reached or elapsed ({local_slot_str}). Initiating upload...")
log(f"\nπ¬ Processing: {video_name} → Consuming slot: {local_slot_str}")
meta = generate_tiktok_metadata(video_name, video_path)
if not meta:
log(f"❌ Failed to construct metadata for {video_name}, skipping.")
continue
log(f"π Caption Content:\n{meta['description']}")
tt_ok = upload_tiktok_video(video_path, meta['description'])
if tt_ok:
if "test_slot" in cache_tiktok:
del cache_tiktok["test_slot"]
save_cache(cache_tiktok, CACHE_FILE_TIKTOK)
elif not is_interactive_test:
mark_slot_as_occupied(cache_tiktok, CACHE_FILE_TIKTOK, target_date_tt.isoformat(), slot_utc_tt.isoformat(), video_name)
shutil.move(video_path, os.path.join(UPLOADED_DIR, video_name))
log(f"✅ Video moved to archive directory: {UPLOADED_DIR}")
log("π Upload workflow successfully completed.")
break
else:
log(f"❌ Upload failed. {video_name} remains in {INPUT_DIR}")
break
if AUTO_SHUTDOWN:
log("Executing power-off sequence...")
os.system("sudo shutdown -h +0.5")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
log("⏹️ Interrupted by user.")
sys.exit(0)
except Exception as e:
log(f"❌ CRITICAL EXCEPTION: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
Make the script executable:
chmod +x /home/julioc/Automatizaciones/shortsOrionDrums/tiktok/autopostV2Tiktok.py
⚙️ Background Automation with Systemd User Services
Rather than running heavy, fragile cron jobs or requiring root credentials, modern Linux distributions manage user background workflows seamlessly through Systemd User Units.
1. Service Definition
Create your unit file in your user configuration directory:
mkdir -p ~/.config/systemd/user/
nano ~/.config/systemd/user/tiktok-uploader.service
Paste the following unit configuration:
[Unit]
Description=Autonomous TikTok Shorts Uploader (OrionDrums)
After=network.target
[Service]
Type=oneshot
WorkingDirectory=/home/julioc/Automatizaciones/shortsOrionDrums/tiktok
ExecStart=/usr/bin/python3 /home/julioc/Automatizaciones/shortsOrionDrums/tiktok/autopostV2Tiktok.py
Environment=PYTHONUNBUFFERED=1
2. Timer Definition
Create the timer unit that periodically wakes the service to check whether a publication window has opened:
nano ~/.config/systemd/user/tiktok-uploader.timer
Add the scheduling schedule:
[Unit]
Description=Timer for TikTok Autonomous Video Uploader
[Timer]
OnBootSec=5min
OnUnitActiveSec=1h
Persistent=true
[Install]
WantedBy=timers.target
3. Enabling Persistence and Timer
Reload the user daemon, enable the timer, and activate system linger so your automated background tasks survive reboots and logout sessions:
# Reload user-level systemd
systemctl --user daemon-reload
# Enable and start the timer immediately
systemctl --user enable --now tiktok-uploader.timer
# Allow user services to run without an active graphical login
sudo loginctl enable-linger julioc
To review upcoming execution windows, run:
systemctl --user list-timers --all | grep tiktok
To tail live publication logs as they occur:
journalctl --user -u tiktok-uploader.service -f
π‘ Maintenance and Long-Term Operation Best Practices
Session Cookie Lifespan: TikTok web cookies generally remain valid for 30 to 90 days. If your logs eventually indicate that Playwright is redirected to the
/loginscreen, simply open your browser, export a freshtiktok_cookies.txtusing the extension, filter it withgrep, and drop it back into the directory.Never Log Out Manually: Logging out on your desktop browser immediately revokes the session on TikTok's auth servers. Always leave the browser session open (you can close tabs and windows freely).
Audio Encoding Guidelines: Drumming content requires dynamic range. Encode your exported vertical MP4s using H.264 video at 1080x1920 (60 fps) and AAC audio with a minimum bitrate of 192–256 kbps. This guarantees the kick drum punch and cymbal definition translate cleanly without compression artifacts.
π Connect and Explore the Project
Passionate about audio engineering, drum production, and Linux system engineering? Check out the music covers, technical setups, and ongoing open-source projects:
π₯ YouTube (Drum Covers):
@orionDracoDrums π» Systems & Web Development:
cesarsystems.com.mx π Personal Blog:
shalom-now.blogspot.com
Comments
Post a Comment