Files
python_scripts/package/tiktok/uploader.py
T

74 lines
2.4 KiB
Python

import json
import requests
from pathlib import Path
SECRETS_FILE = Path(__file__).parent.parent / "tiktok_secrets.json"
# if your file is at /home/richard/python_scripts/tiktok_secrets.json
# use: Path("/home/richard/python_scripts/tiktok_secrets.json")
def load_secrets():
with open(SECRETS_FILE) as f:
secrets = json.load(f)
return secrets["client_key"], secrets["client_secret"], secrets["access_token"], secrets.get("refresh_token", "")
API_BASE = "https://open.tiktokapis.com/v2"
def upload_to_tiktok_api(video_path: str, title: str, privacy="PUBLIC_TO_EVERYONE"):
client_key, client_secret, access_token, refresh_token = load_secrets()
video_path = Path(video_path)
file_size = video_path.stat().st_size
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json; charset=UTF-8"
}
# 1. INIT
init_payload = {
"source_info": {
"source": "FILE_UPLOAD",
"video_size": file_size,
"chunk_size": file_size,
"total_chunk_count": 1
}
}
r = requests.post(f"{API_BASE}/post/publish/video/init/", headers=headers, json=init_payload)
r.raise_for_status()
data = r.json()
if data.get("error", {}).get("code") != "ok":
raise Exception(f"Init failed: {data}")
publish_id = data["data"]["publish_id"]
upload_url = data["data"]["upload_url"]
# 2. UPLOAD
with open(video_path, "rb") as f:
put_headers = {
"Content-Range": f"bytes 0-{file_size-1}/{file_size}",
"Content-Type": "video/mp4"
}
requests.put(upload_url, headers=put_headers, data=f).raise_for_status()
# 3. PUBLISH
publish_payload = {
"publish_id": publish_id,
"post_info": {
"title": title[:2200],
"privacy_level": privacy,
"disable_duet": False,
"disable_comment": False,
"disable_stitch": False,
"video_cover_timestamp_ms": 1000
}
}
pr = requests.post(f"{API_BASE}/post/publish/", headers=headers, json=publish_payload)
pr.raise_for_status()
return pr.json()
if __name__ == "__main__":
result = upload_to_tiktok_api(
"/home/richard/python_scripts/download/clips/ProductiveConfidentWombatThunBeast/ProductiveConfidentWombatThunBeast_gaussian_9_16.mp4",
"Testing upload #Twitch #TeamPGP #Stellaris"
)
print(result)