API で XChat DM 履歴を取得する方法

著者:TwexAPI Team
JA
他の言語:
日本語
English中文
TwexAPI
XChat
DM History
Direct Messages
API Tutorial
CRM

TwexAPI の Get DM History (XChat v3) endpoint で 1:1 または conversation の DM 履歴を取得し、`before` でページングし、sequence_id を監査と CRM 同期のために保存します。

Quick Answer

TwexAPI の Get DM History (XChat v3) endpoint、POST /v3/twitter/dm-history を使うと、user ID、@handle、conversation ID a:b、または group ID g... で XChat conversation history を取得できます。必須 fields は recipient と cookie。任意 fields は pin、10〜200 の count、all、before、proxy です。信頼できる export では all: false にし、page を保存してから、has_more が true の間は最古 message の sequence_id を次の before にします。

FAQ

XChat DM 履歴取得に使う endpoint は?

https://api.twexapi.io の POST /v3/twitter/dm-history を使います。Bearer token で認証し、JSON に recipient と cookie を渡します。pin、count、all、before、proxy は任意です。

DM history の pagination はどう動きますか?

all: false と 10〜200 の count で 1 page を取得します。response が has_more: true の場合、その page の最古 message の sequence_id を次 request の before に渡します。

DM history export で保存すべき field は?

conversation_id、message id、sequence_id、time、sender_id、recipient_id、text、attachment metadata、fetched_at、raw message JSON を保存します。cookie は値ではなく secret reference を保存します。

DM history は、どのように取得したか説明できる場合に価値があります。support ticket、CRM sync、partnership log では、conversation ID、message IDs、timestamps、sender/recipient IDs、attachments、どこまで export したかを示す pagination cursor が必要です。

TwexAPI の Get DM History (XChat v3) endpoint は、XChat conversation history を取得します。1:1 workflow では、recipient に user ID、@handle、または 1928096185664843776:1989842918455291904 のような conversation ID を渡せます。

Endpoint and Request Fields

Answer: Endpoint and Request Fieldsは本ガイドの TwexAPI エンドポイントを Bearer で呼び出して実装します。バッチ/ページングで約 5 Credits/回・20+ QPS です。

XChat conversation を読むには POST /v3/twitter/dm-history を使います。

FieldTypeRequiredNotes
recipientstringYesUser ID、@handle、conversation ID a:b、または group ID g...。
cookiestringYesX authentication cookie または auth_token。server-side に保存します。
pinstring or nullNoIdentity PIN。API default は 1234。
countinteger or nullNopage size は 10 から 200。default は 50。
allboolean or nullNotrue の場合、has_more を辿って全 page を返します。large history では注意。
beforestring or nullNomanual pagination 用。前 page の最古 message の sequence_id を渡します。
proxystring or nullNosession 用 optional HTTP proxy。

Basic Request

Answer: Basic Requestとは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順です。通常の読み取りは 5 Credits(約 $0.05/1K)、対象プランは 20+ QPS です。2026-10-14 時点の公式 Post/User read は $5/$10 per 1K で、rate limit は endpoint ごとに異なります。

curl --request POST \
  --url https://api.twexapi.io/v3/twitter/dm-history \
  --header "Authorization: Bearer $TWEXAPI_BEARER_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
    "recipient": "@example_user",
    "cookie": "auth_token=...; ct0=...; twid=...",
    "pin": "1234",
    "count": 50,
    "all": false
  }'

response は conversation_id、has_more、messages を返します。

1{
2  "code": 200,
3  "msg": "success",
4  "data": {
5    "conversation_id": "1928096185664843776:1989842918455291904",
6    "has_more": true,
7    "messages": [
8      {
9        "id": "1234567890123456789",
10        "text": "Export が正常に動くことを確認しました。",
11        "time": "2024-01-01T12:00:00Z",
12        "sequence_id": "2076661179334979585",
13        "sender_id": "1928096185664843776",
14        "recipient_id": "1989842918455291904",
15        "attachment": null,
16        "attachments": null
17      }
18    ]
19  }
20}

has_more が true の場合、最古 message の sequence_id を取り、次の request の before に渡します。

Python Manual Pagination

Answer: Python Manual Paginationとは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順です。通常の読み取りは 5 Credits(約 $0.05/1K)、対象プランは 20+ QPS です。2026-10-14 時点の公式 Post/User read は $5/$10 per 1K で、rate limit は endpoint ごとに異なります。

manual pagination は all=true より checkpoint を作りやすいです。次の page を取る前に現在 page を保存します。

