ตัวอย่าง API
หน้านี้รวบรวมตัวอย่างการใช้งาน TikMatrix Local API ในภาษาต่าง ๆ
Python
import requests
import json
BASE_URL = "http://localhost:50809/api/v1"
def check_license():
"""Check if API access is available"""
response = requests.get(f"{BASE_URL}/license/check")
return response.json()
def create_task(serials, script_name, script_config=None, multi_account=False):
"""Create a new task"""
payload = {
"serials": serials,
"script_name": script_name,
"script_config": script_config or {},
"enable_multi_account": multi_account
}
response = requests.post(
f"{BASE_URL}/task",
headers={"Content-Type": "application/json"},
json=payload
)
return response.json()
def list_tasks(status=None, page=1, page_size=20):
"""List tasks with optional filters"""
params = {"page": page, "page_size": page_size}
if status is not None:
params["status"] = status
response = requests.get(f"{BASE_URL}/task", params=params)
return response.json()
def get_task(task_id):
"""Get task details"""
response = requests.get(f"{BASE_URL}/task/{task_id}")
return response.json()
def delete_task(task_id):
"""Delete a task"""
response = requests.delete(f"{BASE_URL}/task/{task_id}")
return response.json()
def stop_task(task_id):
"""Stop a running task"""
response = requests.post(f"{BASE_URL}/task/{task_id}/stop")
return response.json()
def retry_task(task_id):
"""Retry a failed task"""
response = requests.post(f"{BASE_URL}/task/{task_id}/retry")
return response.json()
def get_stats():
"""Get task statistics"""
response = requests.get(f"{BASE_URL}/task/stats")
return response.json()
# ตัวอย่างการใช้งาน
if __name__ == "__main__":
# ตรวจสอบไลเซนส์ก่อน
license_info = check_license()
if license_info["code"] != 0:
print("ไม่สามารถใช้งาน API ได้:", license_info["message"])
exit(1)
print("ไลเซนส์ใช้งานได้:", license_info["data"]["plan_name"])
# สร้างงานติดตาม
result = create_task(
serials=["device_serial_1"],
script_name="follow",
script_config={"target_username": "@tikmatrix"}
)
print("สร้างงานแล้ว:", result)
# ดึงสถิติ
stats = get_stats()
print("สถิติ:", stats["data"])
JavaScript / Node.js
const BASE_URL = 'http://localhost:50809/api/v1';
async function checkLicense() {
const response = await fetch(`${BASE_URL}/license/check`);
return response.json();
}
async function createTask(serials, scriptName, scriptConfig = {}, multiAccount = false) {
const response = await fetch(`${BASE_URL}/task`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
serials,
script_name: scriptName,
script_config: scriptConfig,
enable_multi_account: multiAccount
})
});
return response.json();
}
async function listTasks(status = null, page = 1, pageSize = 20) {
const params = new URLSearchParams({ page, page_size: pageSize });
if (status !== null) params.append('status', status);
const response = await fetch(`${BASE_URL}/task?${params}`);
return response.json();
}
async function getTask(taskId) {
const response = await fetch(`${BASE_URL}/task/${taskId}`);
return response.json();
}
async function deleteTask(taskId) {
const response = await fetch(`${BASE_URL}/task/${taskId}`, { method: 'DELETE' });
return response.json();
}
async function stopTask(taskId) {
const response = await fetch(`${BASE_URL}/task/${taskId}/stop`, { method: 'POST' });
return response.json();
}
async function retryTask(taskId) {
const response = await fetch(`${BASE_URL}/task/${taskId}/retry`, { method: 'POST' });
return response.json();
}
async function getStats() {
const response = await fetch(`${BASE_URL}/task/stats`);
return response.json();
}
// ตัวอย่างการใช้งาน
async function main() {
// ตรวจสอบไลเซนส์
const license = await checkLicense();
if (license.code !== 0) {
console.error('ไม ่สามารถใช้งาน API ได้:', license.message);
return;
}
console.log('ไลเซนส์ใช้งานได้:', license.data.plan_name);
// สร้างงาน
const result = await createTask(
['device_serial_1'],
'follow',
{ target_username: '@tikmatrix' }
);
console.log('สร้างงานแล้ว:', result);
// ดึงสถิติ
const stats = await getStats();
console.log('สถิติ:', stats.data);
}
main().catch(console.error);
cURL
# ตรวจสอบไลเซนส์
curl http://localhost:50809/api/v1/license/check
# สร้างงาน
curl -X POST http://localhost:50809/api/v1/task \
-H "Content-Type: application/json" \
-d '{
"serials": ["device_serial_1"],
"script_name": "follow",
"script_config": {"target_username": "@tikmatrix"},
"enable_multi_account": false
}'
# แสดงงานที่รอดำเนินการ
curl "http://localhost:50809/api/v1/task?status=0&page=1&page_size=20"
# ดูรายละเอียดงาน
curl http://localhost:50809/api/v1/task/1
# หยุดงาน
curl -X POST http://localhost:50809/api/v1/task/1/stop
# ลองงานที่ล้มเหลวใหม่
curl -X POST http://localhost:50809/api/v1/task/1/retry
# ลบงาน
curl -X DELETE http://localhost:50809/api/v1/task/1
# ลบงานหล ายรายการ
curl -X DELETE http://localhost:50809/api/v1/task/batch \
-H "Content-Type: application/json" \
-d '{"task_ids": [1, 2, 3]}'
# ลองงานที่ล้มเหลวทั้งหมดใหม่
curl -X POST http://localhost:50809/api/v1/task/retry-all
# ดูสถิติงาน
curl http://localhost:50809/api/v1/task/stats
PowerShell
$BaseUrl = "http://localhost:50809/api/v1"
function Check-License {
$response = Invoke-RestMethod -Uri "$BaseUrl/license/check" -Method Get
return $response
}
function Create-Task {
param(
[string[]]$Serials,
[string]$ScriptName,
[hashtable]$ScriptConfig = @{},
[bool]$MultiAccount = $false
)
$body = @{
serials = $Serials
script_name = $ScriptName
script_config = $ScriptConfig
enable_multi_account = $MultiAccount
} | ConvertTo-Json -Depth 10
$response = Invoke-RestMethod -Uri "$BaseUrl/task" -Method Post `
-ContentType "application/json" -Body $body
return $response
}
function Get-Tasks {
param(
[int]$Status = $null,
[int]$Page = 1,
[int]$PageSize = 20
)
$uri = "$BaseUrl/task?page=$Page&page_size=$PageSize"
if ($null -ne $Status) { $uri += "&status=$Status" }
$response = Invoke-RestMethod -Uri $uri -Method Get
return $response
}