Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions x-api/activity/event-payloads.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1539,7 +1539,7 @@ Encrypted chat payloads include opaque encoded fields used by the XChat client l
"id": "e4f4d3fc-8bbf-4928-92eb-e5058d6bb6f6",
"created_at_msec": "1784841183370",
"sender_id": "2222222222222222222",
"conversation_id": "2222222222222222222:1111111111111111111",
"conversation_id": "1111111111111111111:2222222222222222222",
"conversation_key_version": "1768236281331",
"encoded_event": "CwABAAAAEzIwODA0MDA4MjUyMjcxMDAxNjALAAIA…(truncated)",
"conversation_key_change_event": "CwABAAAAEzIwMTA3NTQ4MTkxMTY0NDk5MDULAAIA…(truncated)",
Expand Down Expand Up @@ -1570,7 +1570,7 @@ Encrypted chat payloads include opaque encoded fields used by the XChat client l
"id": "8e75466b-56ec-4e88-bddf-b18f7cc6030e",
"created_at_msec": "1784841233939",
"sender_id": "1111111111111111111",
"conversation_id": "2222222222222222222:1111111111111111111",
"conversation_id": "1111111111111111111:2222222222222222222",
"conversation_key_version": "1768236281331",
"encoded_event": "CwABAAAAEzIwODA0MDEwMzczMzMyMzc3NjALAAIA…(truncated)",
"conversation_key_change_event": "CwABAAAAEzIwMTA3NTQ4MTkxMTY0NDk5MDULAAIA…(truncated)",
Expand All @@ -1584,9 +1584,9 @@ Encrypted chat payloads include opaque encoded fields used by the XChat client l
}
}
```
### `chat.conversation_join`
### `chat.conversation.join`

Fired when a user joins an encrypted chat conversation. The payload shape matches other chat events (conversation identity and encoded crypto material). Private event — requires user-context authentication.
Fired when a user joins an encrypted chat conversation. The payload shape matches other chat events (conversation identity and encoded crypto material). Private event — requires user-context authentication. `chat.conversation_join` is still accepted as a deprecated alias when creating a subscription; deliveries and responses always use `chat.conversation.join`.

---

Expand Down
2 changes: 1 addition & 1 deletion x-api/activity/event-pricing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ All X Activity API events are delivered via webhooks and billed per event. See t
| `profile.update.affiliate_badge` | $0.005/event |
| `chat.received` | $0.01/event |
| `chat.sent` | not billed |
| `chat.conversation_join` | not billed |
| `chat.conversation.join` | not billed |
| `dm.received` | $0.01/event |
| `dm.sent` | not billed |
| `dm.read` | not billed |
Expand Down
2 changes: 1 addition & 1 deletion x-api/activity/introduction.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ Chat events pertain to the new, encrypted messaging stack, or XChat.
| --- | --- | --- |
| `chat.received` | Fired when a user receives an encrypted direct message | `user_id`, `conversation_type` |
| `chat.sent` | Fired when a user sends an encrypted direct message | `user_id`, `conversation_type` |
| `chat.conversation_join` | Fired when a user joins an encrypted chat conversation | `user_id` |
| `chat.conversation.join` | Fired when a user joins an encrypted chat conversation (`chat.conversation_join` is a deprecated alias) | `user_id` |

### Legacy DM events

Expand Down
2 changes: 1 addition & 1 deletion x-api/getting-started/pricing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ Webhook events delivered through the [X Activity API](/x-api/activity/introducti
| `profile.update.*` | $0.005 |
| `chat.received` | $0.010 |
| `chat.sent` | Not billed |
| `chat.conversation_join` | Not billed |
| `chat.conversation.join` | Not billed |
| `dm.received` | $0.010 |
| `dm.sent` | Not billed |
| `dm.read` | Not billed |
Expand Down
113 changes: 78 additions & 35 deletions xchat/media.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: "Send images and files in X Chat"
sidebarTitle: Media
description: "Share images and file attachments in your encrypted chats: encrypt, upload, send, download, and decrypt media with the Chat XDK."
keywords: ["X Chat media", "encrypted images", "file attachments", "encrypt_stream", "media upload", "media download"]
keywords: ["X Chat media", "encrypted images", "file attachments", "encrypt_file", "media upload", "media download"]
---

Images and other files are encrypted client-side with the Chat XDK (`encrypt_file` / `decrypt_file`), uploaded via the **`/2/chat/media/upload`** routes (sidebar **API reference → Media**), and referenced by **`media_hash_key`** inside `encrypt_message`.
Expand Down Expand Up @@ -42,10 +42,12 @@ flowchart LR

## Encrypt

Read the MIME type and dimensions from the plaintext for the attachment descriptor. Encrypt the file only after `encrypt_message` has returned `payload` for a message that lists this `media_hash_key` (see [Send with an attachment](#send-with-an-attachment)). `encrypt_file` derives the file key from that message. Pass the same conversation key and version you passed to `encrypt_message`, or omit both to resolve them from the key cache.

<Tabs>
<Tab title="Python">
```python
from chat_xdk import detect_mime_type, detect_image_dimensions
from chat_xdk import EncryptFileParams, detect_mime_type, detect_image_dimensions

