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

# Quickstart

> Este guia mostra como recuperar eventos de Mensagens Diretas para o usuário autenticado. Referência para o nível standard da API do X v2 cobrindo consulta.

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

Este guia mostra como recuperar eventos de Mensagens Diretas para o usuário autenticado.

<Note>
  **Pré-requisitos**

  Antes de começar, você precisará de:

  * Uma [conta de desenvolvedor](https://developer.x.com/en/portal/petition/essential/basic-info) com um App aprovado
  * User Access Token (OAuth 1.0a ou OAuth 2.0 PKCE)
</Note>

***

## Obter todos os eventos de DM

Recupere todos os eventos de DM para o usuário autenticado:

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/dm_events?\
  dm_event.fields=created_at,sender_id,text&\
  max_results=100" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN"
  ```

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

  client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")

  # Get all DM events with pagination
  for page in client.dm_events.list(
      dm_event_fields=["created_at", "sender_id", "text"],
      max_results=100
  ):
      for event in page.data:
          print(f"{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" });

  // Get all DM events with pagination
  const paginator = client.dmEvents.list({
    dmEventFields: ["created_at", "sender_id", "text"],
    maxResults: 100,
  });

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

### Resposta

```json title="MessageCreate" lines wrap icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-brackets.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=ed2428e77bab43e57800e1a590e982fa" theme={null}
{
  "data": [
    {
      "id": "1234567890",
      "event_type": "MessageCreate",
      "text": "Hello! How are you?",
      "sender_id": "9876543210",
      "created_at": "2024-01-15T10:30:00.000Z"
    }
  ],
  "meta": {
    "result_count": 1,
    "next_token": "abc123"
  }
}
```

***

## Obter conversa individual

Recupere eventos de DM de uma conversa individual específica:

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/dm_conversations/with/9876543210/dm_events?\
  dm_event.fields=created_at,sender_id,text" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN"
  ```

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

  client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")

  # Get DM events from a one-to-one conversation
  for page in client.dm_events.get_by_participant(
      participant_id="9876543210",
      dm_event_fields=["created_at", "sender_id", "text"]
  ):
      for event in page.data:
          print(f"{event.created_at}: {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" });

  // Get DM events from a one-to-one conversation
  const paginator = client.dmEvents.getByParticipant("9876543210", {
    dmEventFields: ["created_at", "sender_id", "text"],
  });

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

Substitua `9876543210` pelo user ID do outro participante.

***

## Obter conversa por ID

Recupere eventos de DM de um ID de conversa específico:

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/dm_conversations/1234567890-9876543210/dm_events?\
  dm_event.fields=created_at,sender_id,text" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN"
  ```

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

  client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")

  # Get DM events from a conversation by ID
  for page in client.dm_events.get_by_conversation(
      dm_conversation_id="1234567890-9876543210",
      dm_event_fields=["created_at", "sender_id", "text"]
  ):
      for event in page.data:
          print(f"{event.created_at}: {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" });

  // Get DM events from a conversation by ID
  const paginator = client.dmEvents.getByConversation("1234567890-9876543210", {
    dmEventFields: ["created_at", "sender_id", "text"],
  });

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

***

## Filtrar por tipo de evento

Obtenha apenas tipos específicos de eventos:

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/dm_events?\
  event_types=MessageCreate&\
  dm_event.fields=created_at,sender_id,text" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN"
  ```

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

  client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")

  # Get only MessageCreate events
  for page in client.dm_events.list(
      event_types=["MessageCreate"],
      dm_event_fields=["created_at", "sender_id", "text"]
  ):
      for event in page.data:
          print(f"{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" });

  // Get only MessageCreate events
  const paginator = client.dmEvents.list({
    eventTypes: ["MessageCreate"],
    dmEventFields: ["created_at", "sender_id", "text"],
  });

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

### Tipos de eventos

| Tipo                | Descrição                  |
| :------------------ | :------------------------- |
| `MessageCreate`     | Uma mensagem foi enviada   |
| `ParticipantsJoin`  | Usuário entrou na conversa |
| `ParticipantsLeave` | Usuário saiu da conversa   |

***

## Incluir dados do usuário

Expanda as informações do remetente:

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/dm_events?\
  dm_event.fields=created_at,sender_id,text&\
  expansions=sender_id&\
  user.fields=username,profile_image_url" \
    -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")

  # Get DM events with sender info
  for page in client.dm_events.list(
      dm_event_fields=["created_at", "sender_id", "text"],
      expansions=["sender_id"],
      user_fields=["username", "profile_image_url"]
  ):
      for event in page.data:
          # Match sender from includes
          print(f"{event.sender_id}: {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" });

  // Get DM events with sender info
  const paginator = client.dmEvents.list({
    dmEventFields: ["created_at", "sender_id", "text"],
    expansions: ["sender_id"],
    userFields: ["username", "profile_image_url"],
  });

  for await (const page of paginator) {
    page.data?.forEach((event) => {
      console.log(`${event.sender_id}: ${event.text}`);
    });
    // Sender user objects are in page.includes.users
  }
  ```
</CodeGroup>

### Resposta com expansion

```json title="MessageCreate" lines wrap icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-brackets.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=ed2428e77bab43e57800e1a590e982fa" theme={null}
{
  "data": [
    {
      "id": "1234567890",
      "event_type": "MessageCreate",
      "text": "Hello!",
      "sender_id": "9876543210"
    }
  ],
  "includes": {
    "users": [
      {
        "id": "9876543210",
        "username": "example_user",
        "profile_image_url": "https://..."
      }
    ]
  }
}
```

***

## Parâmetros comuns

| Parâmetro          | Descrição                              |
| :----------------- | :------------------------------------- |
| `max_results`      | Eventos por página (1-100, padrão 100) |
| `pagination_token` | Token para a próxima página            |
| `dm_event.fields`  | Campos do evento a retornar            |
| `event_types`      | Filtrar por tipo de evento             |
| `expansions`       | Objetos relacionados a incluir         |

***

## Próximos passos

<CardGroup cols={2}>
  <Card title="Enviar DMs" icon="paper-plane" href="/x-api/direct-messages/manage/quickstart">
    Envie Mensagens Diretas
  </Card>

  <Card title="Guia de integração" icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-book.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=22ac564792481d14ae36a941546039c8" href="/x-api/direct-messages/lookup/integrate" width="24" height="24" data-path="icons/xds/icon-book.svg">
    Conceitos-chave e boas práticas
  </Card>

  <Card title="Referência da 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">
    Documentação completa do endpoint
  </Card>
</CardGroup>
