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

# 통합 가이드

> 이 가이드는 Manage Direct Messages endpoint를 통합하기 위한 핵심 개념을 다룹니다. 관리 기능을 다루는 X API v2 standard 등급 레퍼런스입니다.

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

이 가이드는 Manage Direct Messages endpoint를 애플리케이션에 통합하기 위해 알아야 할 핵심 개념을 다룹니다.

***

## 인증

DM endpoint는 사용자 인증이 필요합니다:

| 방법                                                                                                                             | 설명     |
| :----------------------------------------------------------------------------------------------------------------------------- | :----- |
| [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 인증은 지원되지 않습니다. 모든 Direct Message는 비공개입니다.
</Warning>

### 필수 scope (OAuth 2.0)

| Scope        | 필요 용도           |
| :----------- | :-------------- |
| `dm.write`   | 메시지 전송 및 삭제     |
| `dm.read`    | dm.write와 함께 필수 |
| `tweet.read` | dm scope와 함께 필수 |
| `users.read` | dm scope와 함께 필수 |

***

## Endpoint 개요

| Method | Endpoint                                            | 설명         |
| :----- | :-------------------------------------------------- | :--------- |
| POST   | `/2/dm_conversations/with/:participant_id/messages` | 1:1 메시지 전송 |
| POST   | `/2/dm_conversations`                               | 그룹 대화 생성   |
| POST   | `/2/dm_conversations/:dm_conversation_id/messages`  | 대화에 메시지 추가 |
| DELETE | `/2/dm_events/:event_id`                            | 메시지 삭제     |

***

## 메시지 전송

### 1:1 메시지

특정 사용자에게 메시지를 보냅니다. 대화가 없으면 새로 생성합니다:

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl -X POST "https://api.x.com/2/dm_conversations/with/9876543210/messages" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"text": "Hello!"}'
  ```

  ```python Python SDK theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")

  # Send a one-to-one DM
  response = client.dm_conversations.create_message(
      participant_id="9876543210",
      text="Hello!"
  )
  print(response.data)
  ```

  ```javascript JavaScript SDK theme={null}
  import { Client } from "@xdevplatform/xdk";

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

  // Send a one-to-one DM
  const response = await client.dmConversations.createMessage({
    participantId: "9876543210",
    text: "Hello!",
  });
  console.log(response.data);
  ```
</CodeGroup>

### 그룹 대화

새 그룹을 만들고 첫 메시지를 전송합니다:

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl -X POST "https://api.x.com/2/dm_conversations" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "conversation_type": "Group",
      "participant_ids": ["944480690", "906948460078698496"],
      "message": {"text": "Welcome to our group!"}
    }'
  ```

  ```python Python SDK theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")

  # Create a group conversation
  response = client.dm_conversations.create(
      conversation_type="Group",
      participant_ids=["944480690", "906948460078698496"],
      message={"text": "Welcome to our group!"}
  )
  print(response.data)
  ```

  ```javascript JavaScript SDK theme={null}
  import { Client } from "@xdevplatform/xdk";

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

  // Create a group conversation
  const response = await client.dmConversations.create({
    conversationType: "Group",
    participantIds: ["944480690", "906948460078698496"],
    message: { text: "Welcome to our group!" },
  });
  console.log(response.data);
  ```
</CodeGroup>

<Note>
  `conversation_type` field는 `"Group"`으로 설정해야 하며 대소문자를 구분합니다.
</Note>

### 기존 대화에 추가