with open("photo.jpg", "rb") as f:
plaintext = f.read()
Expand All @@ -54,7 +56,14 @@ flowchart LR
dims = detect_image_dimensions(plaintext)
width, height = dims if dims else (0, 0)

encrypted_blob = chat.encrypt_stream(plaintext, raw_conv_key)
# payload: from encrypt_message with media_hash_key in its attachments
encrypted_blob = chat.encrypt_file(EncryptFileParams(
plaintext,
payload.event_b64,
media_hash_key,
conversation_key=raw_conv_key,
conversation_key_version=conversation_key_version,
))
```
</Tab>
<Tab title="TypeScript">
Expand All @@ -68,19 +77,30 @@ flowchart LR
const width = dims?.width ?? 0;
const height = dims?.height ?? 0;

const encryptedBlob = chat.encryptStream(plaintext, rawConvKey);
// payload: from encryptMessage with mediaHashKey in its attachments
const encryptedBlob = chat.encryptFile({
file: plaintext,
eventB64: payload.eventB64,
mediaHashKey,
conversationKey: rawConvKey,
conversationKeyVersion,
});
```
</Tab>
<Tab title="Rust">
```rust
use chat_xdk_core::{detect_image_dimensions, detect_mime_type};
use chat_xdk_core::{detect_image_dimensions, detect_mime_type, EncryptFileParams};

let plaintext = std::fs::read("photo.jpg")?;
let _mime = detect_mime_type(&plaintext);
let dims = detect_image_dimensions(&plaintext);
let (width, height) = dims.map(|d| (d.width as i64, d.height as i64)).unwrap_or((0, 0));
// payload: from encrypt_message with media_hash_key in its attachments
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let encrypted_blob = chat.encrypt_stream(&plaintext, &conv_key)?;
let encrypted_blob = chat.encrypt_file(
&EncryptFileParams::new(plaintext.clone(), &payload.event_b64, media_hash_key.clone())
.with_conversation_key(conv_key.to_bytes(), &conversation_key_version),
)?;
```
</Tab>
<Tab title="Go">
Expand All @@ -89,7 +109,14 @@ flowchart LR
mime, _ := chatxdk.DetectMimeType(plaintext)
dims, _ := chatxdk.DetectImageDimensions(plaintext)
_ = mime
encrypted, err := chat.EncryptStream(plaintext, rawConvKey)
// payload: from EncryptMessage with mediaHashKey in its attachments
encrypted, err := chat.EncryptFile(chatxdk.EncryptFileParams{
File: plaintext,
EventB64: payload.EventB64,
MediaHashKey: mediaHashKey,
ConversationKey: rawConvKey,
ConversationKeyVersion: conversationKeyVersion,
})
_ = dims
_ = encrypted
```
Expand All @@ -103,25 +130,35 @@ flowchart LR
var dims = ChatXdkUtilities.DetectImageDimensions(plaintext);
int width = (int)(dims?.Width ?? 0);
int height = (int)(dims?.Height ?? 0);
byte[] encryptedBlob = chat.EncryptStream(plaintext, rawConvKey);
// payload: from EncryptMessage with mediaHashKey in its attachments
byte[] encryptedBlob = chat.EncryptFile(new EncryptFileParams(plaintext, payload.EventB64, mediaHashKey)
{
ConversationKey = rawConvKey,
ConversationKeyVersion = conversationKeyVersion,
});
```
</Tab>
<Tab title="Java">
```java
import com.x.chatxdk.ChatXdkUtilities;
import com.x.chatxdk.Types.EncryptFileParams;
import com.x.chatxdk.Types.ImageDimensions;

byte[] plaintext = Files.readAllBytes(Path.of("photo.jpg"));
String mime = ChatXdkUtilities.detectMimeType(plaintext);
ImageDimensions dims = ChatXdkUtilities.detectImageDimensions(plaintext);
int width = dims != null ? (int) dims.width : 0;
int height = dims != null ? (int) dims.height : 0;
byte[] encryptedBlob = chat.encryptStream(plaintext, rawConvKey);
// payload: from encryptMessage with mediaHashKey in its attachments
EncryptFileParams fileParams = new EncryptFileParams(plaintext, payload.eventB64, mediaHashKey);
fileParams.conversationKey = rawConvKey;
fileParams.conversationKeyVersion = conversationKeyVersion;
byte[] encryptedBlob = chat.encryptFile(fileParams);
```
</Tab>
</Tabs>

