> ## 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](/ko/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | 권장          |
| [OAuth 1.0a User Context](/ko/resources/fundamentals/authentication)                                                              | 레거시 지원      |

<Warning>
  App-Only 인증은 지원되지 않습니다. 모든 다이렉트 메시지는 비공개입니다.
</Warning>

<div id="required-scopes-oauth-20">
  ### 필수 스코프 (OAuth 2.0)
</div>

| Scope        | 필요한 작업           |
| :----------- | :--------------- |
| `dm.read`    | DM 이벤트 읽기        |
| `tweet.read` | `dm.read`와 함께 필요 |
| `users.read` | `dm.read`와 함께 필요 |

***

<div id="conversation-types">
  ## 대화 유형
</div>

<CardGroup cols={2}>
  <Card title="일대일" icon="message">
    항상 정확히 두 명의 참가자가 있습니다. 대화 ID 형식: `{smaller_user_id}-{larger_user_id}`
  </Card>

  <Card title="그룹" icon="comments">
    두 명 이상의 참가자가 있습니다. 멤버 구성은 시간에 따라 달라질 수 있습니다.
  </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>

| Field                | Description | Events              |
| :------------------- | :---------- | :------------------ |
| `dm_conversation_id` | 대화 ID       | 전체                  |
| `created_at`         | 이벤트 타임스탬프   | 전체                  |
| `sender_id`          | 보낸/초대한 사용자  | MessageCreate, Join |
| `attachments`        | 미디어 첨부 파일   | MessageCreate       |
| `referenced_tweets`  | 공유된 포스트     | MessageCreate       |

<div id="available-expansions">
  ### 사용 가능한 expansions
</div>

| Expansion                | 반환 항목       |
| :----------------------- | :---------- |
| `sender_id`              | 발신자 User 객체 |
| `participant_ids`        | 참여자 User 객체 |
| `attachments.media_keys` | Media 객체    |
| `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는 v1.1과 v2 엔드포인트에서 동일하게 사용됩니다. 이는 다음을 수행할 수 있다는 의미입니다:

* v2를 사용해 이벤트를 가져온 후 v1.1을 사용해 특정 메시지를 삭제할 수 있습니다
* API 요청에서 x.com URL의 대화 ID를 참조할 수 있습니다

***

<div id="next-steps">
  ## 다음 단계
</div>

<CardGroup cols={2}>
  <Card title="빠른 시작" icon="rocket" href="/ko/x-api/direct-messages/lookup/quickstart">
    첫 번째 DM 조회 요청 보내기
  </Card>

  <Card title="DM 보내기" icon="paper-plane" href="/ko/x-api/direct-messages/manage/introduction">
    다이렉트 메시지 보내기
  </Card>

  <Card title="API 참조 문서" icon="code" href="/ko/x-api/direct-messages/get-dm-events">
    전체 엔드포인트 설명서
  </Card>

  <Card title="샘플 코드" icon="github" href="https://github.com/xdevplatform/Twitter-API-v2-sample-code">
    실행 가능한 코드 예제
  </Card>
</CardGroup>
