Python 範例

示範如何使用 Python 呼叫 Boring API。

安裝套件

pip install requests

基本設定

import requests
import os

# API 設定
API_URL = "https://boring.aiagent-me.com/v2/posts"
API_KEY = os.environ.get("BORING_API_KEY")

# 標頭
HEADERS = {
    "boring-api-key": API_KEY,
    "Content-Type": "application/json"
}

發佈函式

def publish_post(account_id, platform, text, media_urls=None):
    """
    發佈貼文到社群平台

    Args:
        account_id (str): 控制台提供的帳號 ID
        platform (str): "facebook"、"instagram"、"threads"、"x"、"youtube"
        text (str|list): 貼文文字或 Threads 串文陣列
        media_urls (list): 媒體 URL 清單(可選)
    """
    if media_urls is None:
        media_urls = []

    data = {
        "post": {
            "accountId": account_id,
            "content": {
                "text": text,
                "mediaUrls": media_urls,
                "platform": platform
            },
            "target": {
                "targetType": platform
            }
        }
    }

    response = requests.post(API_URL, headers=HEADERS, json=data)
    return response.json()

Facebook 範例

純文字

result = publish_post(
    account_id="your-facebook-account-id",
    platform="facebook",
    text="Hello from Boring API! 🚀"
)

單張照片

result = publish_post(
    account_id="your-facebook-account-id",
    platform="facebook",
    text="Check out our new product!",
    media_urls=["https://example.com/product.jpg"]
)

相簿

result = publish_post(
    account_id="your-facebook-account-id",
    platform="facebook",
    text="Our best moments from the event! 📸",
    media_urls=[
        "https://example.com/event1.jpg",
        "https://example.com/event2.jpg",
        "https://example.com/event3.jpg",
        "https://example.com/event4.jpg"
    ]
)

影片

result = publish_post(
    account_id="your-facebook-account-id",
    platform="facebook",
    text="Watch our product demo! 🎥",
    media_urls=["https://example.com/demo.mp4"]
)

Instagram 範例

單張照片

result = publish_post(
    account_id="your-instagram-account-id",
    platform="instagram",
    text="Beautiful sunset 🌅 #nature #photography",
    media_urls=["https://example.com/sunset.jpg"]
)

輪播

result = publish_post(
    account_id="your-instagram-account-id",
    platform="instagram",
    text="Swipe to see our collection! ➡️",
    media_urls=[
        "https://example.com/photo1.jpg",
        "https://example.com/photo2.jpg",
        "https://example.com/photo3.jpg"
    ]
)

Reels

result = publish_post(
    account_id="your-instagram-account-id",
    platform="instagram",
    text="New product teaser 🔥",
    media_urls=["https://example.com/reel.mp4"]
)

Threads 範例

純文字

result = publish_post(
    account_id="your-threads-account-id",
    platform="threads",
    text="Ask me anything about building social media automation! 💬",
    media_urls=[]
)

帶圖片

result = publish_post(
    account_id="your-threads-account-id",
    platform="threads",
    text="Stack ranking our favorite ideas!",
    media_urls=["https://example.com/photo.jpg"]
)

串文

result = publish_post(
    account_id="your-threads-account-id",
    platform="threads",
    text=[
        "🧵 Let's talk about content planning",
        "1. Define your goals",
        "2. Pick your channels",
        "3. Automate with Boring API"
    ],
    media_urls=[]
)

X(Twitter)範例

result = publish_post(
    account_id="your-x-account-id",
    platform="x",
    text="Launching a new feature today! 🚀 #api #launch",
    media_urls=[]
)

YouTube 範例

result = publish_post(
    account_id="your-youtube-account-id",
    platform="youtube",
    text="Product Tour 2025\n\nFull walkthrough of the new dashboard.",
    media_urls=[
        "https://example.com/video.mp4",
        "https://example.com/thumbnail.jpg"
    ]
)

錯誤處理

result = publish_post(...)

if not result.get("success"):
    print("Error:", result["error"], "-", result["message"])

重試機制

def publish_with_retry(account_id, platform, text, media_urls=None, retries=3):
    for attempt in range(retries):
        result = publish_post(account_id, platform, text, media_urls)

        if result.get("success"):
            return result

        if result.get("error") not in ["RateLimitExceeded", "ServiceUnavailable", "Timeout"]:
            return result

        wait = 2 ** attempt
        time.sleep(wait)

    return {"success": False, "error": "MaxRetriesExceeded"}

批次發佈

posts = [
    {"account_id": "fb-id", "platform": "facebook", "text": "Hello FB!", "media_urls": []},
    {"account_id": "ig-id", "platform": "instagram", "text": "Hello IG!", "media_urls": ["https://..."]},
    {"account_id": "threads-id", "platform": "threads", "text": "Hello Threads!", "media_urls": []}
]

for post in posts:
    result = publish_post(**post)

完整腳本

#!/usr/bin/env python3
import requests
import os
import logging

API_URL = "https://boring.aiagent-me.com/v2/posts"
API_KEY = os.environ.get("BORING_API_KEY")

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def publish_post(account_id, platform, text, media_urls=None):
    headers = {
        "boring-api-key": API_KEY,
        "Content-Type": "application/json"
    }

    payload = {
        "post": {
            "accountId": account_id,
            "content": {
                "text": text,
                "mediaUrls": media_urls or [],
                "platform": platform
            },
            "target": {
                "targetType": platform
            }
        }
    }

    response = requests.post(API_URL, headers=headers, json=payload)
    return response.json()

def main():
    logger.info("Publishing to Facebook...")
    result = publish_post(
        account_id=os.environ.get("FB_ACCOUNT_ID"),
        platform="facebook",
        text="Hello from Boring API! 🚀",
        media_urls=[]
    )

    if result["success"]:
        logger.info(f"Success! Post ID: {result['data']['post_id']}")
    else:
        logger.error(f"Failed: {result['message']}")

if __name__ == "__main__":
    main()

延伸閱讀