

สร้างงานนำเสนออัตโนมัติด้วย Python: คู่มือ 2Slides API
Python เป็นภาษาที่ใช้กันมากที่สุดสำหรับระบบอัตโนมัติ data pipelines และเวิร์กโฟลว์ AI คู่มือนี้จะแสดงวิธีใช้ 2Slides REST API จาก Python เพื่อสร้างงานนำเสนออัตโนมัติ — ตั้งแต่สไลด์เดี่ยวๆ แบบง่ายๆ ไปจนถึงไปป์ไลน์อัตโนมัติที่ซับซ้อน
ข้อกำหนดเบื้องต้น
pip install requests python-dotenvสร้างไฟล์ .env:
TWOSLIDES_API_KEY=sk-2slides-your-api-keyเริ่มต้นอย่างรวดเร็ว: สร้างสไลด์แรกของคุณ
import os
import time
import requests
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv('TWOSLIDES_API_KEY')
BASE_URL = 'https://2slides.com/api/v1'
HEADERS = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
def generate_slides(topic, theme_id=None, mode='async'):
"""สร้างงานนำเสนอจากหัวข้อข้อความ"""
payload = {
'userInput': topic,
'mode': mode,
'responseLanguage': 'en',
'resolution': '2K',
}
if theme_id:
payload['themeId'] = theme_id
response = requests.post(
f'{BASE_URL}/slides/generate',
headers=HEADERS,
json=payload
)
response.raise_for_status()
return response.json()
def wait_for_job(job_id, timeout=300, interval=3):
"""ตรวจสอบสถานะจนกว่างานจะเสร็จสมบูรณ์"""
start = time.time()
while time.time() - start < timeout:
response = requests.get(
f'{BASE_URL}/jobs/{job_id}',
headers=HEADERS
)
data = response.json()
status = data.get('status')
print(f' Job {job_id}: {status}')
if status == 'success':
return data
if status == 'failed':
raise Exception(f'Job failed: {data}')
time.sleep(interval)
raise TimeoutError(f'Job {job_id} timed out after {timeout}s')
# สร้างงานนำเสนอ
job = generate_slides('Top 10 AI Trends for 2026')
print(f'Job ID: {job["jobId"]}')
result = wait_for_job(job['jobId'])
print(f'Download: {result["downloadUrl"]}')แปลงเอกสารเป็นสไลด์
def convert_file_to_slides(file_url, prompt='', theme_id=None):
"""แปลงไฟล์ PDF, DOCX, XLSX หรือไฟล์อื่นๆ เป็นสไลด์"""
payload = {
'fileUrl': file_url,
'userInput': prompt,
'mode': 'async'
}
if theme_id:
payload['themeId'] = theme_id
response = requests.post(
f'{BASE_URL}/slides/create-pdf-slides',
headers=HEADERS,
json=payload
)
response.raise_for_status()
job = response.json()
return wait_for_job(job['jobId'])
# แปลงรายงานรายไตรมาสจาก PDF
result = convert_file_to_slides(
file_url='https://your-storage.com/q1-report.pdf',
prompt='สรุปผู้บริหารสำหรับคณะกรรมการ ไม่เกิน 10 สไลด์'
)
print(f'Download: {result["downloadUrl"]}')สไลด์ที่ตรงกับดีไซน์ (สร้างแบบนี้)
def create_like_this(topic, reference_image_url, resolution='2K'):
"""สร้างสไลด์ที่ตรงกับดีไซน์อ้างอิง"""
payload = {
'userInput': topic,
'designStyle': {
'global': {
'referenceImageUrl': reference_image_url
}
},
'resolution': resolution,
'mode': 'async'
}
response = requests.post(
f'{BASE_URL}/slides/create-like-this',
headers=HEADERS,
json=payload
)
response.raise_for_status()
job = response.json()
return wait_for_job(job['jobId'])
# จับคู่เทมเพลตแบรนด์ของคุณ
result = create_like_this(
topic='รายงานทีมประจำเดือน — มีนาคม 2026',
reference_image_url='https://your-brand.com/slide-template.png'
)เพิ่มเสียงบรรยาย
def add_narration(job_id, mode='single', voice='Charon', content_mode='concise'):
"""เพิ่มเสียงบรรยาย AI ให้กับสไลด์ที่มีอยู่"""
payload = {
'jobId': job_id,
'mode': mode,
'voice': voice,
'contentMode': content_mode
}
response = requests.post(
f'{BASE_URL}/slides/generate-narration',
headers=HEADERS,
json=payload
)
response.raise_for_status()
return response.json()
def download_with_audio(job_id):
"""ดาวน์โหลดสไลด์พร้อมไฟล์เสียงบรรยาย"""
response = requests.post(
f'{BASE_URL}/slides/download-slides-pages-voices',
headers=HEADERS,
json={'jobId': job_id}
)
response.raise_for_status()
return response.json()เรียกดูธีม
def search_themes(query=''):
"""ค้นหาธีมสไลด์ที่มีอยู่"""
params = {'query': query} if query else {}
response = requests.get(
f'{BASE_URL}/themes',
headers=HEADERS,
params=params
)
response.raise_for_status()
return response.json()
themes = search_themes('corporate')
for theme in themes.get('themes', []):
print(f"{theme['id']}: {theme['name']}")ตัวอย่าง Production Pipeline
"""
Pipeline รายงานประจำสัปดาห์อัตโนมัติ
รันผ่าน cron: 0 9 * * MON python weekly_report.py
"""
import json
from datetime import datetime
def weekly_report_pipeline():
print(f'กำลังสร้างรายงานประจำสัปดาห์: {datetime.now().isoformat()}')
# 1. สร้างสไลด์
job = generate_slides(
topic='''Weekly Engineering Update — สัปดาห์ที่ 23 มีนาคม 2026:
- Deploy v2.4 ไป production (uptime 99.9%)
- ส่งมอบ API endpoint ใหม่ 3 ตัว
- ประสิทธิภาพ: p99 latency ลดลง 40%
- ความเร็ว Sprint: 42 story points (เป้าหมาย: 40)
- สัปดาห์หน้า: database migration, ระบบ auth ใหม่''',
theme_id='corporate-standard-id'
)
result = wait_for_job(job['jobId'])
print(f'สไลด์พร้อมแล้ว: {result["downloadUrl"]}')
# 2. เพิ่มการบรรยาย
add_narration(job['jobId'], mode='single', voice='Kore')
print('เพิ่มการบรรยายแล้ว')
# 3. ดาวน์โหลดแพ็กเกจ
package = download_with_audio(job['jobId'])
print(f'แพ็กเกจทั้งหมด: {json.dumps(package, indent=2)}')
return result['downloadUrl']
if __name__ == '__main__':
url = weekly_report_pipeline()
print(f'\nURL รายงาน: {url}')แนวทางปฏิบัติที่ดีในการจัดการข้อผิดพลาด
from requests.exceptions import HTTPError, Timeout, ConnectionError
def safe_generate(topic, retries=3):
"""สร้างสไลด์พร้อมระบบลองใหม่"""
for attempt in range(retries):
try:
job = generate_slides(topic)
return wait_for_job(job['jobId'])
except HTTPError as e:
if e.response.status_code == 429:
wait = 2 ** attempt * 5 # Exponential backoff
print(f'ถูกจำกัดอัตรา รอ {wait} วินาที...')
time.sleep(wait)
elif e.response.status_code == 402:
raise Exception('เครดิตไม่เพียงพอ')
else:
raise
except (Timeout, ConnectionError) as e:
print(f'ข้อผิดพลาดเครือข่าย (ครั้งที่ {attempt + 1}): {e}')
time.sleep(5)
raise Exception(f'ล้มเหลวหลังจากลองใหม่ {retries} ครั้ง')คำถามที่พบบ่อย
ต้องใช้ Python เวอร์ชันอะไร?
Python 3.7+ สำหรับ f-strings และความเข้ากันได้กับ requests
สามารถใช้ async Python (asyncio/aiohttp) ได้หรือไม่?
ได้ — แทนที่ requests ด้วย aiohttp สำหรับการเรียก HTTP แบบ async รูปแบบการ polling ทำงานเหมือนกัน
จัดการงาน batch ขนาดใหญ่อย่างไร?
ใช้ asyncio เพื่อรันการสร้างหลายรายการพร้อมกัน โดยเคารพขอบเขตอัตรา (60 req/min)
เริ่มทำงานอัตโนมัติ — รับ API key ของ 2Slides และสร้างงานนำเสนอจาก Python
About 2Slides
Create stunning AI-powered presentations in seconds. Transform your ideas into professional slides with 2slides AI Agent.
Try For Free