LiveMira API
KO
내 계정

TikTok LIVE 보물상자·럭키백 데이터 API

현재 유효한 보물상자 또는 럭키백이 있는 LIVE 방을 room_id와 함께 제공합니다. WebSocket 또는 HTTP 폴링으로 전달되며, 먼저 탭의 모든 유효 항목을 보낸 뒤 이후에는 변경 사항만 보냅니다.

목차요금 및 임대 방법빠른 시작데이터 탭엔드포인트 및 키데이터 전달 방식WebSocketHTTP 폴링항목 필드처리 시 참고 사항오류 코드 및 종료 코드제한 및 규칙변경 내역

요금 및 임대 방법

API는 유효한 보물상자나 럭키백이 있는 방을 고객님의 시스템으로 바로 보내 주므로 직접 TikTok을 스캔할 필요가 없습니다. 다음 용도에 적합합니다:

탭 id이름30일 요금
c2016보물상자 20/162,700,000 코인
cgold골드 보물상자2,700,000 코인
cr1Ratio 12,700,000 코인
cr2Ratio ≥ 22,700,000 코인
cr4Ratio ≥ 42,700,000 코인
chung보류된 상자2,700,000 코인
cluck추천 대박방2,700,000 코인
b2럭키백 레벨 2–102,700,000 코인
b1럭키백 레벨 12,700,000 코인
b0럭키백 레벨 02,700,000 코인

임대 방법

  1. 계정 페이지에서 로그인하거나 가입하세요.
  2. 지갑을 충전하세요.
  3. 보물상자·럭키백 데이터 API 섹션에서 + API 임대를 클릭하고 탭을 선택한 후 지갑으로 결제하세요.
  4. 연결 정보를 클릭하면 엔드포인트, 키, 값이 채워진 샘플을 받을 수 있습니다.

계정 페이지에서 API 임대

