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

# 連携ガイド

> DM ルックアップエンドポイントとの連携に関する主要な概念とベストプラクティス

export const Button = ({href, children}) => {
  return <div className="not-prose group">
    <a href={href}>
      <button className="flex items-center space-x-2.5 py-1 px-4 bg-primary-dark dark:bg-white text-white dark:text-gray-950 rounded-full group-hover:opacity-[0.9] font-medium">
        <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 ルックアップエンドポイントを統合するために必要となる基本的な概念を説明します。

***

<div id="authentication">
  ## 認証
</div>

DM エンドポイントにおいて非公開の会話にアクセスするには、ユーザー認証が必要です。

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

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

<div id="required-scopes-oauth-20">
  ### 必要なスコープ (OAuth 2.0)
</div>

| スコープ         | 必要となるケース         |
| :----------- | :--------------- |
| `dm.read`    | DM イベントの読み取り     |
| `tweet.read` | `dm.read` と併せて必須 |
| `users.read` | `dm.read` と併せて必須 |

***

<div id="conversation-types">
  ## 会話タイプ
</div>

<CardGroup cols={2}>
  <Card title="1対1" icon="message">
    参加者は常に2人だけです。Conversation ID の形式: `{smaller_user_id}-{larger_user_id}`
  </Card>

  <Card title="グループ" icon="comments">
    2人以上の参加者がいます。参加メンバーは時間の経過とともに変わることがあります。
  </Card>
</CardGroup>

***

<div id="event-types">
  ## イベントタイプ
</div>

| イベント                | 説明              | 主なフィールド                        |
| :------------------ | :-------------- | :----------------------------- |
| `MessageCreate`     | メッセージが送信された     | `text`, `sender_id`            |
| `ParticipantsJoin`  | ユーザーがグループに参加した  | `participant_ids`, `sender_id` |
| `ParticipantsLeave` | ユーザーがグループから退出した | `participant_ids`              |

<div id="example-events">
  ### イベントの例
</div>

<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>

***

<div id="fields-and-expansions">
  ## フィールドと Expansions
</div>

<div id="default-fields">
  ### デフォルトフィールド
</div>

| イベントタイプ                | デフォルトフィールド                            |
| :--------------------- | :------------------------------------ |
| MessageCreate          | `id`, `event_type`, `text`            |
| ParticipantsJoin/Leave | `id`, `event_type`, `participant_ids` |

<div id="available-fields">
  ### 利用可能なフィールド
</div>

| フィールド                | 説明              | イベント                |
| :------------------- | :-------------- | :------------------ |
| `dm_conversation_id` | 会話ID            | すべて                 |
| `created_at`         | イベントのタイムスタンプ    | すべて                 |
| `sender_id`          | 送信または招待を行ったユーザー | MessageCreate, Join |
| `attachments`        | メディアの添付ファイル     | MessageCreate       |
| `referenced_tweets`  | 共有された投稿         | MessageCreate       |

<div id="available-expansions">
  ### 利用可能な expansions
</div>

| Expansion                | 返されるオブジェクト     |
| :----------------------- | :------------- |
| `sender_id`              | 送信者のユーザーオブジェクト |
| `participant_ids`        | 参加者のユーザーオブジェクト |
| `attachments.media_keys` | メディアオブジェクト     |
| `referenced_tweets.id`   | ポストオブジェクト      |

<div id="example-with-expansions">
  ### expansions を指定した例
</div>

<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 Python SDK 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 JavaScript SDK 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>

***

<div id="pagination">
  ## ページネーション
</div>

DM イベントは逆時系列 (新しいものが先) で返されます。

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

  # ページネーション用トークンを使った後続リクエスト
  curl "https://api.x.com/2/dm_events?max_results=100&pagination_token=NEXT_TOKEN" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN"
  ```

  ```python Python SDK 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 JavaScript SDK 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>

***

<div id="id-compatibility-with-v11">
  ## v1.1 との ID 互換性
</div>

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

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

***

<div id="next-steps">
  ## 次のステップ
</div>

<CardGroup cols={2}>
  <Card title="クイックスタート" icon="rocket" href="/ja/x-api/direct-messages/lookup/quickstart">
    初めてのDMルックアップリクエストを送信する
  </Card>

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

  <Card title="APIリファレンス" icon="code" href="/ja/x-api/direct-messages/get-dm-events">
    エンドポイントの詳細なドキュメント
  </Card>

  <Card title="サンプルコード" icon="github" href="https://github.com/xdevplatform/Twitter-API-v2-sample-code">
    実行可能なコード例
  </Card>
</CardGroup>
