TwexAPI で XChat 会話一覧を取得する方法
DM history を export する前に、どの conversation が存在するかを把握する必要があります。Support system、CRM sync、compliance archive は、多くの場合 inbox list から始まります。必要なのは conversation ID、direct/group type、muted state、participant user IDs です。
TwexAPI の Get Conversations (XChat v3) endpoint は、POST /v3/twitter/conversations で XChat conversation list を返します。
この endpoint は conversation を一覧するものです。Message history、media files、message text は返しません。Conversation inventory を作り、full message export が必要な conversation に対して POST /v3/twitter/dm-history を呼びます。
Endpoint と Request Fields
Authenticated account の XChat conversations を一覧するには POST /v3/twitter/conversations を使います。
| Field | Type | Required | Notes |
|---|---|---|---|
cookie | string | Yes | X authentication cookie または auth_token。server-side に保管します。 |
count | integer or null | No | Page size は 10 から 200。Job behavior を安定させるため明示します。 |
all | boolean or null | No | true の場合、inbox cursor をたどって全 conversations を返します。大きい inbox では遅くなることがあります。 |
proxy | string or null | No | Optional HTTP proxy。 |
Basic Request
curl --request POST \
--url https://api.twexapi.io/v3/twitter/conversations \
--header "Authorization: Bearer $TWEXAPI_BEARER_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"cookie": "auth_token=...; ct0=...; twid=...",
"count": 100,
"all": false
}'response は data に conversation objects の array を返します。
1{
2 "code": 200,
3 "msg": "success",
4 "data": [
5 {
6 "conversation_id": "1928096185664843776:1989842918455291904",
7 "type": "direct",
8 "is_muted": false,
9 "participants": [
10 "1928096185664843776",
11 "1989842918455291904"
12 ]
13 },
14 {
15 "conversation_id": "g1234567890",
16 "type": "group",
17 "is_muted": false,
18 "participants": [
19 "1928096185664843776",
20 "1989842918455291904",
21 "1234567890123456789"
22 ]
23 }
24 ]
25}conversation_id を stable key として保存します。Direct conversation は a:b のような形、group conversation は g... で始まる場合があります。
Python Conversation Sync
この script は conversation list を読み、後続の history export に使える normalized rows を保存します。
1import os
2from datetime import datetime, timezone
3from typing import Any
4
5import requests
6
7API_URL = "https://api.twexapi.io/v3/twitter/conversations"
8BEARER_TOKEN = os.environ["TWEXAPI_BEARER_TOKEN"]
9X_COOKIE = os.environ["TWEXAPI_X_COOKIE"]
10PROXY = os.environ.get("TWEXAPI_PROXY")
11
12def fetch_conversations(
13 *,
14 count: int = 100,
15 all_conversations: bool = False,
16) -> list[dict[str, Any]]:
17 if count < 10 or count > 200:
18 raise ValueError("count must be between 10 and 200")
19
20 payload: dict[str, Any] = {
21 "cookie": X_COOKIE,
22 "count": count,
23 "all": all_conversations,
24 }
25 if PROXY:
26 payload["proxy"] = PROXY
27
28 response = requests.post(
29 API_URL,
30 headers={
31 "Authorization": f"Bearer {BEARER_TOKEN}",
32 "Content-Type": "application/json",
33 "Accept": "application/json",
34 },
35 json=payload,
36 timeout=90,
37 )
38 response.raise_for_status()
39 data = response.json()
40
41 if data.get("code") != 200:
42 raise RuntimeError(data.get("msg", "TwexAPI returned an error"))
43
44 return data["data"]
45
46def normalize_conversation(
47 account_key: str,
48 conversation: dict[str, Any],
49) -> dict[str, Any]:
50 participants = conversation.get("participants") or []
51 return {
52 "account_key": account_key,
53 "conversation_id": conversation["conversation_id"],
54 "conversation_type": conversation["type"],
55 "is_muted": conversation["is_muted"],
56 "participants": participants,
57 "participant_count": len(participants),
58 "synced_at": datetime.now(timezone.utc).isoformat(),
59 "raw": conversation,
60 }
61
62def conversations_for_history_export(
63 rows: list[dict[str, Any]],
64) -> list[dict[str, Any]]:
65 return [
66 row
67 for row in rows
68 if not row["is_muted"] and row["conversation_type"] in {"direct", "group"}
69 ]
70
71if __name__ == "__main__":
72 account_key = "support_account"
73 conversations = fetch_conversations(count=100, all_conversations=True)
74 rows = [normalize_conversation(account_key, item) for item in conversations]
75 export_queue = conversations_for_history_export(rows)
76
77 print(f"Synced {len(rows)} conversations")
78 print(f"Queued {len(export_queue)} conversations for history checks")Script を実行する前に、server environment に TWEXAPI_BEARER_TOKEN と TWEXAPI_X_COOKIE を設定します。この endpoint は X cookie を必要とするため、browser code から呼ばないでください。
When To Use all=true
Full inbox inventory が必要なときは all=true を使います。たとえば初回 CRM sync や scheduled audit です。API は内部で inbox cursor をたどり、到達できる全 conversations を返します。
Lightweight health check や UI preview では all: false にし、bounded count を指定します。Response は manual cursor field を公開していないため、conversation_id から独自 cursor を作らないでください。
Conversation-to-History Workflow
- List conversations:
POST /v3/twitter/conversationsを呼び、各conversation_idを保存します。 - Classify:
directとgroupを分け、participant IDs を保持します。 - Select: Account、type、muted state、internal policy に基づき、message export が必要な conversations を選びます。
- Export history: 選択した row に対して、
conversation_idをrecipientとしてPOST /v3/twitter/dm-historyを呼びます。 - Resolve media: History messages に attachments がある場合は、対象 media item に
POST /v3/twitter/dm-mediaを呼びます。
Endpoint ごとの役割を分けると整理しやすくなります。Conversations は inbox discovery、history は messages、media は files を扱います。
Fields To Store
| Field | Why it matters |
|---|---|
account_key | どの X account の inbox かを示します。 |
conversation_id | 後続 history export の stable key。 |
conversation_type | direct と group workflow を区別します。 |
is_muted | Prioritization や exclusion rule に使えます。 |
participants | CRM や support record と照合する participant user IDs。 |
participant_count | Direct/group の sanity check。 |
synced_at | Inbox snapshot の取得時刻。 |
| Raw conversation JSON | Schema が変わったときに reprocess できます。 |
Full account cookie を conversation rows に保存しないでください。Credential reference だけを保存します。
Common Mistakes
- この endpoint が message text を返すと思い込む。返るのは conversation objects だけです。
- Large inbox の latency-sensitive request path で
all=trueを使う。 participantsを display names として扱う。これは user IDs です。- Group conversation ID が
a:bに見えないため group conversation を捨てる。 - Response が manual cursor を公開していないのに、
conversation_idから fake cursor を作る。
Wrap-up
POST /v3/twitter/conversations で XChat inbox inventory を作ります。保存する主な値は conversation_id、type、is_muted、participants です。その後、必要な thread を dm-history に渡し、media が必要な場合は dm-media へ進めます。