빠른 시작

  1. 계정 페이지에서 API를 임대하면 키(lmk_…)와 전용 엔드포인트(https://apibot.dichvu321.com/g/…)를 받습니다.
  2. 연결 정보를 열어 값이 채워진 샘플을 보거나, 아래의 WebSocket 및 HTTP 샘플을 사용하세요.

WebSocket을 권장합니다. 장시간 연결을 유지할 수 없을 때는 HTTP 폴링을 사용하세요. 두 방식 모두 같은 데이터를 반환합니다.

데이터 탭

각 API는 하나의 탭입니다. 키는 임대한 탭의 데이터만 받습니다. 여러 탭이 필요하면 여러 API를 임대하세요(각각 고유한 키와 엔드포인트가 있습니다).

탭 id이름탭에 포함된 내용
c2016보물상자 20/16비율 1.2~1.25(예: 코인 20개에 당첨자 16명), 코인 20개 이상인 카운트다운 중인 보물상자
cgold골드 보물상자카운트다운 중인 골드 보물상자
cr1Ratio 1코인 수와 당첨자 수가 같은 보물상자
cr2Ratio ≥ 2비율 2 이상인 보물상자
cr4Ratio ≥ 4비율 4 이상인 보물상자
cluck추천 대박방비율 7 이상인 보물상자(코인은 많고 당첨자는 적음)
chung보류된 상자열림 시간이 지났지만 아직 방에 남아 있는 보물상자, 최대 15분간 유지
b2럭키백 레벨 2–10레벨 2~10이 필요한 럭키백
b1럭키백 레벨 1레벨 1이 필요한 럭키백
b0럭키백 레벨 0레벨 조건이 없는 럭키백

비율 = 코인 수 ÷ 당첨자 수. chung을 제외한 보물상자 탭에는 카운트다운 중인 상자만 포함되며 보류된 상자는 포함되지 않습니다.

엔드포인트 및 키

데이터 전달 방식

  1. 스냅샷: 첫 응답에는 탭의 모든 유효 항목이 만료 시간 오름차순으로 포함됩니다. 기존 목록 전체를 이것으로 교체하세요.
  2. 델타: events는 새로 생기거나 변경된 항목으로, id 기준으로 upsert합니다. removed는 삭제할 id 목록입니다.
  3. 다시 연결하면(또는 /v1/connect를 다시 호출하면) 새 스냅샷을 받습니다.

혼잡한 탭은 1,000개 항목을 넘을 수 있어 스냅샷이 약 100~500 KB가 됩니다. HTTP에서는 Accept-Encoding: gzip을 보내세요.

WebSocket

Authorization 헤더와 함께 wss://apibot.dichvu321.com/g/YOUR_GATE/v1/stream에 연결하세요. 그러면 서버가 다음을 보냅니다:

type시점내용
hello연결 직후tab, server_ms, expires_at (플랜 만료 시간, Unix 초), heartbeat_s
snapshothello 직후 1회seq, server_ms, events (모든 유효 항목), removed (비어 있음)
delta변경이 있을 때마다, 최대 0.4초마다seq, server_ms, events, removed
heartbeat15초마다server_ms
json
{"type":"hello","tab":"c2016","server_ms":1794265258000,"expires_at":1796857258,"heartbeat_s":15}
{"type":"snapshot","seq":1,"server_ms":1794265258010,"events":[{"id":"chest:7706291234567890123","kind":"chest","room_id":"7706290000000000001","creator":"example_user","total_coins":100,"winner_count":80,"participant_count":null,"viewer_count":112,"ratio":1.25,"opens_at_ms":1794265318000,"expires_at_ms":1794265318000,"chest_type":"normal","chest_status":"active","bag_level":null,"bag_method":null,"bag_comment":null,"country_code":null,"rank_label":null,"event_label":null}],"removed":[]}
{"type":"delta","seq":2,"server_ms":1794265261400,"events":[],"removed":["chest:7706291234567890123"]}
{"type":"heartbeat","server_ms":1794265273000}

Python

python
# pip install "websockets>=14"
import asyncio, json, websockets

URL = "wss://apibot.dichvu321.com/g/YOUR_GATE/v1/stream"
HEADERS = {"Authorization": "Bearer lmk_..."}
items = {}  # id -> 항목

def apply(msg):
    for e in msg["events"]:
        items[e["id"]] = e
    for i in msg["removed"]:
        items.pop(i, None)

async def main():
    delay = 1
    while True:
        try:
            async with websockets.connect(URL, additional_headers=HEADERS, open_timeout=10, max_size=None) as ws:
                delay = 1
                while True:
                    msg = json.loads(await asyncio.wait_for(ws.recv(), 45))
                    if msg["type"] == "snapshot":
                        items.clear()
                        apply(msg)
                        print("snapshot:", len(items))
                    elif msg["type"] == "delta":
                        apply(msg)
                        for e in msg["events"]:
                            print(e["room_id"], e["creator"], e["total_coins"], e["expires_at_ms"])
        except websockets.InvalidStatus as e:
            raise SystemExit(f"HTTP {e.response.status_code}")   # 401, 402, 403, 404, 423, 429
        except websockets.ConnectionClosed as e:
            if e.rcvd and e.rcvd.code in (4001, 4002, 4003):
                raise SystemExit(f"closed {e.rcvd.code} {e.rcvd.reason}")
        except (OSError, TimeoutError):
            pass
        await asyncio.sleep(delay)
        delay = min(delay * 2, 15)

asyncio.run(main())

Node.js

javascript
// npm i ws
const WebSocket = require("ws");
const URL = "wss://apibot.dichvu321.com/g/YOUR_GATE/v1/stream";
const HEADERS = { Authorization: "Bearer lmk_..." };
const items = new Map();
let delay = 1000;

function connect() {
  const ws = new WebSocket(URL, { headers: HEADERS, handshakeTimeout: 10000 });
  let timer;
  const alive = () => { clearTimeout(timer); timer = setTimeout(() => ws.terminate(), 45000); };
  ws.on("open", () => { delay = 1000; alive(); });
  ws.on("ping", alive);
  ws.on("message", (data) => {
    alive();
    const msg = JSON.parse(data);
    if (msg.type === "snapshot") items.clear();
    if (msg.type === "snapshot" || msg.type === "delta") {
      for (const e of msg.events) items.set(e.id, e);
      for (const id of msg.removed) items.delete(id);
      console.log(msg.type, "items:", items.size);
    }
  });
  ws.on("unexpected-response", (req, res) => { console.error("HTTP", res.statusCode); process.exit(1); });
  ws.on("error", () => {});
  ws.on("close", (code, reason) => {
    clearTimeout(timer);
    if ([4001, 4002, 4003].includes(code)) { console.error("closed", code, String(reason)); process.exit(1); }
    setTimeout(connect, delay);
    delay = Math.min(delay * 2, 15000);
  });
}
connect();

HTTP 폴링

기본 URL: https://apibot.dichvu321.com/g/YOUR_GATE/v1. 모든 요청에 Authorization: Bearer lmk_…를 포함합니다.

단계요청결과
1POST /v1/connectsession, tab, poll_ms(3000), lease_s(30), expires_at. 시작 시 한 번 호출합니다.
2GET /v1/events
X-Session: <session>
첫 호출은 cursor 없이 합니다: 모든 유효 항목과 cursor가 포함된 "type":"snapshot"을 반환합니다.
3GET /v1/events?cursor=N
X-Session: <session>
3초마다 마지막으로 받은 cursor를 보내세요. 200은 새 cursor가 포함된 "type":"delta"이고, 204는 새 변경 없음(같은 cursor 유지)을 뜻합니다.
bash
# 1. 세션 열기
curl -s -X POST "https://apibot.dichvu321.com/g/YOUR_GATE/v1/connect" -H "Authorization: Bearer lmk_..."
# {"session":"Zm9v...","tab":"c2016","poll_ms":3000,"lease_s":30,"expires_at":1796857258}

# 2. 첫 읽기: 모든 유효 항목
curl -s --compressed "https://apibot.dichvu321.com/g/YOUR_GATE/v1/events" -H "Authorization: Bearer lmk_..." -H "X-Session: Zm9v..."
# {"type":"snapshot","cursor":8412731,"server_ms":1794265258010,"events":[...],"removed":[]}

# 3. 이후 읽기: 변경 사항만
curl -s --compressed -i "https://apibot.dichvu321.com/g/YOUR_GATE/v1/events?cursor=8412731" -H "Authorization: Bearer lmk_..." -H "X-Session: Zm9v..."
# HTTP 204  (새 변경 없음)
# HTTP 200  {"type":"delta","cursor":8412732,"server_ms":1794265261400,"events":[...],"removed":["chest:..."]}

Python

python
# pip install requests
import time, requests

BASE = "https://apibot.dichvu321.com/g/YOUR_GATE/v1"
H = {"Authorization": "Bearer lmk_...", "User-Agent": "my-system/1.0"}
items = {}  # id -> 항목
http = requests.Session()

def connect():
    r = http.post(BASE + "/connect", headers=H, timeout=10)
    r.raise_for_status()
    return r.json()["session"]

session, cursor = connect(), None
while True:
    try:
        r = http.get(BASE + "/events", headers={**H, "X-Session": session},
                     params={"cursor": cursor} if cursor else None, timeout=10)
    except requests.RequestException:
        time.sleep(1)          # 같은 cursor로 재시도
        continue
    if r.status_code == 200:
        d = r.json()
        if d["type"] == "snapshot":
            items.clear()
        cursor = d["cursor"]
        for e in d["events"]:
            items[e["id"]] = e
        for i in d["removed"]:
            items.pop(i, None)
        print(d["type"], "items:", len(items))
    elif r.status_code == 204:
        pass                   # 새 변경 없음
    elif r.status_code == 429:
        time.sleep(int(r.headers.get("Retry-After", 2)))
        continue
    elif r.status_code == 409 and r.json().get("code") == "session_expired":
        session, cursor = connect(), None
        continue
    else:
        raise SystemExit(f"{r.status_code} {r.text}")   # kicked, locked, expired: 중지, 다시 연결하지 않음
    time.sleep(3)

Node.js

javascript
// npm i axios
const axios = require("axios");
const http = axios.create({
  baseURL: "https://apibot.dichvu321.com/g/YOUR_GATE/v1",
  headers: { Authorization: "Bearer lmk_...", "User-Agent": "my-system/1.0" },
  timeout: 10000,
  validateStatus: () => true,
});
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const items = new Map();

async function connect() {
  const r = await http.post("/connect");
  if (r.status !== 200) throw new Error(`connect ${r.status} ${JSON.stringify(r.data)}`);
  return r.data.session;
}

(async () => {
  let session = await connect(), cursor = null;
  for (;;) {
    let r;
    try {
      r = await http.get("/events", { headers: { "X-Session": session }, params: cursor ? { cursor } : {} });
    } catch { await sleep(1000); continue; }           // 같은 cursor로 재시도
    if (r.status === 200) {
      if (r.data.type === "snapshot") items.clear();
      cursor = r.data.cursor;
      for (const e of r.data.events) items.set(e.id, e);
      for (const id of r.data.removed) items.delete(id);
      console.log(r.data.type, "items:", items.size);
    } else if (r.status === 429) {
      await sleep(Number(r.headers["retry-after"] || 2) * 1000); continue;
    } else if (r.status === 409 && r.data.code === "session_expired") {
      session = await connect(); cursor = null; continue;
    } else if (r.status !== 204) {
      throw new Error(`${r.status} ${JSON.stringify(r.data)}`);   // kicked, locked, expired
    }
    await sleep(3000);
  }
})();

PHP

php
<?php
// php poll.php
const BASE = "https://apibot.dichvu321.com/g/YOUR_GATE/v1";
const KEY  = "lmk_...";

function call(string $method, string $path, string $session = ""): array {
    $headers = ["Authorization: Bearer " . KEY, "User-Agent: my-system/1.0"];
    if ($session !== "") $headers[] = "X-Session: " . $session;
    $ch = curl_init(BASE . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER => true, CURLOPT_ENCODING => "", CURLOPT_TIMEOUT => 10,
    ]);
    $raw = curl_exec($ch);
    if ($raw === false) return [0, null, 1];
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $head = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $retry = preg_match('/^retry-after:\s*(\d+)/mi', substr($raw, 0, $head), $m) ? (int) $m[1] : 2;
    return [$status, json_decode(substr($raw, $head), true), $retry];
}

