> ## Documentation Index
> Fetch the complete documentation index at: https://x-preview-mintlify-d8d2882f.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# X Chat のリアルタイムイベント

> chat.received、chat.sent、その他の暗号化された X Chat のアクティビティを Webhook またはアクティビティストリームで受信し、Chat XDK でペイロードを復号します。

X は **`chat.received`**、**`chat.sent`**、および関連する X Chat のアクティビティを、ペイロードに**暗号文**を含めて配信します。[Chat XDK](/ja/xchat/xchat-xdk) で復号してください。

| レイヤー               | 役割                                                                                                                |
| :----------------- | :---------------------------------------------------------------------------------------------------------------- |
| **X Activity API** | `GET /2/activity/stream`; `POST` / `GET` / `PUT` / `DELETE` `/2/activity/subscriptions`(操作ごとに OpenAPI のセキュリティを参照) |
| **Webhook**        | 独自の HTTPS URL で終端する場合はオプションの `POST` / `GET` `/2/webhooks` および `PUT` / `DELETE` `/2/webhooks/{webhook_id}` ルート     |
| **Chat XDK**       | `decrypt_event` / `decrypt_events`、および `set_signing_keys` / `set_cache_keys` のセッションストア                            |

プライベート X Chat のイベントタイプでは、監視するユーザーに対する認可が必要です。暗号化された X Chat のファイル添付は **`media_hash_key`** と X Chat メディアダウンロードを使い、Post API の `expansions=attachments.media_keys` / `media.fields=variants` ではありません。

***

## イベントタイプ

| イベント                     | いつ                       |
| :----------------------- | :----------------------- |
| `chat.received`          | 購読ユーザーが暗号化された DM を受信したとき |
| `chat.sent`              | 購読ユーザーが暗号化された DM を送信したとき |
| `chat.conversation_join` | 購読ユーザーがグループに参加したとき(提供時)  |

***

## 1. 配信方式を選ぶ

**アクティビティストリーム(多くのボットで最もシンプル):** App の Bearer トークンで `GET /2/activity/stream`(OpenAPI に従いオプションで `backfill_minutes`、`start_time`、`end_time`)。クライアント側で `chat.received` / `chat.sent` をフィルタします。

**アクティビティサブスクリプション:** 永続的なサブスクリプションを次で管理します。

* `POST /2/activity/subscriptions` — 作成
* `GET /2/activity/subscriptions` — 一覧(ページング)
* `PUT /2/activity/subscriptions/{subscription_id}` — 更新
* `DELETE /2/activity/subscriptions/{subscription_id}` または `DELETE /2/activity/subscriptions?ids=` — 削除

リクエストボディと必要なスコープは各ルートの OpenAPI 操作で定義されています。X Activity API(XAA)サブスクリプションの作成には、監視するユーザーに対する**ユーザーコンテキスト認可**(OAuth 2.0 のユーザーコンテキストと関連スコープ。チャットイベントには `dm.read` など)が必要です。

