ทำไมต้องใช้ Python สำหรับการทำงานอัตโนมัติในโซเชียลมีเดีย
Python is the go-to language for automation. It\'s readable, has a massive ecosystem, and it\'s perfect for scripts that run on a schedule. And when it comes to posting to social media programmatically, the alternative to using an API like Upload-Post is building OAuth integrations for each platform yourself. That means handling TikTok\'s Content Posting API, Instagram\'s Graph API, YouTube\'s Data API, and so on. Each with its own authentication flow, rate limits, and quirks.
With the social media posting API, you make one API call and it posts to all ten platforms. The Python SDK makes this even simpler.
กำลังตั้งค่าสภาพแวดล้อมของคุณ
1. ติดตั้ง SDK
pip install upload-post 2. รับคีย์ API ของคุณ
Create a free account at app.upload-post.com and generate an API key from the แดชบอร์ดคีย์ API. Store it as an environment variable:
export UPLOAD_POST_API_KEY="your-api-key-here" 3. เชื่อมต่อบัญชีโซเชียลของคุณ
In the Upload-Post dashboard, create a profile (e.g. "mybrand") and connect your TikTok, Instagram, YouTube and any other accounts you want to post to. The profile name is what you\'ll reference in your code.
การอัปโหลดครั้งแรกของคุณ: การโพสต์วิดีโอ
import os
from upload_post import UploadPostClient
client = UploadPostClient(
api_key=os.environ["UPLOAD_POST_API_KEY"]
)
response = client.upload_video(
video_path="my-video.mp4",
title="ผลิตภัณฑ์ใหม่ของเราในแอ็คชั่น",
user="mybrand",
platforms=["tiktok", "instagram", "youtube"]
)
if response["success"]:
for platform, result in response["results"].items():
if result["success"]:
print(f"{platform}: {result['url']}")
else:
print(f"{platform}: upload failed")
else:
print("Upload failed:", response) That\'s a working script. Run it and your video goes live on three platforms. Now let\'s make it do more.
กำลังโพสต์รูปภาพและคารูเซล
response = client.upload_photos(
photos=["slide-1.jpg", "slide-2.jpg", "slide-3.jpg"],
title="สมุดภาพคอลเลกชันฤดูร้อน",
description="ทุกชิ้นผลิตในโปรตุเกส ช้อปปิ้งที่ลิงก์ในชีวประวัติ",
user="mybrand",
platforms=["instagram", "tiktok", "linkedin"]
)
print(response) Instagram creates a carousel post, TikTok creates a slideshow, and LinkedIn shows a multi-image post. Each platform gets the format it prefers.
กำลังโพสต์เนื้อหาข้อความ
For text only posts (think Twitter threads, LinkedIn updates, or Reddit submissions):
response = client.upload_text(
title="เราเพิ่งปล่อยอัปเดตใหญ่สำหรับ API ของเรา. นี่คือสิ่งที่เปลี่ยนแปลง...",
user="mybrand",
platforms=["x", "linkedin", "threads", "bluesky"]
)
print(response) If your text exceeds the character limit on a platform, the API handles it smartly. On X, text over 280 characters automatically becomes a thread. On Threads, the split happens at 500 characters. On Bluesky, at 300.
ใช้พารามิเตอร์เฉพาะแพลตฟอร์ม
The title parameter sets the default caption for all platforms, but you\'ll often want different copy for each one. Here\'s how to customize per platform:
import requests
import os
API_KEY = os.environ["UPLOAD_POST_API_KEY"]
with open("product-demo.mp4", "rb") as video:
response = requests.post(
"https://api.upload-post.com/api/upload",
headers={"การอนุญาต": f"Apikey {API_KEY}"},
files={"video": video},
data={
"user": "mybrand",
"title": "Check this out",
# Platform specific titles
"tiktok_title": "POV: ผลิตภัณฑ์ของคุณขายตัวเอง #ecommerce #dropshipping",
"instagram_title": "การเปิดตัวใหม่ ลิงก์ในชีวประวัติสำหรับการเข้าถึงล่วงหน้า",
"youtube_title": "สาธิตผลิตภัณฑ์ | รีวิวเต็มรูปแบบ",
"youtube_description": "ในวิดีโอนี้เราจะแสดงให้คุณเห็นว่ามันทำงานอย่างไร...",
"linkedin_title": "ตื่นเต้นที่จะได้แชร์การเปิดตัวผลิตภัณฑ์ล่าสุดของเรากับชุมชน",
# Platform specific settings
"platform[]": ["tiktok", "instagram", "youtube", "linkedin"],
"privacy_level": "PUBLIC_TO_EVERYONE",
"media_type": "REELS",
"tags[]": ["product", "demo", "review"],
"privacyStatus": "public",
}
)
print(response.json())
This example uses the requests library directly instead of the SDK, which gives you access to every single API parameter. Check the full API reference for all available options per platform.
กำหนดเวลาโพสต์สำหรับภายหลัง
from datetime import datetime, timedelta
# Schedule for tomorrow at 9 AM
tomorrow_9am = (datetime.now() + timedelta(days=1)).replace(
hour=9, minute=0, second=0, microsecond=0
)
response = client.upload_video(
video_path="tomorrows-content.mp4",
title="สวัสดีตอนเช้า! เนื้อหาใหม่สำหรับฟีดของคุณ",
user="mybrand",
platforms=["tiktok", "instagram"],
scheduled_date=tomorrow_9am.isoformat(),
timezone="อเมริกา/นิวยอร์ก"
)
print(f"กำหนดเวลาแล้ว! รหัสงาน: {response['job_id']}")
print(f"จะเผยแพร่ที่: {response['scheduled_date']}") You can schedule up to 365 days in advance. For more details on scheduling and the queue system, read our scheduling guide.
การสร้างการทำงานอัตโนมัติแบบเต็มรูปแบบ: ตัวตรวจสอบโฟลเดอร์
Here\'s a practical script that watches a folder for new video files and automatically uploads them. This is great for agencies that receive client content in a shared folder:
import os
import time
import json
from upload_post import UploadPostClient
client = UploadPostClient(
api_key=os.environ["UPLOAD_POST_API_KEY"]
)
WATCH_FOLDER = "/path/to/content/inbox"
PROCESSED_FILE = "/path/to/content/processed.json"
CHECK_INTERVAL = 60 # seconds
def load_processed():
if os.path.exists(PROCESSED_FILE):
with open(PROCESSED_FILE) as f:
return set(json.load(f))
return set()
def save_processed(processed):
with open(PROCESSED_FILE, "w") as f:
json.dump(list(processed), f)
def upload_video(filepath):
filename = os.path.basename(filepath)
title = filename.rsplit(".", 1)[0].replace("-", " ").replace("_", " ")
response = client.upload_video(
video_path=filepath,
title=title,
user="mybrand",
platforms=["tiktok", "instagram", "youtube"],
add_to_queue=True,
async_upload=True
)
return response
print(f"Watching {WATCH_FOLDER} for new videos...")
processed = load_processed()
while True:
for filename in os.listdir(WATCH_FOLDER):
if filename in processed:
continue
if not filename.lower().endswith((".mp4", ".mov")):
continue
filepath = os.path.join(WATCH_FOLDER, filename)
print(f"New file detected: {filename}")
try:
result = upload_video(filepath)
print(f" Queued successfully: {result.get('job_id', 'done')}")
processed.add(filename)
save_processed(processed)
except Exception as e:
print(f" Error: {e}")
time.sleep(CHECK_INTERVAL) Run this script in the background (or as a systemd service) and every time someone drops a video in the folder, it gets published to all your connected platforms. If you need something more robust, consider using n8n or Make.com for a managed workflow.
ทำงานกับ API โดยตรง (โดยไม่ใช้ SDK)
If you prefer not to use the SDK or need lower level control, you can use the requests library directly. Here\'s the equivalent of the SDK upload:
import requests
API_KEY = "your-api-key-here"
API_URL = "https://api.upload-post.com/api/upload"
# Upload a video
with open("video.mp4", "rb") as f:
response = requests.post(
API_URL,
headers={"การอนุญาต": f"Apikey {API_KEY}"},
files={"video": ("video.mp4", f, "video/mp4")},
data={
"user": "mybrand",
"title": "โพสต์ด้วย Python requests",
"platform[]": ["tiktok", "instagram"],
}
)
print(response.status_code)
print(response.json()) การตรวจสอบความถูกต้องของ API key ของคุณ
Before running a big batch, it\'s a good idea to validate that your key works and check your plan limits:
response = requests.get(
"https://api.upload-post.com/api/uploadposts/me",
headers={"การอนุญาต": f"Apikey {API_KEY}"}
)
data = response.json()
print(f"อีเมล: {data['email']}")
print(f"แผน: {data['plan']}") แนวทางปฏิบัติที่ดีที่สุดในการจัดการข้อผิดพลาด
When building production scripts, handle these common scenarios:
import requests
def upload_with_retry(video_path, title, platforms, max_retries=3):
for attempt in range(max_retries):
try:
with open(video_path, "rb") as f:
response = requests.post(
"https://api.upload-post.com/api/upload",
headers={"การอนุญาต": f"Apikey {API_KEY}"},
files={"video": f},
data={
"user": "mybrand",
"title": title,
"platform[]": platforms,
"async_upload": "true",
},
timeout=120
)
if response.status_code == 200:
return response.json()
elif response.status_code == 429:
# Rate limited, check usage
usage = response.json().get("usage", {})
print(f"Rate limited. Used {usage.get('count')}/{usage.get('limit')}")
return None
elif response.status_code == 401:
print("Invalid API key")
return None
else:
print(f"Attempt {attempt + 1} failed: {response.status_code}")
except requests.exceptions.Timeout:
print(f"Attempt {attempt + 1} timed out, retrying...")
print(f"การพยายามทั้งหมด {max_retries} ล้มเหลวสำหรับ {video_path}")
return None กำลังตรวจสอบประวัติการอัปโหลด
You can pull your upload history to verify what went through or build a reporting dashboard:
response = requests.get(
"https://api.upload-post.com/api/uploadposts/history?page=1&limit=20",
headers={"การอนุญาต": f"Apikey {API_KEY}"}
)
for entry in response.json()["history"]:
status = "OK" if entry["success"] else "FAILED"
print(f"[{status}] {entry['platform']} - {entry['post_title']} - {entry['post_url']}") ขั้นตอนถัดไป
Now that you have the basics, here are some ideas for what to build next:
- เชื่อมต่อสคริปต์ของคุณกับ CMS หรือฐานข้อมูลเพื่อให้เนื้อหาใหม่เผยแพร่อัตโนมัติ
- Use the bulk upload approach to process entire content libraries
- นำวิดีโอยาวกลับมาใช้ใหม่เป็นคลิปสั้น using FFmpeg and the Upload-Post API
- Build a white label integration if you\'re building a SaaS product that needs social publishing
- Explore our n8n templates for AI powered workflows that generate and publish content automatically