function connect(): string {
    [$status, $d] = call("POST", "/connect");
    if ($status !== 200) exit("connect $status " . json_encode($d) . "\n");
    return $d["session"];
}

$items = [];   // id => 항목
$session = connect();
$cursor = null;
while (true) {
    [$status, $d, $retry] = call("GET", "/events" . ($cursor === null ? "" : "?cursor=" . $cursor), $session);
    if ($status === 200) {
        if ($d["type"] === "snapshot") $items = [];
        $cursor = $d["cursor"];
        foreach ($d["events"] as $e) $items[$e["id"]] = $e;
        foreach ($d["removed"] as $id) unset($items[$id]);
        echo $d["type"], " items: ", count($items), "\n";
    } elseif ($status === 0) {
        sleep(1); continue;                // 네트워크 오류: 같은 cursor로 재시도
    } elseif ($status === 429) {
        sleep($retry); continue;
    } elseif ($status === 409 && ($d["code"] ?? "") === "session_expired") {
        $session = connect(); $cursor = null; continue;
    } elseif ($status !== 204) {           // 204: 새 변경 없음
        exit("$status " . json_encode($d) . "\n");   // kicked, locked, expired: 중지, 다시 연결하지 않음
    }
    sleep(3);
}

Go

go
// go run main.go
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
	"time"
)

