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

# 統合ガイド

> このガイドでは、Direct Messages lookup エンドポイントをアプリケーションに統合するために必要な主要概念を説明します。lookup をカバーする X API v2 standard tier のリファレンスです。

export const Button = ({href, children}) => {
  return <div className="not-prose">
    <a href={href}>
      <button className="x-btn">
        <span>{children}</span>
        <svg width="3" height="24" viewBox="0 -9 3 24" class="h-6 rotate-0 overflow-visible"><path d="M0 0L3 3L0 6" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"></path></svg>
      </button>
    </a>
  </div>;
};

このガイドでは、Direct Messages lookup エンドポイントをアプリケーションに統合するために必要な主要な概念を説明します。

***

## 認証

DM エンドポイントでは、プライベートな会話にアクセスするためにユーザー認証が必要です。

| Method                                                                                                                         | Description |
| :----------------------------------------------------------------------------------------------------------------------------- | :---------- |
| [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | 推奨          |
| [OAuth 1.0a User Context](/resources/fundamentals/authentication)                                                              | レガシーサポート    |

<Warning>
  App-Only 認証はサポートされていません。すべてのダイレクトメッセージは非公開です。
</Warning>

### 必要なスコープ（OAuth 2.0）

| Scope        | Required for   |
| :----------- | :------------- |
| `dm.read`    | DM イベントの読み取り   |
| `tweet.read` | dm.read と併用が必要 |
| `users.read` | dm.read と併用が必要 |

***

## 会話のタイプ

<CardGroup cols={2}>
  <Card title="1 対 1" icon="https://mintcdn.com/x-preview/ygI6sSJPehlc0qNT/icons/xds/icon-chat.svg?fit=max&auto=format&n=ygI6sSJPehlc0qNT&q=85&s=9fde7d51b4f18c96d3a38a81d519761f" width="24" height="24" data-path="icons/xds/icon-chat.svg">
    参加者は常に 2 名のみ。会話 ID の形式: `{smaller_user_id}-{larger_user_id}`
  </Card>

  <Card title="グループ" icon="https://mintcdn.com/x-preview/ygI6sSJPehlc0qNT/icons/xds/icon-chat-unread.svg?fit=max&auto=format&n=ygI6sSJPehlc0qNT&q=85&s=ce6313d8c0b7b4e5363f2ce80b89f7e4" width="24" height="24" data-path="icons/xds/icon-chat-unread.svg">
    2 名以上の参加者。メンバーシップは時間とともに変わることがあります。
  </Card>
</CardGroup>

***

## イベントタイプ

| Event               | Description     | Key fields                     |
| :------------------ | :-------------- | :----------------------------- |
| `MessageCreate`     | メッセージが送信された     | `text`, `sender_id`            |
| `ParticipantsJoin`  | ユーザーがグループに参加した  | `participant_ids`, `sender_id` |
| `ParticipantsLeave` | ユーザーがグループから退出した | `participant_ids`              |

### イベント例

<AccordionGroup>
  <Accordion title="MessageCreate">
    ```json theme={null}
    {
      "id": "1582838499983564806",
      "event_type": "MessageCreate",
      "text": "Hi everyone.",
      "sender_id": "944480690",
      "dm_conversation_id": "1578398451921985538",
      "created_at": "2022-10-19T20:58:00.000Z"
    }
    ```
  </Accordion>

  <Accordion title="ParticipantsJoin">
    ```json theme={null}
    {
      "id": "1582835469712138240",
      "event_type": "ParticipantsJoin",
      "participant_ids": ["944480690"],
      "sender_id": "17200003",
      "dm_conversation_id": "1578398451921985538",
      "created_at": "2022-10-19T20:45:58.000Z"
    }
    ```
  </Accordion>

  <Accordion title="ParticipantsLeave">
    ```json theme={null}
    {
      "id": "1582838535115067392",
      "event_type": "ParticipantsLeave",
      "participant_ids": ["944480690"],
      "dm_conversation_id": "1578398451921985538",
      "created_at": "2022-10-19T20:58:09.000Z"
    }
    ```
  </Accordion>
</AccordionGroup>

***

## Fields と expansions

### デフォルトフィールド

| Event type             | Default fields                        |
| :--------------------- | :------------------------------------ |
| MessageCreate          | `id`, `event_type`, `text`            |
| ParticipantsJoin/Leave | `id`, `event_type`, `participant_ids` |

### 利用可能なフィールド

| Field                | Description  | Events              |
| :------------------- | :----------- | :------------------ |
| `dm_conversation_id` | 会話 ID        | All                 |
| `created_at`         | イベントのタイムスタンプ | All                 |
| `sender_id`          | 送信者/招待者      | MessageCreate, Join |
| `attachments`        | メディア添付       | MessageCreate       |
| `referenced_tweets`  | 共有された Post   | MessageCreate       |

### 利用可能な expansions

| Expansion                | Returns          |
| :----------------------- | :--------------- |
| `sender_id`              | 送信者の User オブジェクト |
| `participant_ids`        | 参加者の User オブジェクト |
| `attachments.media_keys` | Media オブジェクト     |
| `referenced_tweets.id`   | Post オブジェクト      |

### expansions を使用した例

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/dm_events?\
  dm_event.fields=created_at,sender_id,attachments&\
  expansions=sender_id,attachments.media_keys&\
  user.fields=username,profile_image_url&\
  media.fields=url,type" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN"
  ```

  ```python title="Python SDK" lines wrap icon="python" theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")

  # expansions を指定して DM イベントを取得
  for page in client.dm_events.list(
      dm_event_fields=["created_at", "sender_id", "attachments"],
      expansions=["sender_id", "attachments.media_keys"],
      user_fields=["username", "profile_image_url"],
      media_fields=["url", "type"],
      max_results=100
  ):
      for event in page.data:
          print(f"Event: {event.event_type} - {event.text}")
  ```

  ```javascript title="JavaScript SDK" lines wrap icon="square-js" theme={null}
  import { Client } from "@xdevplatform/xdk";

  const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });

  const paginator = client.dmEvents.list({
    dmEventFields: ["created_at", "sender_id", "attachments"],
    expansions: ["sender_id", "attachments.media_keys"],
    userFields: ["username", "profile_image_url"],
    mediaFields: ["url", "type"],
    maxResults: 100,
  });

  for await (const page of paginator) {
    page.data?.forEach((event) => {
      console.log(`Event: ${event.event_type} - ${event.text}`);
    });
  }
  ```
</CodeGroup>

***

## ページネーション

DM イベントは新しい順（新しいものが先）に返されます。

<CodeGroup dropdown>
  ```bash cURL theme={null}
  # 最初のリクエスト
  curl "https://api.x.com/2/dm_events?max_results=100" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN"

  # pagination トークンを使った次のリクエスト
  curl "https://api.x.com/2/dm_events?max_results=100&pagination_token=NEXT_TOKEN" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN"
  ```

  ```python title="Python SDK" lines wrap icon="python" theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")

  # SDK がページネーションを自動的に処理します
  all_events = []

  for page in client.dm_events.list(max_results=100):
      if page.data:
          all_events.extend(page.data)

  print(f"Found {len(all_events)} DM events")
  ```

  ```javascript title="JavaScript SDK" lines wrap icon="square-js" theme={null}
  import { Client } from "@xdevplatform/xdk";

  const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });

  async function getAllDMEvents() {
    const allEvents = [];

    // SDK がページネーションを自動的に処理します
    const paginator = client.dmEvents.list({ maxResults: 100 });

    for await (const page of paginator) {
      if (page.data) {
        allEvents.push(...page.data);
      }
    }

    return allEvents;
  }

  // 使用例
  const events = await getAllDMEvents();
  console.log(`Found ${events.length} DM events`);
  ```
</CodeGroup>

<Note>
  最大 **過去 30 日** までのイベントを取得できます。
</Note>

***

## v1.1 との ID 互換性

会話 ID とイベント ID は v1.1 と v2 のエンドポイント間で共有されています。つまり、次のことが可能です。

* v2 でイベントを取得し、v1.1 で特定のメッセージを削除する
* x.com URL の会話 ID を API リクエストで参照する

***

## 次のステップ

<CardGroup cols={2}>
  <Card title="クイックスタート" icon="https://mintcdn.com/x-preview/oR-aRNyj1BKPJtxM/icons/xds/icon-rocket.svg?fit=max&auto=format&n=oR-aRNyj1BKPJtxM&q=85&s=b978d7a9225de31709efbbed5b84e92d" href="/x-api/direct-messages/lookup/quickstart" width="24" height="24" data-path="icons/xds/icon-rocket.svg">
    最初の DM lookup リクエストを実行
  </Card>

  <Card title="DM を送信" icon="paper-plane" href="/x-api/direct-messages/manage/introduction">
    ダイレクトメッセージを送信
  </Card>

  <Card title="API リファレンス" icon="https://mintcdn.com/x-preview/ygI6sSJPehlc0qNT/icons/xds/icon-code.svg?fit=max&auto=format&n=ygI6sSJPehlc0qNT&q=85&s=488e23401b19225b89acc0136d242219" href="/x-api/direct-messages/get-dm-events" width="24" height="24" data-path="icons/xds/icon-code.svg">
    エンドポイントの完全なドキュメント
  </Card>

  <Card title="サンプルコード" icon="github" href="https://github.com/xdevplatform/Twitter-API-v2-sample-code">
    動作するコード例
  </Card>
</CardGroup>
