LiveMira API
EN
My account

TikTok LIVE chest and bag data API

LIVE rooms that currently have a valid chest or bag, with room_id. Delivered over WebSocket or HTTP polling: first every valid item of the tab, then changes only.

ContentsPricing and how to rentQuick startData tabsEndpoint and keyHow data is deliveredWebSocketHTTP pollingItem fieldsHandling notesError and close codesLimits and rulesChangelog

Pricing and how to rent

The API pushes rooms with a valid chest or bag straight into your system, so you do not have to scan TikTok yourself. A good fit for:

Tab idNamePrice for 30 days
c2016Chest 20/162,700,000 coins
cgoldGold chests2,700,000 coins
cr1Ratio 12,700,000 coins
cr2Ratio ≥ 22,700,000 coins
cr4Ratio ≥ 42,700,000 coins
chungHung chests2,700,000 coins
cluckLucky picks2,700,000 coins
b2Bags level 2–102,700,000 coins
b1Bags level 12,700,000 coins
b0Bags level 02,700,000 coins

How to rent

  1. Sign in or sign up on the account page.
  2. Top up your wallet.
  3. In the Chest and bag data API section, click + Rent an API, pick a tab and pay from the wallet.
  4. Click Connection details to get your endpoint, key and ready-filled samples.

Rent an API on the account page

Quick start

  1. Rent an API on the account page to get a key (lmk_…) and a private endpoint (https://apibot.dichvu321.com/g/…).
  2. Open Connection details for samples with your values filled in, or use the WebSocket and HTTP samples below.

Prefer WebSocket. Use HTTP polling when you cannot hold a long-lived connection. Both return the same data.

Data tabs

Each API is one tab. A key only receives the tab it was rented for. For several tabs, rent several APIs (each has its own key and endpoint).

Tab idNameWhat the tab contains
c2016Chest 20/16Counting-down chests with a ratio of 1.2 to 1.25 (for example 20 coins for 16 winners) and at least 20 coins
cgoldGold chestsCounting-down gold chests
cr1Ratio 1Chests where coins equal the number of winners
cr2Ratio ≥ 2Chests with a ratio of 2 or more
cr4Ratio ≥ 4Chests with a ratio of 4 or more
cluckLucky picksChests with a ratio of 7 or more (many coins, few winners)
chungHung chestsChests whose open time has passed but are still hanging in the room, kept for up to 15 minutes
b2Bags level 2–10Bags that require level 2 to 10
b1Bags level 1Bags that require level 1
b0Bags level 0Bags with no level requirement

Ratio = coins divided by winners. Except for chung, chest tabs only contain counting-down chests, not hung ones.

Endpoint and key

How data is delivered

  1. Snapshot: the first response holds every valid item of the tab, sorted by expiry ascending. Replace your whole list with it.
  2. Delta: events are new or changed items, upsert by id; removed lists the ids to delete.
  3. Reconnecting (or calling /v1/connect again) yields a fresh snapshot.

A busy tab can exceed 1,000 items, so a snapshot is roughly 100–500 KB. With HTTP, send Accept-Encoding: gzip.

WebSocket

Connect to wss://apibot.dichvu321.com/g/YOUR_GATE/v1/stream with the Authorization header. The server then sends:

typeWhenContent
helloRight after connectingtab, server_ms, expires_at (plan expiry, Unix seconds), heartbeat_s
snapshotRight after hello, onceseq, server_ms, events (every valid item), removed (empty)
deltaWhenever something changes, at most every 0.4 sseq, server_ms, events, removed
heartbeatEvery 15 secondsserver_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 -> item

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 polling

Base URL: https://apibot.dichvu321.com/g/YOUR_GATE/v1. Every request carries Authorization: Bearer lmk_….

StepRequestResult
1POST /v1/connectsession, tab, poll_ms (3000), lease_s (30), expires_at. Call once at start-up.
2GET /v1/events
X-Session: <session>
First call, without cursor: returns "type":"snapshot" with every valid item and a cursor.
3GET /v1/events?cursor=N
X-Session: <session>
Every 3 seconds, send the cursor you last received. 200 is a "type":"delta" with a new cursor; 204 means nothing new (keep the same cursor).
bash
# 1. Open a session
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. First read: every valid item
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. Later reads: changes only
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  (nothing new)
# 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 -> item
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)          # retry with the same 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                   # nothing new
    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: stop, do not reconnect
    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; }           // retry with the same 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 => item