const base = "https://apibot.dichvu321.com/g/YOUR_GATE/v1"
const key = "lmk_..."

type reply struct {
	Type    string           `json:"type"`
	Cursor  int64            `json:"cursor"`
	Events  []map[string]any `json:"events"`
	Removed []string         `json:"removed"`
	Session string           `json:"session"`
	Code    string           `json:"code"`
}

var client = &http.Client{Timeout: 10 * time.Second}

func call(method, path, session string) (int, reply, time.Duration) {
	var d reply
	req, _ := http.NewRequest(method, base+path, nil)
	req.Header.Set("Authorization", "Bearer "+key)
	req.Header.Set("User-Agent", "my-system/1.0")
	if session != "" {
		req.Header.Set("X-Session", session)
	}
	res, err := client.Do(req)
	if err != nil {
		return 0, d, time.Second
	}
	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)
	json.Unmarshal(body, &d)
	retry, _ := strconv.Atoi(res.Header.Get("Retry-After"))
	if retry < 1 {
		retry = 2
	}
	return res.StatusCode, d, time.Duration(retry) * time.Second
}

func connect() string {
	status, d, _ := call("POST", "/connect", "")
	if status != 200 {
		fmt.Println("connect", status, d.Code)
		os.Exit(1)
	}
	return d.Session
}

func main() {
	items := map[string]map[string]any{} // id -> 항목
	session, path := connect(), "/events"
	for {
		status, d, retry := call("GET", path, session)
		switch {
		case status == 200:
			if d.Type == "snapshot" {
				clear(items)
			}
			path = "/events?cursor=" + strconv.FormatInt(d.Cursor, 10)
			for _, e := range d.Events {
				items[e["id"].(string)] = e
			}
			for _, id := range d.Removed {
				delete(items, id)
			}
			fmt.Println(d.Type, "items:", len(items))
		case status == 204: // 새 변경 없음
		case status == 0: // 네트워크 오류: 같은 cursor로 재시도
			time.Sleep(retry)
			continue
		case status == 429:
			time.Sleep(retry)
			continue
		case status == 409 && d.Code == "session_expired":
			session, path = connect(), "/events"
			continue
		default: // kicked, locked, expired: 중지, 다시 연결하지 않음
			fmt.Println(status, d.Code)
			os.Exit(1)
		}
		time.Sleep(3 * time.Second)
	}
}

cURL

bash
BASE="https://apibot.dichvu321.com/g/YOUR_GATE/v1"
KEY="lmk_..."

# 1) 세션 열기, 시작 시 1회
curl -s -X POST "$BASE/connect" -H "Authorization: Bearer $KEY"
# -> {"session":"...","tab":"...","poll_ms":3000,"lease_s":30,...}