`encrypt_stream` / `decrypt_stream` process the whole payload in memory. For large files, `stream_encryptor()` / `stream_decryptor()` return incremental objects (`StreamEncryptor` / `StreamDecryptor`): feed chunks with `push`, then call `finish` once; `finish` errors if the stream was truncated.
`encrypt_file` / `decrypt_file` process the whole file in memory. For large files, `file_encryptor` / `file_decryptor` take the same parameters without the file bytes and return incremental objects: feed chunks with `push`, then call `finish` once; `finish` errors if the file was truncated.

---

Expand Down Expand Up @@ -287,37 +324,23 @@ The conversation key pair can be omitted entirely: with `set_cache_keys(true)` e

Path: [`GET /2/chat/media/{conversation_id}/{media_hash_key}`](/x-api/chat/download-chat-media). Response body is ciphertext. On inbound messages, read `media_hash_key` from decrypted attachments / `media_hashes`.

**Pick the key by the event's key version.** Each decrypted message event carries the `keyVersion` (JS; `key_version` in the other bindings) its content was encrypted under. Decrypt an attachment with the conversation key for **that** version (`conversationKeys.keys[event.keyVersion]`), not the latest. After a key rotation (for example a member add), the latest key cannot decrypt media attached to older messages.
`decrypt_file` takes the downloaded bytes, the base64 event of the message that carries the file (as passed to `decrypt_event`), the conversation's key map, and the `media_hash_key`. It finds the attachment in that event and derives the file key from the conversation key for the message's own key version.

<Tabs>
<Tab title="Python">
```python
keys = result["conversation_keys"]["keys"]
key_for_media = keys[event["key_version"]] # not the latest version
plaintext = chat.decrypt_stream(encrypted_blob, key_for_media)
```
</Tab>
<Tab title="TypeScript">
```typescript
const keys = result.conversationKeys.keys;
const keyForMedia = keys[event.keyVersion]; // not the latest version
const plaintext = chat.decryptStream(encryptedBlob, keyForMedia);
```
</Tab>
</Tabs>
**Pass the full key map, not only the latest key.** After a key rotation (for example a member add), the latest key cannot decrypt media attached to older messages, so the map must hold the version the message was encrypted under (for example `conversation_keys.keys` from `decrypt_events`). With `set_cache_keys(true)`, pass an empty map to use the cached keys.