$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;                // network error: retry with the same cursor
    } elseif ($status === 429) {
        sleep($retry); continue;
    } elseif ($status === 409 && ($d["code"] ?? "") === "session_expired") {
        $session = connect(); $cursor = null; continue;
    } elseif ($status !== 204) {           // 204: nothing new
        exit("$status " . json_encode($d) . "\n");   // kicked, locked, expired: stop, do not reconnect
    }
    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 -> item
	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: // nothing new
		case status == 0: // network error: retry with the same 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: stop, do not reconnect
			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) Open a session, once at startup
curl -s -X POST "$BASE/connect" -H "Authorization: Bearer $KEY"
# -> {"session":"...","tab":"...","poll_ms":3000,"lease_s":30,...}

# 2) First call: every item still valid (type "snapshot")
curl -s --compressed "$BASE/events" -H "Authorization: Bearer $KEY" -H "X-Session: SESSION"
# -> {"type":"snapshot","cursor":123456,"events":[...],"removed":[]}

# 3) Then every 3 s: only the changes since the cursor you just got. 204 = nothing new
curl -s --compressed "$BASE/events?cursor=CURSOR" -H "Authorization: Bearer $KEY" -H "X-Session: SESSION"

Item fields

FieldTypeMeaning
idstringUnique item id, chest:… or bag:…. Use it as the key for updates and removals.
kindstringchest (chest) or bag (bag)
room_idstringThe real TikTok LIVE room id. Always a string, because the number is too large for JavaScript numbers.
creatorstringUsername (uniqueId) of the room owner
total_coinsintTotal coins in the chest or bag
winner_countintNumber of winner slots
participant_countint | nullBags only: number of people who joined. null when not known yet.
viewer_countint | nullCurrent viewers in the room, approximate
rationumber | nulltotal_coins / winner_count, rounded to 4 decimals
opens_at_msintWhen the chest or bag opens, Unix milliseconds
expires_at_msintWhen the item stops being valid. For counting-down chests and bags it equals opens_at_ms. For hung chests it is opens_at_ms plus 15 minutes.
chest_typestring | nullnormal, gold; null for bags
chest_statusstring | nullactive (counting down), hung (hung); null for bags
bag_levelint | nullRequired level of the bag, 0 to 10; null for chests
bag_methodint | nullHow to join the bag: 1 comment, 2 share, 3 tap join
bag_commentstring | nullThe text to comment when bag_method is 1, up to 80 characters
country_codestring | nullCountry code of the room owner, when known
rank_labelstring | nullRank label of the room owner, when known
event_labelstring | nullGift name for event chests, when present

Fields marked null may be empty on first delivery and filled in later by a delta with the same id. New fields may be added in the future; ignore fields you do not know.

Handling notes

Error and close codes

HTTP errors return JSON {"code":"…","message":"…","message_en":"…"}, sometimes with retry_after (seconds). Branch on code.

HTTPcodeWhat it meansWhat to do
401invalid_keyWrong keyCheck the key
402expiredPlan expiredRenew within 7 days to keep the key and endpoint
403browser_blockedRequest sent from a web page in a browserCall from a script or server
403revokedKey revokedStop, contact support
404—Wrong endpoint, or the API expired more than 7 days ago and its gate is gone (empty body)Check the endpoint on the account page. If the hold period has passed, rent again to get a new key and endpoint
409kickedAnother stream took overStop, do not reconnect automatically
409session_expiredSession expired after 30 seconds without pollingCall /v1/connect again
409cursor_conflictCursor mismatchCheck the client; one reader per key
423lockedKey temporarily lockedWait for retry_after
426upgrade_requiredPlain GET on /v1/streamUse wss://
429rate_limitedToo many requestsWait for Retry-After

WebSocket close codes

CodeWhat it meansWhat to do
4001Another stream took overStop, do not reconnect automatically
4002Plan expiredRenew, then start again
4003Key no longer valid or temporarily lockedStop and check the status on the account page
1012Server restartingReconnect after a few seconds
1013Your side reads too slowlyReconnect and process items faster

Limits and rules

Changelog