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

# Guide d’intégration

> Concepts clés et bonnes pratiques pour intégrer les endpoints de consultation des 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>;
};

Ce guide couvre les principaux concepts nécessaires pour intégrer les endpoints d’interrogation des Direct Messages dans votre application.

***

<div id="authentication">
  ## Authentification
</div>

Les endpoints de DM nécessitent une authentification utilisateur pour accéder aux conversations privées :

| Méthode                                                                                                                           | Description                                    |
| :-------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------- |
| [OAuth 2.0 Authorization Code with PKCE](/fr/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | Recommandé                                     |
| [OAuth 1.0a User Context](/fr/resources/fundamentals/authentication)                                                              | Prise en charge pour compatibilité descendante |

<Warning>
  L'authentification App-Only n'est pas prise en charge. Tous les Messages privés sont privés.
</Warning>

<div id="required-scopes-oauth-20">
  ### Scopes requis (OAuth 2.0)
</div>

| Scope        | Requis pour                                    |
| :----------- | :--------------------------------------------- |
| `dm.read`    | Lecture des événements de messages privés (DM) |
| `tweet.read` | Requis avec `dm.read`                          |
| `users.read` | Requis avec `dm.read`                          |

***

<div id="conversation-types">
  ## Types de conversation
</div>

<CardGroup cols={2}>
  <Card title="Individuelle" icon="message">
    Contient toujours exactement deux participants. Format de l'id de conversation : `{smaller_user_id}-{larger_user_id}`
  </Card>

  <Card title="Groupe" icon="comments">
    Deux participants ou plus. La composition des membres peut évoluer dans le temps.
  </Card>
</CardGroup>

***

<div id="event-types">
  ## Types d’événements
</div>

| Événement           | Description                        | Champs clés                    |
| :------------------ | :--------------------------------- | :----------------------------- |
| `MessageCreate`     | Un message a été envoyé            | `text`, `sender_id`            |
| `ParticipantsJoin`  | Un utilisateur a rejoint le groupe | `participant_ids`, `sender_id` |
| `ParticipantsLeave` | Un utilisateur a quitté le groupe  | `participant_ids`              |

<div id="example-events">
  ### Exemples d’événements
</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">
  ## Champs et expansions
</div>

<div id="default-fields">
  ### Champs par défaut
</div>

| Type d’événement       | Champs par défaut                     |
| :--------------------- | :------------------------------------ |
| MessageCreate          | `id`, `event_type`, `text`            |
| ParticipantsJoin/Leave | `id`, `event_type`, `participant_ids` |

<div id="available-fields">
  ### Champs disponibles
</div>

| Champ                | Description                             | Événements          |
| :------------------- | :-------------------------------------- | :------------------ |
| `dm_conversation_id` | Identifiant de la conversation          | Tous                |
| `created_at`         | Horodatage de l’événement               | Tous                |
| `sender_id`          | Expéditeur / initiateur de l’invitation | MessageCreate, Join |
| `attachments`        | Pièces jointes média                    | MessageCreate       |
| `referenced_tweets`  | Publications partagées                  | MessageCreate       |

<div id="available-expansions">
  ### Expansions disponibles
</div>

| Expansion                | Renvoie                             |
| :----------------------- | :---------------------------------- |
| `sender_id`              | Objet utilisateur de l’expéditeur   |
| `participant_ids`        | Objets utilisateur des participants |
| `attachments.media_keys` | Objets média                        |
| `referenced_tweets.id`   | Objets de type Publication          |

<div id="example-with-expansions">
  ### Exemple avec 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")

  # Récupérer des événements de DM avec des expansions
  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">
  ## Pagination
</div>

Les événements de DM sont renvoyés dans l'ordre chronologique inverse (du plus récent au plus ancien) :

<CodeGroup dropdown>
  ```bash cURL theme={null}
  # Première requête
  curl "https://api.x.com/2/dm_events?max_results=100" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN"

  # Requête suivante avec un jeton de pagination
  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")

  # Le SDK gère automatiquement la pagination
  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 = [];

    // Le SDK gère automatiquement la pagination
    const paginator = client.dmEvents.list({ maxResults: 100 });

    for await (const page of paginator) {
      if (page.data) {
        allEvents.push(...page.data);
      }
    }

    return allEvents;
  }

  // Utilisation
  const events = await getAllDMEvents();
  console.log(`Found ${events.length} DM events`);
  ```
</CodeGroup>

<Note>
  Les événements datant d’**au plus 30 jours** sont disponibles.
</Note>

***

<div id="id-compatibility-with-v11">
  ## Compatibilité des ID avec la v1.1
</div>

Les identifiants de conversation et d’événement sont partagés entre les endpoints v1.1 et v2. Cela signifie que vous pouvez :

* Utiliser la v2 pour récupérer des événements, puis utiliser la v1.1 pour supprimer des messages spécifiques
* Utiliser des identifiants de conversation provenant d’URL x.com dans des requêtes d’API

***

<div id="next-steps">
  ## Étapes suivantes
</div>

<CardGroup cols={2}>
  <Card title="Démarrage rapide" icon="rocket" href="/fr/x-api/direct-messages/lookup/quickstart">
    Effectuez votre première requête de recherche de messages directs
  </Card>

  <Card title="Envoyer des DM" icon="paper-plane" href="/fr/x-api/direct-messages/manage/introduction">
    Envoyez des messages directs
  </Card>

  <Card title="Référence de l’API" icon="code" href="/fr/x-api/direct-messages/get-dm-events">
    Documentation complète du point de terminaison
  </Card>

  <Card title="Exemples de code" icon="github" href="https://github.com/xdevplatform/Twitter-API-v2-sample-code">
    Exemples de code prêts à l’emploi
  </Card>
</CardGroup>