# 2) 첫 호출: 아직 유효한 모든 항목(type "snapshot")
curl -s --compressed "$BASE/events" -H "Authorization: Bearer $KEY" -H "X-Session: SESSION"
# -> {"type":"snapshot","cursor":123456,"events":[...],"removed":[]}

# 3) 이후 3초마다: 방금 받은 cursor 이후의 변경 사항만. 204 = 새 변경 없음
curl -s --compressed "$BASE/events?cursor=CURSOR" -H "Authorization: Bearer $KEY" -H "X-Session: SESSION"

항목 필드

필드유형의미
idstring항목의 고유 id, chest:… 또는 bag:…. 업데이트와 삭제의 키로 사용하세요.
kindstringchest(보물상자) 또는 bag(럭키백)
room_idstring실제 TikTok LIVE 방 id. 숫자가 JavaScript 숫자형에 비해 너무 크므로 항상 문자열입니다.
creatorstring방 주인의 사용자 이름(uniqueId)
total_coinsint보물상자 또는 럭키백의 총 코인
winner_countint당첨 자리 수
participant_countint | null럭키백만 해당: 참여 인원. 아직 알 수 없으면 null.
viewer_countint | null방의 현재 시청자 수(대략)
rationumber | nulltotal_coins / winner_count, 소수점 4자리로 반올림
opens_at_msint보물상자 또는 럭키백이 열리는 시각, Unix 밀리초
expires_at_msint항목이 유효하지 않게 되는 시각. 카운트다운 중인 보물상자와 럭키백은 opens_at_ms와 같습니다. 보류된 상자는 opens_at_ms에 15분을 더한 값입니다.
chest_typestring | nullnormal, gold; 럭키백은 null
chest_statusstring | nullactive(카운트다운 중), hung(보류됨); 럭키백은 null
bag_levelint | null럭키백의 필요 레벨, 0~10; 보물상자는 null
bag_methodint | null럭키백 참여 방법: 1 댓글, 2 공유, 3 참여 누르기
bag_commentstring | nullbag_method가 1일 때 댓글로 달 텍스트, 최대 80자
country_codestring | null방 주인의 국가 코드(알려진 경우)
rank_labelstring | null방 주인의 랭크 라벨(알려진 경우)
event_labelstring | null이벤트 보물상자의 선물 이름(있는 경우)

null로 표시된 필드는 처음 전달될 때 비어 있을 수 있으며, 나중에 같은 id의 delta로 채워집니다. 향후 새 필드가 추가될 수 있으니 모르는 필드는 무시하세요.

처리 시 참고 사항

오류 코드 및 종료 코드

HTTP 오류는 JSON {"code":"…","message":"…","message_en":"…"}를 반환하며, 때로는 retry_after(초)가 포함됩니다. code로 분기하세요.

HTTPcode의미조치 방법
401invalid_key잘못된 키키를 확인하세요
402expired플랜 만료키와 엔드포인트를 유지하려면 7일 이내에 연장하세요
403browser_blocked브라우저의 웹 페이지에서 보낸 요청스크립트나 서버에서 호출하세요
403revoked키 폐기됨중지하고 고객지원에 문의하세요
404—엔드포인트가 잘못되었거나, API가 만료된 지 7일이 넘어 게이트가 사라졌습니다(빈 본문)계정 페이지에서 엔드포인트를 확인하세요. 보존 기간이 지났다면 다시 임대하여 새 키와 엔드포인트를 받으세요
409kicked다른 스트림이 대체함중지하고 자동으로 다시 연결하지 마세요
409session_expired30초 동안 폴링이 없어 세션이 만료됨/v1/connect를 다시 호출하세요
409cursor_conflictcursor 불일치클라이언트를 확인하세요. 키당 읽기 주체는 하나입니다
423locked키가 일시적으로 잠김retry_after만큼 기다리세요
426upgrade_required/v1/stream에 일반 GET 요청wss://를 사용하세요
429rate_limited요청이 너무 많음Retry-After만큼 기다리세요

WebSocket 종료 코드

코드의미조치 방법
4001다른 스트림이 대체함중지하고 자동으로 다시 연결하지 마세요
4002플랜 만료연장한 후 다시 시작하세요
4003키가 더 이상 유효하지 않거나 일시적으로 잠김중지하고 계정 페이지에서 상태를 확인하세요
1012서버 재시작 중몇 초 후 다시 연결하세요
1013고객님 쪽의 읽기 속도가 너무 느림다시 연결하고 항목을 더 빠르게 처리하세요

제한 및 규칙

변경 내역