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

> Esta guía te lleva paso a paso a recuperar los eventos de Mensajes Directos del usuario autenticado. Referencia para el nivel estándar de la X API v2 que cubre lookup.

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

Esta guía te lleva paso a paso a recuperar los eventos de Mensajes Directos del usuario autenticado.

<Note>
  **Requisitos previos**

  Antes de comenzar, necesitarás:

  * Una [cuenta de desarrollador](https://developer.x.com/en/portal/petition/essential/basic-info) con una App aprobada
  * Un User Access Token (OAuth 1.0a u OAuth 2.0 PKCE)
</Note>

***

## Obtener todos los eventos de DM

Recupera todos los eventos de DM del usuario 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 SDK de Python 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="SDK de JavaScript" 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>

### Respuesta

```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"
  }
}
```

***

## Obtener una conversación uno a uno

Recupera los eventos de DM de una conversación uno a uno 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 SDK de Python 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="SDK de JavaScript" 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>

Reemplaza `9876543210` con el ID de usuario del otro participante.

***

## Obtener conversación por ID

Recupera los eventos de DM de un ID de conversación 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 SDK de Python 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="SDK de JavaScript" 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

Obtén solo tipos de eventos específicos:

<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 SDK de Python 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="SDK de JavaScript" 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                | Descripción                          |
| :------------------ | :----------------------------------- |
| `MessageCreate`     | Se envió un mensaje                  |
| `ParticipantsJoin`  | Un usuario se unió a la conversación |
| `ParticipantsLeave` | Un usuario abandonó la conversación  |

***

## Incluir datos del usuario

Expande la información del remitente:

<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="SDK de Python" 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="SDK de JavaScript" 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>

### Respuesta con 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 comunes

| Parámetro          | Descripción                                 |
| :----------------- | :------------------------------------------ |
| `max_results`      | Eventos por página (1-100, por defecto 100) |
| `pagination_token` | Token para la siguiente página              |
| `dm_event.fields`  | Campos del evento a devolver                |
| `event_types`      | Filtrar por tipo de evento                  |
| `expansions`       | Objetos relacionados a incluir              |

***

## Próximos pasos

<CardGroup cols={2}>
  <Card title="Enviar DMs" icon="paper-plane" href="/x-api/direct-messages/manage/quickstart">
    Envía Mensajes Directos
  </Card>

  <Card title="Guía de integración" 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">
    Conceptos clave y buenas prácticas
  </Card>

  <Card title="Referencia de la 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">
    Documentación completa de endpoints
  </Card>
</CardGroup>