**Webhook:** HTTPS エンドポイントでイベントを終端する場合は、`POST /2/webhooks` で Webhook を登録し、CRC チャレンジに応答し、`POST /2/activity/subscriptions` で `webhook_id` を参照するアクティビティサブスクリプションを作成します(OpenAPI の Webhooks と Activity 操作を参照)。Python/TypeScript XDK では、SDK のバージョンに含まれていれば Webhook とアクティビティ用のヘルパーを公開している場合があります。

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from xdk import Client

    # Stream (app token) — exact helper names depend on your XDK version
    stream_client = Client(bearer_token="YOUR_BEARER_TOKEN")
    # for event in stream_client.activity.stream():
    #     handle_payload(event)  # see "Decrypt with the Chat XDK" below

    # Or create a subscription — requires user-context auth for the monitored user
    client = Client(access_token="YOUR_OAUTH2_USER_TOKEN")
    client.activity.create_subscription({
        "event_type": "chat.received",
        "filter": {"user_id": "USER_ID_TO_MONITOR"},
    })
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { Client } from '@xdevplatform/xdk';

    // Creating a subscription requires user-context auth for the monitored user
    const client = new Client({ accessToken: 'YOUR_OAUTH2_USER_TOKEN' });
    await client.activity.createSubscription({
      event_type: 'chat.received',
      filter: { user_id: 'USER_ID_TO_MONITOR' },
    });
    // Stream: client.activity.stream() when available in your SDK version
    ```
  </Tab>
</Tabs>

送信コピーも必要な場合は `chat.sent` も購読してください。他の言語では同じ `/2/activity/*` HTTPS ルートを直接呼び出します(サブスクリプション作成にはユーザーコンテキストトークン、ストリームには App の Bearer トークン)。

***

## 2. CRC(Webhook のみ)

Webhook を使う場合は、Challenge-Response Check(GET `crc_token`)に対して、消費者シークレットを使ってトークンを HMAC-SHA256 したものを、Webhook プロダクトが期待する JSON 形式(通常は `sha256=<base64>`)で返してください。

***

## 3. Chat XDK で復号する

ライブフィールド:**`payload.encoded_event`**、オプションで **`payload.conversation_key_change_event`**。配信は **`event_uuid`** で重複排除してください。メッセージは復号済みイベントに含まれる **`message_id`** で重複排除してください——これは署名済みコンテンツの一部です。シーケンス ID はバックエンドで割り当てられる署名なしのメタデータです。

以下のスニペットは、最も短いハンドラーになるように 2 つの**オプション**セッションストアを使います:`set_signing_keys` は参加者の公開鍵を保持(一度 [public-keys エンドポイント](/x-api/chat/get-user-public-keys) から取得)し、`set_cache_keys(true)` は各会話の検証済み鍵を保持するので、`decrypt_event` はイベントだけで済みます。ペイロードが `conversation_key_change_event` を含む場合は、まずそれを `decrypt_events` に通してください:これは鍵変更を検証し、キャッシュがオンなら以後の `decrypt_event` 呼び出しのために鍵を保持します。インスタンス状態を持たない方式が好ましい場合は、呼び出しごとに鍵を渡してください——このセクションの末尾のノートを参照してください。

JavaScript は camelCase のイベントタイプ(`message`)を使いますが、他のバインディングは `"Message"` とスネークケースのフィールドを使います。

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    # chat has keys loaded and set_identity called (see Getting Started)
    chat.set_cache_keys(True)
    chat.set_signing_keys(participant_signing_keys)  # all participants, from the public-key routes

    data = body.get("data") or {}
    if data.get("event_type") in ("chat.received", "chat.sent"):
        p = data.get("payload") or {}
        if p.get("conversation_key_change_event"):
            # Verify the key change and retain its key in the cache
            chat.decrypt_events([p["conversation_key_change_event"]])
        ev = chat.decrypt_event(p["encoded_event"])
        if ev["type"] == "Message":
            print(ev["sender_id"], ev["content"]["text"])
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    // chat has keys loaded and setIdentity called (see Getting Started)
    chat.setCacheKeys(true);
    chat.setSigningKeys(participantSigningKeys); // all participants, from the public-key routes

    const data = body?.data ?? {};
    if (data.event_type === 'chat.received' || data.event_type === 'chat.sent') {
      const p = data.payload ?? {};
      if (p.conversation_key_change_event) {
        // Verify the key change and retain its key in the cache
        chat.decryptEvents([p.conversation_key_change_event]);
      }
      const ev = chat.decryptEvent(p.encoded_event);
      if (ev.type === 'message') {
        console.log(ev.senderId, ev.content.text);
      }
    }
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    // chat has keys loaded and set_identity called (see Getting Started)
    chat.set_cache_keys(true);
    chat.set_signing_keys(participant_signing_keys); // all participants

    if let Some(kc) = key_change.as_deref() {
        // Verify the key change and retain its key in the cache
        let _ = chat.decrypt_events(&[kc], &[]);
    }
    // Decrypt with the cached conversation key; verify against the stored signing keys
    let event = chat.decrypt_event(&encoded_event, &Default::default(), &[])?;
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    // chat has keys loaded and SetIdentity called (see Getting Started)
    chat.SetCacheKeys(true)
    _ = chat.SetSigningKeys(participantSigningKeys) // all participants

    if keyChange != "" {
        // Verify the key change and retain its key in the cache
        _, _ = chat.DecryptEvents([]string{keyChange}, nil)
    }
    // Decrypt with the cached conversation key; verify against the stored signing keys
    event, err := chat.DecryptEvent(encodedEvent, nil, nil)
    if err == nil && event.Type == "Message" {
        fmt.Println(event.AsMessage().Text())
    }
    ```
  </Tab>

  <Tab title="C#">
    ```csharp theme={null}
    // chat has keys loaded and SetIdentity called (see Getting Started)
    chat.SetCacheKeys(true);
    chat.SetSigningKeys(participantSigningKeys); // all participants

    if (!string.IsNullOrEmpty(keyChangeB64))
    {
        // Verify the key change and retain its key in the cache
        chat.DecryptEvents(new[] { keyChangeB64 });
    }
    // Decrypt with the cached conversation key; verify against the stored signing keys
    var evt = chat.DecryptEvent(encodedEvent);
    if (evt.GetProperty("type").GetString() == "Message")
        Console.WriteLine(evt.GetProperty("content").GetProperty("text").GetString());
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    // chat has keys loaded and setIdentity called (see Getting Started)
    chat.setCacheKeys(true);
    chat.setSigningKeys(participantSigningKeys); // all participants

    if (keyChangeB64 != null && !keyChangeB64.isEmpty()) {
        // Verify the key change and retain its key in the cache
        chat.decryptEvents(List.of(keyChangeB64), null);
    }
    // Decrypt with the cached conversation key; verify against the stored signing keys
    JsonNode evt = chat.decryptEvent(encodedEvent, (Map<String, byte[]>) null, null);
    if ("Message".equals(evt.path("type").asText())) {
        System.out.println(evt.path("content").path("text").asText());
    }
    ```
  </Tab>
</Tabs>

代わりに鍵マップを自分の手で保持したい場合、`extract_conversation_keys` は `conversation_key_change_event` から鍵を復号し、`decrypt_event` はそれら(および送信者の署名鍵)を明示的な引数として受け取ります——明示的で空でない引数は常にストアより優先されます。

履歴:[`GET /2/chat/conversations/{id}/events`](/x-api/chat/get-chat-conversation-events) + **`decrypt_events`** — [はじめに](/ja/xchat/getting-started#6-receive-and-decrypt) を参照してください。

***

## ペイロード形状(ライブ)

```json theme={null}
{
  "data": {
    "event_type": "chat.received",
    "event_uuid": "0f52b591-4b7e-4f13-92cd-30e6b2a3f18a",
    "payload": {
      "conversation_id": "1215441834412953600-1843439638876491776",
      "sender_id": "1843439638876491776",
      "encoded_event": "BASE64_ENCODED_MESSAGE_EVENT",
      "conversation_key_version": "1782945126642",
      "conversation_key_change_event": "BASE64_ENCODED_KEY_CHANGE_EVENT"
    }
  }
}
```

***

## プラクティス

* プラットフォーム要件に沿って Webhook の署名を検証してください
* セッションストアは一度セットしてください:参加者全員に対して `set_signing_keys`、会話鍵には `set_cache_keys(true)`
* 依存メッセージを復号する前に鍵変更ブロブを適用してください(`decrypt_events` 経由)
* 配信は `event_uuid` で、メッセージは署名済みの `message_id` で重複排除してください