<Tabs>
<Tab title="Python">
```python
import requests
from chat_xdk import detect_mime_type
from chat_xdk import DecryptFileParams, detect_mime_type

api_id = conversation_id.replace(":", "-")
url = f"https://api.x.com/2/chat/media/{api_id}/{media_hash_key}"
r = requests.get(url, headers={"Authorization": f"Bearer {access_token}"})
r.raise_for_status()

plaintext = chat.decrypt_stream(r.content, raw_conv_key)
# event_b64: the message's event; keys: result["conversation_keys"]["keys"]
plaintext = chat.decrypt_file(DecryptFileParams(r.content, event_b64, keys, media_hash_key))
mime = detect_mime_type(plaintext) or "application/octet-stream"
```
</Tab>
Expand All @@ -331,7 +354,13 @@ Path: [`GET /2/chat/media/{conversation_id}/{media_hash_key}`](/x-api/chat/downl
{ headers: { Authorization: `Bearer ${accessToken}` } },
);
const encryptedBlob = new Uint8Array(await res.arrayBuffer());
const plaintext = chat.decryptStream(encryptedBlob, rawConvKey);
// eventB64: the message's event; keys: result.conversationKeys.keys
const plaintext = chat.decryptFile({
encrypted: encryptedBlob,
eventB64,
conversationKeys: keys,
mediaHashKey,
});
const mime = detectMimeType(plaintext) ?? 'application/octet-stream';
```
</Tab>
Expand All @@ -343,8 +372,13 @@ Path: [`GET /2/chat/media/{conversation_id}/{media_hash_key}`](/x-api/chat/downl
.header("Authorization", &auth)
.send()?
.bytes()?;
// conv_key: &XChatConversationKey from extract_conversation_keys / decrypt_conversation_key
let plaintext = chat.decrypt_stream(&encrypted_blob, &conv_key)?;
// event_b64: the message's event; keys: result.conversation_keys.keys
let plaintext = chat.decrypt_file(&DecryptFileParams::new(
encrypted_blob.to_vec(),
&event_b64,
keys.clone(),
&media_hash_key,
))?;
```
</Tab>
<Tab title="Go">
Expand All @@ -354,8 +388,15 @@ Path: [`GET /2/chat/media/{conversation_id}/{media_hash_key}`](/x-api/chat/downl
req, _ := http.NewRequest(http.MethodGet, url, nil)
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := http.DefaultClient.Do(req)
// read body into []byte → chat.DecryptStream(encryptedBlob, rawConvKey)
// read resp.Body into encryptedBlob; keys: result.ConversationKeys.Keys
plaintext, err := chat.DecryptFile(chatxdk.DecryptFileParams{
Encrypted: encryptedBlob,
EventB64: eventB64,
ConversationKeys: keys,
MediaHashKey: mediaHashKey,
})
_ = resp
_ = plaintext
_ = err
```
</Tab>
Expand All @@ -364,7 +405,8 @@ Path: [`GET /2/chat/media/{conversation_id}/{media_hash_key}`](/x-api/chat/downl
var apiId = conversationId.Replace(':', '-');
byte[] encryptedBlob = await http.GetByteArrayAsync(
$"https://api.x.com/2/chat/media/{apiId}/{mediaHashKey}");
byte[] plaintext = chat.DecryptStream(encryptedBlob, rawConvKey);
// eventB64: the message's event; keys: result.ConversationKeys.Keys
byte[] plaintext = chat.DecryptFile(new DecryptFileParams(encryptedBlob, eventB64, keys, mediaHashKey));
string? mime = ChatXdkUtilities.DetectMimeType(plaintext);
```
</Tab>
Expand All @@ -377,7 +419,8 @@ Path: [`GET /2/chat/media/{conversation_id}/{media_hash_key}`](/x-api/chat/downl
.GET()
.build();
byte[] encryptedBlob = http.send(req, HttpResponse.BodyHandlers.ofByteArray()).body();
byte[] plaintext = chat.decryptStream(encryptedBlob, rawConvKey);
// eventB64: the message's event; keys: result.conversationKeys.keys
byte[] plaintext = chat.decryptFile(new DecryptFileParams(encryptedBlob, eventB64, keys, mediaHashKey));
String mime = ChatXdkUtilities.detectMimeType(plaintext);
```
</Tab>
Expand Down
23 changes: 19 additions & 4 deletions xchat/real-time-events.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -221,19 +221,34 @@ Instead, use **XAA (`chat.received` / `chat.sent`)** as your primary real-time p
```json title="chat.received" lines wrap icon="/icons/xds/icon-brackets.svg"
{
"data": {
"event_uuid": "8511582263942905822",
"created_at": "2026-10-07T19:17:36.304Z",
"filter": {
"user_id": "1215441834412953600"
},
"event_type": "chat.received",
"event_uuid": "0f52b591-4b7e-4f13-92cd-30e6b2a3f18a",
"payload": {
"conversation_id": "1215441834412953600-1843439638876491776",
"conversation_token": "CONVERSATION_TOKEN",
"id": "e4f4d3fc-8bbf-4928-92eb-e5058d6bb6f6",
"created_at_msec": "1784841183370",
"sender_id": "1843439638876491776",
"encoded_event": "BASE64_ENCODED_MESSAGE_EVENT",
"conversation_id": "1215441834412953600:1843439638876491776",
"conversation_key_version": "1782945126642",
"conversation_key_change_event": "BASE64_ENCODED_KEY_CHANGE_EVENT"
"encoded_event": "BASE64_ENCODED_MESSAGE_EVENT",
"conversation_key_change_event": "BASE64_ENCODED_KEY_CHANGE_EVENT",
"message_event_signature": {
"public_key_version": "1765382634817",
"signature": "BASE64_SIGNATURE",
"signature_version": "7",
"signing_public_key": "BASE64_SIGNING_PUBLIC_KEY"
}
}
}
}
```

`payload.conversation_id` uses the canonical colon form: `lower:higher` user IDs for a 1:1 conversation, or the `g…` ID for a group. Replace `:` with `-` before using a 1:1 ID in a URL path. In these `chat.*` payloads, `payload.id` is the message's UUID (its `message_id`). In [`GET /2/chat/conversations/{id}/events`](/x-api/chat/get-chat-conversation-events) responses, `id` is instead the event's sequence ID. See [Event payloads](/x-api/activity/event-payloads#chat-events-xchat) for `chat.sent` and the other event types.

---

## Practices
Expand Down
Loading