1import os
2from datetime import datetime, timezone
3from typing import Any
4
5import requests
6
7API_URL = "https://api.twexapi.io/v3/twitter/dm-history"
8BEARER_TOKEN = os.environ["TWEXAPI_BEARER_TOKEN"]
9X_COOKIE = os.environ["TWEXAPI_X_COOKIE"]
10XCHAT_PIN = os.environ.get("TWEXAPI_XCHAT_PIN", "1234")
11PROXY = os.environ.get("TWEXAPI_PROXY")
12
13def fetch_dm_page(
14    recipient: str,
15    *,
16    before: str | None = None,
17    count: int = 50,
18) -> dict[str, Any]:
19    if count < 10 or count > 200:
20        raise ValueError("count must be between 10 and 200")
21
22    payload: dict[str, Any] = {
23        "recipient": recipient,
24        "cookie": X_COOKIE,
25        "pin": XCHAT_PIN,
26        "count": count,
27        "all": False,
28    }
29    if before:
30        payload["before"] = before
31    if PROXY:
32        payload["proxy"] = PROXY
33
34    response = requests.post(
35        API_URL,
36        headers={
37            "Authorization": f"Bearer {BEARER_TOKEN}",
38            "Content-Type": "application/json",
39            "Accept": "application/json",
40        },
41        json=payload,
42        timeout=60,
43    )
44    response.raise_for_status()
45    data = response.json()
46
47    if data.get("code") != 200:
48        raise RuntimeError(data.get("msg", "TwexAPI returned an error"))
49
50    return data["data"]
51
52def normalize_message(conversation_id: str, message: dict[str, Any]) -> dict[str, Any]:
53    return {
54        "conversation_id": conversation_id,
55        "message_id": message["id"],
56        "text": message.get("text"),
57        "time": message.get("time"),
58        "sequence_id": message.get("sequence_id"),
59        "sender_id": message.get("sender_id"),
60        "recipient_id": message.get("recipient_id"),
61        "attachment": message.get("attachment"),
62        "attachments": message.get("attachments"),
63        "fetched_at": datetime.now(timezone.utc).isoformat(),
64        "raw": message,
65    }
66
67def export_history(recipient: str, *, max_pages: int = 10) -> list[dict[str, Any]]:
68    before = None
69    rows: list[dict[str, Any]] = []
70
71    for _ in range(max_pages):
72        page = fetch_dm_page(recipient, before=before)
73        conversation_id = page["conversation_id"]
74        messages = page.get("messages") or []
75
76        rows.extend(normalize_message(conversation_id, msg) for msg in messages)
77
78        if not page.get("has_more") or not messages:
79            break
80
81        oldest = min(
82            messages,
83            key=lambda msg: int(msg.get("sequence_id") or 0),
84        )
85        before = oldest.get("sequence_id")
86        if not before:
87            break
88
89    return rows
90
91if __name__ == "__main__":
92    exported = export_history("@example_user", max_pages=5)
93    print(f"Exported {len(exported)} messages")

production では、次 page に進む前に現在 page を永続化します。job が止まったら、最後に保存した before から再開します。

When To Use all=true

Answer: When To Use all=trueとは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順です。通常の読み取りは 5 Credits(約 $0.05/1K)、対象プランは 20+ QPS です。2026-10-14 時点の公式 Post/User read は $5/$10 per 1K で、rate limit は endpoint ごとに異なります。

all=true は小さい conversation や、明示的に full export が必要な internal tool には便利です。support system、CRM sync、long-running archive では、page ごとに recovery しやすい manual pagination が向いています。

conversation が十分小さく、page-level recovery が不要な場合だけ all=true を使います。

Fields To Store

Answer: Fields To Storeとは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順です。通常の読み取りは 5 Credits(約 $0.05/1K)、対象プランは 20+ QPS です。2026-10-14 時点の公式 Post/User read は $5/$10 per 1K で、rate limit は endpoint ごとに異なります。

FieldWhy it matters
conversation_idAPI が返す stable conversation key。
message_iddedupe と sent message への link。
sequence_idpagination checkpoint と ordering signal。
timeconversation timeline。
sender_id and recipient_iddirection と participant mapping。
textsearch や ticket context。
attachment and attachmentsmedia evidence と XChat v3 attachment metadata。
fetched_atsnapshot time の説明。
Raw message JSONschema change 時の reprocess 用。

message records に account cookie を保存しないでください。credential reference を保存します。

Common Mistakes

Answer: Common Mistakesとは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順です。通常の読み取りは 5 Credits(約 $0.05/1K)、対象プランは 20+ QPS です。2026-10-14 時点の公式 Post/User read は $5/$10 per 1K で、rate limit は endpoint ごとに異なります。

  • large history に all=true を使い、page-level recovery を失う。
  • current page を保存する前に before を保存する。
  • pagination に最新 message の sequence_id を使う。必要なのは最古 message の sequence_id です。
  • @handle を permanent identity として扱う。返却された conversation_id を保存します。
  • 最初の test conversation が text-only だったため attachments を捨てる。

Wrap-up

Answer: Wrap-upとは、この事例で api.twexapi.io の TwexAPI Bearer API を使う手順です。通常の読み取りは 5 Credits(約 $0.05/1K)、対象プランは 20+ QPS です。2026-10-14 時点の公式 Post/User read は $5/$10 per 1K で、rate limit は endpoint ごとに異なります。

POST /v3/twitter/dm-history は user ID、@handle、conversation ID で XChat history を取得できます。信頼できる pattern は manual pagination です。page を取得し、normalized messages と raw JSON を保存し、最古 sequence_id を次の before にして、has_more が true の間続けます。

API で XChat DM 履歴を取得する方法