XChat
Hold encrypted 1:1 and group conversations on XChat, with all cryptography handled inside the adapter.
Create a new bot
Scaffold a Next.js bot with the XChat adapter using create-chat-sdk:
pnpm create chat-sdk@latest my-bot --adapter xchat memory -yThe generated app uses the Memory state adapter for local development. To add the adapter to an existing app, start at Install.
Install
pnpm add @chat-adapter/x @chat-adapter/state-memoryQuick start
The adapter auto-detects XCHAT_BOT_TOKEN, XCHAT_PIN, and X_CONSUMER_SECRET from the environment. The bot's user id and @handle are resolved from GET /2/users/me at startup.
The memory state adapter keeps subscriptions and locks in process memory, which suits local development. Use Redis or PostgreSQL in production.
Route both GET and POST through the adapter. See Webhooks for what each method handles.
XChat adapter vs X adapter
The @chat-adapter/x package contains two adapters for different X surfaces. This page covers the XChat adapter. For public posts, mentions, and classic DMs, use the X adapter.
| X adapter | XChat adapter | |
|---|---|---|
| Factory | createXAdapter from @chat-adapter/x | createXchatAdapter from @chat-adapter/x/chat |
| Conversations | Public timeline mentions and replies (post.mention.create), and classic unencrypted direct messages | Encrypted XChat 1:1 and group conversations |
| Top-level posts | Posts from the bot account to the public timeline (x:public) | Not supported |
| Reactions | Likes only | Emoji reactions |
| Typing indicators and read receipts | Not supported | Supported |
| Encryption | None | Handled inside the adapter: Juicebox PIN, key exchange, and signed messages |
You can register both adapters on the same Chat instance if your bot needs public posts and DMs as well as encrypted XChat.
Platform setup
Register encryption keys
The bot account needs registered public keys and a Juicebox-backed private-key store before it can participate in encrypted conversations:
- Generate keypairs with
chat-xdk(generateKeypairs()). - Register them via
POST /2/users/{id}/public_keys. - Store the private keys in Juicebox with a PIN (
chat.setup(pin)).
The adapter unlocks the keys at startup with the same PIN (XCHAT_PIN). Registration is a one-time step per account.
Create a webhook
Register a webhook URL so the X Activity API can deliver events:
X validates the URL with a CRC challenge, so the endpoint must be live before you create the webhook. Webhooks and activity subscriptions can also be managed in the X Developer Portal.
Subscribe to chat events
Create activity subscriptions for the bot user with the bot's OAuth 2.0 user token:
Subscribe to chat.conversation_join as well if you want the bot to post a welcome message when it is added to a group.
Configuration
| Prop | Type | Default | Description |
|---|---|---|---|
botToken? | string | OAuth 2.0 user access token for the bot account (also accepted as `accessToken`). Auto-detected from `XCHAT_BOT_TOKEN` or `X_ACCESS_TOKEN`. | |
pin? | string | Juicebox PIN. When set, the bot's private keys unlock automatically during `initialize()`. Auto-detected from `XCHAT_PIN`. | |
consumerSecret? | string | App consumer secret for webhook signature verification. Auto-detected from `X_CONSUMER_SECRET`. Required to receive webhooks: X signs every POST, so without it every POST is rejected with 401. Polling deployments do not need it. | |
disableWebhookVerification? | boolean | Accept webhook POSTs without verifying their HMAC. Auto-detected from `X_DISABLE_WEBHOOK_VERIFICATION`. Only use it when an upstream layer verifies the signature. Not recommended in production. | |
editSafetyDelayMs? | number | 5000 | Minimum age (ms) a freshly posted message must reach before its first edit is sent, so receiving clients have stored the original the edit targets. `0` disables the wait. |
sendReadReceipts? | boolean | true | Send a read receipt for each delivered inbound message before handlers run. |
userName? | string | Bot @handle for mention detection. Auto-detected from `X_BOT_USERNAME`, otherwise resolved from `GET /2/users/me`. | |
welcomeMessage? | string | false | Message posted when the bot joins a group. `false` disables it; when omitted, the adapter posts a default that tells members to @mention the bot for a reply. | |
verifySignatures? | boolean | true | Require verifiable signatures on incoming messages. `X_VERIFY_SIGNATURES=false` opts out. |
signingKeyVersion? | string | Signing key version override. Normally fetched during `initialize()`. Auto-detected from `X_SIGNING_KEY_VERSION`. | |
apiBaseUrl? | string | "https://api.x.com" | Base URL for media REST calls. |
Environment variables
| Variable | Required | Description |
|---|---|---|
XCHAT_BOT_TOKEN | Yes, unless X_ACCESS_TOKEN is set | OAuth 2.0 user token for the bot account |
X_ACCESS_TOKEN | No | Fallback name for the bot token |
XCHAT_PIN | No | Juicebox PIN that unlocks the bot's private keys at startup |
X_CONSUMER_SECRET | To receive webhooks | App secret for CRC responses and webhook signature verification |
X_BOT_USERNAME | No | @handle override. Resolved from GET /2/users/me when unset |
X_VERIFY_SIGNATURES | No | Set to false to accept messages with unverifiable signatures |
X_DISABLE_WEBHOOK_VERIFICATION | No | Set to true to skip webhook HMAC verification when an upstream layer verifies it |
X_SIGNING_KEY_VERSION | No | Signing key version override |
Webhooks
The route handles two kinds of request from X:
- GET CRC challenge: the adapter answers with an HMAC-SHA256 of the token keyed by your app's consumer secret. Routing GET through the adapter lets it constrain CRC tokens before signing them.
- POST event delivery: the adapter verifies the
x-twitter-webhooks-signatureheader againstX_CONSUMER_SECRET.
Encryption
Every XChat conversation is encrypted, and the adapter handles the whole crypto lifecycle: conversation-key extraction and caching, message decryption and signature verification, and encryption and signing on send. Conversation keys arrive through KeyChange events and are cached per conversation and key version. Incoming message signatures are verified against participants' signing keys; with verifySignatures: true (the default), unverifiable messages are dropped. Media is encrypted separately from message text using streaming encryption.
Mention behavior in groups
bot.onNewMention(handler) fires for group messages that mention the bot. A group message counts as a mention when its rich-text mention entities include the bot's @handle or user ID, when it is a swipe-reply to one of the bot's own messages, or when its plain text contains @handle (fallback when no entities are present). To also reply to group messages that don't mention the bot, register bot.onNewMessage(handler) without a pattern.
Open DM
openDM(userId) reuses an existing conversation or runs a fresh key exchange so the bot can message first. It requires the recipient to have encrypted chat set up, and the server requires the recipient to trust the bot (for example, follow it) before the first message is accepted.
Formatting
XChat clients do not render markdown, so outgoing markdown appears literally as plain text. The adapter detects URLs and @mentions in outgoing text and renders them as tappable links and mention pills. Tables render as ASCII code blocks. Cards degrade to text with URL and mention entities plus a URL preview attachment: the first x.com/.../status/... URL in outgoing text auto-attaches as a post card.
Read receipts and typing
A read receipt is sent for each delivered inbound message before handlers run unless sendReadReceipts: false. To control the timing yourself, disable automatic receipts and call thread.markAsRead() in the handler. XChat advances the conversation's read watermark through the target message sequence. The typing indicator is re-sent every 3 seconds while a handler runs.
Automatic receipts never interrupt a handler, since a failure is logged and swallowed. A thread.markAsRead() call you make yourself rejects on failure, so await it or attach a .catch().
When a delivered message has no sequence id, such as an event the adapter could not decrypt, the watermark advances to the latest event in the conversation. When only an explicit message id is available, the adapter replays recent history and rejects if it cannot resolve that exact message rather than advancing through newer messages.
Edits, deletes, and streaming
The adapter can edit and delete only the bot's own messages. The first edit of a fresh message is held until the message is editSafetyDelayMs old (default 5000ms), so receiving clients have stored the original before the edit arrives. Deletes are delete-for-all. Streaming works through message edits, but the age gate makes rapid token-by-token updates coarse.
Thread IDs
- 1:1 conversations:
xchat:1234567890-9876543210(both participant IDs) - Group conversations:
xchat:g123456789(opaqueg-prefixed ID)
REST paths use the other participant's user ID for 1:1 conversations and the g... ID for groups; the adapter converts automatically.
Feature support
Messaging
| Feature | Supported |
|---|---|
| Post message | |
| Message replies | |
| Edit message | Own text messages, age-gated |
| Delete message | Own messages |
| File uploads | |
| Streaming | Age-gated edits |
| Scheduled messages |
Rich content
| Feature | Supported |
|---|---|
| Card format | Plain text + URL preview |
| Buttons | |
| Link buttons | Tappable URLs |
| Select menus | |
| Tables | ASCII |
| Charts | |
| Fields | Plain text |
| Images in cards | |
| Modals |
Conversations
| Feature | Supported |
|---|---|
| Slash commands | |
| Mentions | |
| Add reactions | |
| Remove reactions | |
| Typing indicator | |
| Mark as read | |
| Message edit events | |
| Message delete events | |
| DMs | |
| Ephemeral messages | |
| User lookup | |
| Parent subject | |
| Native client | |
| Custom API endpoint | Media REST calls |
Message history
| Feature | Supported |
|---|---|
| Fetch messages | |
| Fetch single message | |
| Fetch thread info | |
| Fetch channel messages | |
| List threads | |
| Fetch channel info | |
| Post channel message |