참여 중인 대화에 메시지를 전송합니다:

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl -X POST "https://api.x.com/2/dm_conversations/1582103724607971328/messages" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{"text": "Another message"}'
  ```

  ```python Python SDK theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")

  # Add message to existing conversation
  response = client.dm_conversations.add_message(
      dm_conversation_id="1582103724607971328",
      text="Another message"
  )
  print(response.data)
  ```

  ```javascript JavaScript SDK theme={null}
  import { Client } from "@xdevplatform/xdk";

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

  // Add message to existing conversation
  const response = await client.dmConversations.addMessage({
    dmConversationId: "1582103724607971328",
    text: "Another message",
  });
  console.log(response.data);
  ```
</CodeGroup>

***

## 미디어 첨부

메시지당 미디어 한 개(사진, 동영상 또는 GIF)를 첨부할 수 있습니다.

<Steps>
  <Step title="미디어 업로드">
    [Media Upload endpoint](/x-api/media/quickstart/media-upload-chunked)를 사용하여 파일을 업로드하고 `media_id`를 받습니다.
  </Step>

  <Step title="메시지에 포함">
    ```json theme={null}
    {
      "text": "Check out this image!",
      "attachments": [{"media_id": "1583157113245011970"}]
    }
    ```
  </Step>
</Steps>

<Note>
  * 인증된 사용자가 미디어를 업로드했어야 합니다
  * 미디어는 업로드 후 24시간 동안 사용 가능합니다
  * 메시지당 첨부는 하나만 지원됩니다
</Note>

***

## Post 공유

Post URL을 텍스트에 추가하면 메시지에 Post가 포함됩니다:

```json theme={null}
{
  "text": "Have you seen this? https://x.com/XDevelopers/status/1580559079470145536"
}
```

응답에는 Post ID가 담긴 `referenced_tweets` field가 포함됩니다.

***

## 메시지 요구사항

| Field         | 필수 여부 | 참고          |
| :------------ | :---- | :---------- |
| `text`        | 예\*   | 첨부가 없으면 필수  |
| `attachments` | 예\*   | 텍스트가 없으면 필수 |

\*`text` 또는 `attachments` 중 하나는 반드시 제공해야 합니다.

***

## v1.1과의 ID 호환성

대화 ID와 이벤트 ID는 v1.1과 v2 endpoint 간에 공유됩니다. 이를 통해 하이브리드 워크플로가 가능합니다:

* v2로 메시지 생성
* v1.1로 메시지 삭제(v2에서 아직 미제공)
* x.com URL의 대화 ID 참조

***

## 오류 처리

| Status | 오류                | 해결 방법             |
| :----- | :---------------- | :---------------- |
| 400    | Invalid request   | 요청 본문 형식 확인       |
| 401    | Unauthorized      | access token 확인   |
| 403    | Forbidden         | scope 및 사용자 권한 확인 |
| 429    | Too Many Requests | 잠시 기다렸다가 재시도      |

### 자주 발생하는 문제

<AccordionGroup>
  <Accordion title="사용자에게 전송할 수 없음">
    수신자가 알 수 없는 사용자로부터의 메시지를 차단하는 DM 설정을 사용 중이거나 발신자를 차단했을 수 있습니다.
  </Accordion>

  <Accordion title="미디어 첨부 실패">
    미디어가 동일한 인증된 사용자에 의해 업로드되었고 업로드 후 24시간 이내인지 확인하세요.
  </Accordion>

  <Accordion title="그룹 생성 실패">
    모든 참가자 ID가 유효한지, 그리고 사용자가 그룹 DM 초대를 허용하는지 확인하세요.
  </Accordion>
</AccordionGroup>

***

## 다음 단계

<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/manage/quickstart" width="24" height="24" data-path="icons/xds/icon-rocket.svg">
    첫 Direct Message 전송하기
  </Card>

  <Card title="DM 조회" icon="inbox" href="/x-api/direct-messages/lookup/introduction">
    DM 대화 조회하기
  </Card>

  <Card title="미디어 업로드" icon="https://mintcdn.com/x-preview/oR-aRNyj1BKPJtxM/icons/xds/icon-photo.svg?fit=max&auto=format&n=oR-aRNyj1BKPJtxM&q=85&s=d0986097dcff55478c32801b20440ecc" href="/x-api/media/quickstart/media-upload-chunked" width="24" height="24" data-path="icons/xds/icon-photo.svg">
    첨부용 미디어 업로드
  </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/create-dm-message-by-participant-id" width="24" height="24" data-path="icons/xds/icon-code.svg">
    전체 endpoint 문서
  </Card>
</CardGroup>
