Приклади API
Ця сторінка містить приклади коду для використання локального API TikMatrix різними мовами програмування.
Python
import requests
import json
BASE_URL = "http://localhost:50809/api/v1"
def check_license():
"""Перевірити, чи доступний доступ до API"""
response = requests.get(f"{BASE_URL}/license/check")
return response.json()
def create_task(serials, script_name, script_config=None, multi_account=False):
"""Створити нову задачу"""
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):
"""Вивести задачі з необов'язковими фільтрами"""
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):
"""Отримати деталі задачі"""
response = requests.get(f"{BASE_URL}/task/{task_id}")
return response.json()
def delete_task(task_id):
"""Видалити задачу"""
response = requests.delete(f"{BASE_URL}/task/{task_id}")
return response.json()
def stop_task(task_id):
"""Зупинити задачу, що виконується"""
response = requests.post(f"{BASE_URL}/task/{task_id}/stop")
return response.json()
def retry_task(task_id):
"""Повторити невдалу задачу"""
response = requests.post(f"{BASE_URL}/task/{task_id}/retry")
return response.json()
def get_stats():
"""Отримати статистику задач"""
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_user": "@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_user: '@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_user": "@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
}
function Stop-TaskById {
param([int]$TaskId)
$response = Invoke-RestMethod -Uri "$BaseUrl/task/$TaskId/stop" -Method Post
return $response
}
function Remove-TaskById {
param([int]$TaskId)
$response = Invoke-RestMethod -Uri "$BaseUrl/task/$TaskId" -Method Delete
return $response
}
# Приклад використання
$license = Check-License
if ($license.code -ne 0) {
Write-Error "Доступ до API недоступний: $($license.message)"
exit 1
}
Write-Host "Ліцензія в порядку: $($license.data.plan_name)"
# Створити задачу
$result = Create-Task -Serials @("device_serial_1") `
-ScriptName "follow" `
-ScriptConfig @{ target_user = "@tikmatrix" }
Write-Host "Задачу створено: $($result | ConvertTo-Json)"