@kispi/chat Version 0.8.1Rendered from the README of the published package, so it matches exactly what npm serves.
Examples that use the chat-server CLI are for engine operators. As a consumer, create apps and keys in the console.
@kispi/chat
Client SDK for GravEx Chat, a managed realtime chat API. Many rooms over one socket, history in the right order. Zero runtime dependencies, both ESM and CJS, type declarations included.
- Get keys: sign up in the console to get a
ck_; your code creates apps andpk_/sk_keys through the console API. - Hand it to your AI: example prompts at /docs/ai, agent summary at llms.txt.
There are two entry points. @kispi/chat is the client for the browser and Node;
@kispi/chat/server is for the consumer backend that holds the sk_.
npm install @kispi/chatThis document covers the entire surface. Anything not here is internal and changes without notice.
@kispi/chat — client
createChatClient(options): ChatClient
| Option | Type | |
|---|---|---|
key |
string |
Required. A pk_. It is public, so it is fine to put in the browser |
token |
() => string | Promise<string> |
Required. A user token signed by your backend. Called again on every connect and whenever REST gets a 401, so an expired one is never reused. A throw is retried with backoff; throwing a ChatError means do not retry (see below) |
WebSocket |
new (url) => WebSocketLike |
Implementation to use instead of the global |
fetch |
typeof fetch |
Same as above |
Do not create token in the browser. Signing requires the sk_, and if the sk_
is in the browser, the whole app is open.
ChatClient
| Property | |
|---|---|
state |
'connecting' | 'open' | 'reconnecting' | 'closed' |
user |
The connected user. {id, name, avatar?} — the identity the server accepted from the token (what hello carried). Use this instead of parsing your token response. Set once connect()/reconnect() resolves |
connectionId |
Identifier used for support requests and forced disconnects |
hello |
Everything the server sent on connect: limits (effective), unread ({total, mentions, roomsCapped?} — absent is not zero, it means the count could not be read, so recover with unread()), warnings, serverTime, heartbeatMs |
| Method | |
|---|---|
connect() |
Connects. If already connected or connecting, it joins that attempt. Rejects on failure, but retries continue in the background (see below) |
close() |
Disconnects. This one does not reconnect. Call connect() to come back |
reconnect() |
Re-authenticates: calls token() again and replaces the socket. Room handles, subscriptions and messages are kept (when the user changes, messages is dropped and refilled), and the state goes open → reconnecting → open (never closed). Use it after a nickname or avatar change, and when logging in or out switches the user (below) |
room(roomId) |
Room handle. Same id, same object |
roomByKey(key) |
Handle for a room opened by key. The server tells you the id when you subscribe. Does not create the room — for a key that doesn't exist, subscribe() rejects with not_found. Rooms are created by the backend with rooms.ensure() |
roomList() |
The live list of my rooms (RoomList, below) — a channel sidebar. One per client |
rooms.list({cursor?, limit?}) |
One page of the rooms I'm in: {rooms: MyRoom[], cursor}. MyRoom is {room, lastSeq, readSeq, unread, unreadMentions, unreadCapped?, lastMessage?}, latest activity first |
rooms.discover({type?, cursor?, limit?}) |
Browse public rooms |
rooms.update(roomId, {name?, meta?}) |
Rename a room or change its meta. Owners and admins only (otherwise forbidden); every subscriber gets room.updated |
rooms.delete(roomId) |
Soft-deletes the room. Owner only (forbidden otherwise). Subscribers get room.deleted; it leaves roomList() |
rooms.members(roomId).list/add/remove |
Membership. list is {members: MemberRow[], cursor} — {userId?, name?, role, joinedAt?, withdrawn?} (a withdrawn row has no userId) |
unread() |
{total, mentions, roomsCapped?, rooms} — the same field names as chat.hello?.unread |
updateMe(meta) |
My meta. name and avatar come from the token claims |
| Event | |
|---|---|
state |
The four values above |
error |
The client stopped at closed on its own, and why (a ChatError): an authentication refusal, or a ChatError from token(). Not emitted for close() |
notification |
A new message arrived in a room I'm a member of, but I'm not viewing that room |
notification.typing |
{roomId, userId, threadId?} — someone is typing in a room I'm a member of but have not subscribed (a room list's "typing…"). It comes only for small rooms (about ten members or fewer; the engine may change it) — a bigger room sends nothing. Never for my own typing; for a subscribed room use typists() / typing.changed. Show it for five seconds or more, and clear it when that user's message arrives |
resumed |
{reconnected} — back after a reconnect (true), or a tab/app return, network return or back/forward-cache restore (pageshow) found the socket alive and resubscribed every room (false). Rooms and roomList() catch themselves up; use it to refetch what the SDK does not hold (an activity feed, search results) |
user.presence |
Presence changes of my other connections |
frame |
Every received frame. For debugging |
on returns an unsubscribe function.
const off = chat.on('state', s => setStatus(s))
off()Room
| Property | |
|---|---|
messages |
Ascending by seq. The SDK handles ordering and gap filling. A new array on every change. Thread replies are included (rows with a threadId) — to draw the main timeline only, keep the rows without one |
typing.changed |
{threadId?, userIds} — typists() changed for that place (the main timeline, or the thread rooted at threadId) |
id / key |
Room identifiers. If opened by key, id is absent until you subscribe |
lastSeq |
The room's last seq as reported by the server |
presence |
{count, users?, capped?} — who is in this room now. The SDK folds the subscribe ack and the increments of presence events into it. users is there only for rooms of 100 or fewer; larger, or unknown, it is absent — use presenceList() then |
hasOlder |
Whether loadOlder() has more past to read. Lets you decide whether to draw "load earlier" before the first loadOlder(). The same test as loadOlder()'s hasMore; false while the list is empty. Re-read it on messages |
| Method | |
|---|---|
subscribe() |
Turns on the live feed and reads the latest page (sends no limit, so it is the engine's client default, 20 messages; if the first screen is not full, keep calling loadOlder() while hasOlder). Does nothing if already caught up. Fine to call before connecting — it waits until connected (rejects with closed on close()) |
unsubscribe() |
Stops viewing this room. It is not resubscribed on reconnect |
send({text, attachments?, entities?, replyTo?, threadId?, meta?}, {clientMessageId?}) |
Publish. Acked with {messageId, seq}. If a subscription is in progress, it waits for it. While reconnecting it waits for the connection, then sends (below) |
loadOlder({limit?}) |
Reads the page before the oldest message (default 100) and prepends it to messages. Returns {messages, hasMore}. Use it when scrolling up. If the list is empty (before subscribing), it reads nothing |
history({before?, after?, limit?, view?}) |
Reads the past directly (no limit means the engine default of 20, at most 100). Independent of messages. view is 'main', 'all', or {thread: id} |
thread(rootId, {root?}) |
Thread handle (Thread, below). One per root id, cached until close() |
edit(messageId, {text?, entities?, attachments?}) |
Edits your own message. Replaces the body — pass back the attachments/entities to keep. Sender only, within the app's edit window (forbidden otherwise). The returned row is applied to messages and open threads at once |
delete(messageId) |
Deletes a message: your own, or anyone's for owners and admins. Idempotent. The row becomes a tombstone at once |
reload() |
Re-reads the latest page and replaces the list (pages loaded with loadOlder() are dropped). A reconnect already refreshes held rows by itself (below), so this is for manual refresh buttons |
react(messageId, emoji) / unreact(...) |
Reactions. Idempotent. Updates that row's myReactions before the frame goes out, and rolls it back if the server refuses. The count is not moved optimistically; it is set to the server's value when the reaction.* event arrives (below) |
reactionsOf(messageId, {emoji?, cursor?, limit?}) |
Who reacted. Each row is a (user, emoji) pair, so one person can appear on several rows. limit defaults to 50, max 100; the last page's cursor is an empty string |
markRead(seq, {threadId?}) |
Read cursor |
reads({userId?, cursor?, limit?}) |
Read cursors, paged. {reads: [{userId?, seq, threadId?, withdrawn?}], cursor}. userId narrows to one person -- reads({userId: chat.user.id}) recovers your own per-thread cursors. Stop when cursor is '' |
typing({threadId?}) |
Typing indicator. Does not throw. Call it on every input event — the SDK sends at most once per second per room. Pass threadId while writing a thread reply |
typists({threadId?}) |
Who is typing now, user ids, earliest signal first. Without you. Someone drops out five seconds after their last signal or when their message arrives. typing.changed fires on every change |
join() / leave() |
Membership |
presenceList() |
Who is in this room right now |
Event names are exactly the wire names, and the payloads are in the type declarations.
| Event | Payload |
|---|---|
message.created / message.updated |
Message. On created, thread is absent, reactions is empty, and the SDK fills myReactions with [] (the wire carries none) |
message.deleted |
{id, seq}. seq is the one the message got when it was published |
reaction.added / reaction.removed |
{messageId, emoji, count, userId?}. The SDK has already updated that row's reactions count (and myReactions if it was yours) in messages and in open thread handles. Only rows read with history() are the consumer's |
thread.updated |
{rootId, count, lastSeq?, lastAt?}. The SDK has already updated the root row's thread (count, lastSeq, lastAt) in messages and in thread handles' root |
presence |
{count, joined?, left?, users?, capped?}. joined/left are incremental, users replaces |
typing |
{userId, threadId?} -- threadId is the thread root id, absent for the main timeline |
read |
{userId, seq, threadId?} |
member.joined / member.left |
{userId, role?} |
room.updated |
The room object (unknown — the server's own representation) |
room.deleted |
{roomId} |
custom |
Exactly the object rooms.custom(roomId, payload) sent |
The SDK emits three more that have no wire counterpart.
| Event | When |
|---|---|
messages |
Every time the list changes. A new array each time; an emitted array is never touched again |
error |
Reading history or filling a gap failed. The room resubscribes itself. The retry button for a person is subscribe(). The refresh after a reconnect (below) failing also emits this, but then the room does not resubscribe (it stays subscribed; the next reconnect tries again) |
reset |
The list was discarded and refilled — the cursor was older than the retention period, or the client reconnected as a different user (below). You must discard what you rendered |
Things to know
messages is a new array every time, and only changed rows are new objects. Put it
straight into state that compares by reference.
// Svelte 5
let messages = $state.raw<Message[]>([])
room.on('messages', m => (messages = m))
// React
const [messages, setMessages] = useState<Message[]>([])
useEffect(() => room.on('messages', setMessages), [room])
// Vue
const messages = shallowRef<Message[]>([])
room.on('messages', m => (messages.value = m))Don't ignore
reset. If you keep appending to the old list, you're left with a gap that nobody fills.Attach the past to the same list with
loadOlder().history()is a direct read that doesn't touch the list, so merging and deduplicating fall to you.Draw reaction chips from
reactionsandmyReactionstogether.react()movesmyReactionsfirst and waits forreaction.addedfor the count, so an emoji you are the first to add sits briefly inmyReactionsonly. Draw that chip as the highlighted emoji alone (no count) rather than inventing a1— someone else may have pressed it in between.Each message has a cap on distinct emoji (
hello.limits.maxDistinctEmojiPerMessage, 20 by default). A new emoji past it is refused withinvalidand the SDK rollsmyReactionsback. Pressing an emoji already on the message is never capped. To disable a picker, check thatreactions.lengthhas reached the cap and the emoji is not among them.Draw a thread panel with
room.thread(rootId)(Thread, below). Old replies may not be in the room'smessages(it holds the recent part of the whole stream), so the handle reads them through the thread view and applies new replies, reactions, edits and deletes to them too.Draw "X is typing" from
typists(). The SDK drops you, and drops someone after five quiet seconds or when their message arrives. The rawtypingevent still comes, andtypingis also delivered to the sender. If you render "X is typing", skip your ownuserId.typingcarries no name. Look the name up inroom.presence.users— whoever is watching the room is there. Collecting names from message senders misses anyone who has not spoken yet. Ifusersis absent (a room over 100), fetch it once withpresenceList(), and fall back to a placeholder if the name is still missing.typingarrives at most once per person per room every three seconds. There is no "stopped" event, so keep the indicator for five seconds or more after the last one — even someone typing steadily can be broadcast more than four seconds apart, and anything shorter blinks between events.Each room announces only a few typists at a time (three today). Every broadcast goes out once per person in the room, and a screen draws "A, B and C are typing" at most anyway. In a busy room some people typing are never announced — don't write code that depends on the number (the engine may change it).
tsroom.on('typing', ({ userId }) => { if (userId === chat.user?.id) return const name = room.presence?.users?.find(u => u.id === userId)?.name showTyping(userId, name ?? 'Someone') // clearing it after ~5 seconds is yours to do })Draw a room list's "typing…" from
notification.typing. A room you have not subscribed gets notyping, so this event stands in -- for small rooms only (once you subscribe the room, the same person's typing arrives astyping.changedand this event stops). There is no "stopped" event: show it for five seconds or more and clear it when that user's message arrives (notification'spreview.sender.id).tsconst typingIn = new Map<string, Map<string, number>>() // roomId -> userId -> expiry chat.on('notification.typing', ({ roomId, userId, threadId }) => { if (threadId !== undefined) return // main timeline only const room = typingIn.get(roomId) ?? new Map() room.set(userId, Date.now() + 5_000) typingIn.set(roomId, room) renderRoomRow(roomId) // drop expired entries on a timer or the next render })The connection comes back on its own. It reconnects with exponential backoff, so don't write your own retry loop.
A reconnect also brings the rows you already hold up to date. The catch-up (
since) only fills new messages; a reaction, a thread count (thread.updated), an edit or a delete on a message you already had rides on no event while you were away. So after a real reconnect (including a tab or app returning from the background, same user) and once the catch-up is done, the SDK reads the newest page once (the engine's default, 20 messages; one GET per room) and merges them into the rows it holds. The list is not replaced (noreset, pages loaded withloadOlder()stay); each row that actually changed becomes a new object with amessage.updated, a row that is now deleted becomes a tombstone withmessage.deleted(messagesfires once). A row that a live event, or a reaction this client pressed, touched while the read was in flight is left alone because that value is newer. Rows older than that page are not re-read — usereload()for those. Thread replies live in the same timeline, so they are refreshed along with their roots. If the read fails onlyerroris emitted and the room stays subscribed. You do not need to callreload()yourself.What you send while reconnecting waits, then goes out.
send,react,unreactandmarkReadskip the backoff when the state isconnecting/reconnecting, wait for the connection, and send. If the socket drops before the ack, the same frame is sent once more — the server dedups onclientMessageId, and reactions and reads are idempotent, so nothing lands twice. Waiting plus the ack is capped at 15 seconds, thentimeout.closednow comes only from a stopped client (close(), an auth refusal, or neverconnect()ed).typing()does not wait; it is dropped.The SDK handles token expiry. When REST gets a 401 it calls
token()again and retries once. There's no need to reconnect periodically.Throwing a
ChatErrorfromtoken()stops the client. That is how you say a failure, like a ban, is not worth retrying.After a nickname or avatar change,
reconnect(). The server reads those values from the token claims once, when the socket authenticates.Logging in or out is
reconnect()too. Whentoken()returns a different user the SDK notices: every room drops the list it held, reads recent history again as the new user and emitsreset(the rows'myReactionswere the previous user's). A send, reaction or read still waiting for the previous user is rejected withclosedinstead of going out under the new name, so send as the new user afterreconnect()resolves.close()thenconnect()behaves the same. There is no need to create a new client. A room the new user cannot subscribe to (a private room only the previous user was in) emitserrorinstead ofresetand stays empty. Callreconnect()whenever the login state changes — the REST path that refreshes a token on a 401 does not check whether the user changed.
Thread — room.thread(rootId, {root?})
One thread panel. Replies are part of the room's stream, so their seqs are not contiguous and old ones
are not in the room's messages; the handle holds the replies it read through the thread view
(view=thread:<rootId>) and applies the room's events to them. It is live while the room is subscribed.
| Property | |
|---|---|
messages |
Replies, ascending by seq. A new array on every change. A deleted reply keeps its place as a tombstone (deletedAt) — filter it to hide it |
root |
The root: the room's own row, else the copy passed as {root} (an old message opened from search or a link), else undefined |
hasOlder |
Whether loadOlder() would find more replies |
loaded |
load() finished once |
| Method | |
|---|---|
load({limit?}) |
Reads the newest page of replies (100 by default and at most) and replaces what is held (replies that arrived live meanwhile stay). Call it when the panel opens |
loadOlder({limit?}) |
Prepends the page above the oldest reply. {messages, hasMore} |
markRead(seq?) |
The thread's read cursor (default: the newest reply held). Sends nothing when this handle already marked that far, so it can run on every messages event |
close() |
Stops following. room.thread(rootId) afterwards is a new handle |
Events: messages (replies changed), root (root changed — reactions, edit, delete, reply count),
error (the re-read after a reconnect failed; the handle stays).
- React with
room.react()— the room's list and every open thread press the same row optimistically together and roll back together. - Reply with
room.send({text, threadId: rootId}). The reply lands on this handle. - After a reconnect (same user) the newest 100 replies are re-read and merged: replies posted while away come in, held ones get their reactions, edits and deletes. A different user drops them and reads again. A root copy outside the room's list moves by events only (there is no single-message route to re-read it).
RoomList — chat.roomList()
The rooms you are in, with unread counts — a channel sidebar. Call load() once (up to 1000 rooms); the SDK keeps it current.
rooms |
RoomSummary[] — {id, room, lastSeq, readSeq, unread, mentions, unreadCapped?, lastMessage?}. A new array on every change. Server order (latest activity); sorting and grouping are the screen's |
get(roomId) |
One room |
load() |
Reads again and replaces. A call during one runs once more after it |
loaded |
load() finished once |
events rooms / error |
The list changed / a read failed |
What the SDK keeps current:
notification(a message in a room you have not subscribed): the server'sunread/unreadMentionsandlastSeq; +1 if the counts are missing. An unknown room (you were just added) reloads the list.- Subscribed rooms: a new message moves
lastSeq. Your ownroom.markRead(seq)on the main timeline movesreadSeqand zeroesunread/mentionsonce it reacheslastSeq. A subscribed room'sunreadis never raised — when a room on screen counts as read is the screen's call. room.updatedreplaces the room object;room.deletedand your ownmember.leftremove it (both arrive for subscribed rooms only).rooms.update()/rooms.delete()correct it from their answer.resumedreloads it — counts that moved while away ride on no event. A different user empties and reloads it.
Mention helpers — buildMentions · mentionSpans
An engine mention is {type: 'mention', userId, offset, length} in body.entities; offset/length are JS (UTF-16)
indexes into body.text covering the whole @name. The engine resolves userId for unreadMentions and push and does not check the offsets.
buildMentions(text, people, {skipCode?})— finds@namefor each ofpeople({id, name}[]) in the final text being sent. Not mail (a@b.com); the longer name first (@Annais notAnn); not when a letter follows the name; skips markdown code (fenced blocks, inline spans) unlessskipCode: false. Two people with one name are handed out inpeopleorder. At most 100.mentionSpans(text, entities)— the received entities that agree with the text, as{start, end, userId}[]: a mention with auserId, inside the text on one line, starting at@, not overlapping an earlier one.
const text = input.trim()
await room.send({ text, entities: buildMentions(text, picked) })text is untrusted plain text
Message text, and user-supplied display names/nicknames (name), are plain text
the engine does not HTML-escape or sanitize. This is by design — escaping depends on
the output context you render into (an HTML text node, an attribute, some other
format), which the engine cannot decide on your behalf. The engine only validates
(size, shape).
So consumers must render it as text — textContent, or your framework's text binding
(React's {text}, Svelte's {text}, Vue's {{ text }}). Never pass it straight into
innerHTML or v-html. If you add linkification or markup, don't build an HTML
string with a regex replace — build DOM from text nodes instead.
// Don't — builds an HTML string with a regex
el.innerHTML = text.replace(urlRegex, '<a href="$1">$1</a>')
// Do — builds DOM from text nodes
for (const part of splitByUrl(text)) {
el.appendChild(part.isUrl ? makeAnchor(part.text) : document.createTextNode(part.text))
}Bad-word filtering and similar moderation is not escaping — it's a tenant policy.
The engine only opens the mechanism (the before_publish hook); the consumer decides
(see the before_publish section in docs/protocol.md).
Using it in the browser
You must add the page's origin to the pk_'s allowed origins. That's the only thing —
the server emits CORS headers itself, so there's no proxy to touch. Origins are edited on the
key screen in the console.
Scheme, host and port must match exactly. https://example.com and
https://www.example.com, http://localhost:3000 and http://127.0.0.1:3000 are different
origins. Add development origins separately.
From an origin that isn't on the list it isn't just REST that fails — the connection itself
is a 401. An authentication refusal is a failure the SDK doesn't retry, so the client stops
at closed, and the reason arrives on chat.on('error').
On Node (bots, tests) there is no origin to add. The server accepts a request with no
Origin header without an origin check — Node's global WebSocket and fetch don't send one,
so they connect as is. If you set the header yourself, its value must be on the allowed list.
The origin list only stops another site from using your pk_ in a visitor's browser (a pk_ is
public). A user token is required everywhere.
Errors
Failures are ChatError. A text message (the default kind) needs text (whitespace-only counts as empty) or an attachment; otherwise it is refused with invalid.
try {
await room.send({ text })
} catch (err) {
if (err instanceof ChatError && err.code === 'rate_limited') {
retryAfter(err.retryAfterMs)
}
}| Field | |
|---|---|
code |
A union of the known values (ChatErrorCode), so a typo fails to compile. From the server: unauthorized, forbidden, not_found, invalid, too_large, rate_limited, banned, moderation_denied, cursor_too_old, quota_exceeded, internal. From the SDK: timeout, closed. A code the server adds later still type-checks |
retryAfterMs |
Wait time reported by the server when you hit a limit |
appCode |
Consumer-side code attached by a before_publish webhook when rejecting |
status |
HTTP status, if the error came from a REST call |
quota_exceeded means the app's storage quota (limits.maxStoredMessages) is full. Only new messages are refused (403 over REST); edits, deletes and reactions still work. Deleting messages does not free space (deleted messages are still counted) -- it clears when the app operator raises the quota or purges rooms. Waiting does not clear it, so there is no retryAfterMs and the SDK does not resend -- show "storage is full" instead of retrying.
@kispi/chat/server — backend
Uses the sk_. Never put it in the browser.
import { createChatServer } from '@kispi/chat/server'
const chat = createChatServer({
secretKey: process.env.CHAT_SECRET_KEY!, // sk_…
webhookSecret: process.env.CHAT_WEBHOOK_SECRET,
guestSecret: process.env.CHAT_GUEST_SECRET, // only if you use guest()
})chat.token(input): string
A local signature that doesn't touch the network.
| Field | |
|---|---|
userId |
Required. Becomes the JWT sub. Your service's user id |
name |
Required. This value wins on every connect |
avatar, meta |
Optional |
ttlSeconds |
Default 1 hour, max 24 hours. Exceeding it is rejected, not truncated |
chat.guest({credential?, name, avatar?, meta?, ttlSeconds?})
Identity for a visitor who isn't logged in. Returns {userId, credential, token, created}.
Uses neither the network nor storage.
app.post('/api/chat-token', (req, res) => {
if (req.user) return res.json({ token: chat.token({ userId: req.user.id, name: req.user.name }) })
const g = chat.guest({ credential: req.cookies.chat_guest, name: 'Guest' })
res.cookie('chat_guest', g.credential, { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 400 * 864e5 })
res.json({ token: g.token })
})Never sign a userId handed back by the browser as-is. guest() has the browser hold a
credential instead of the id — if it verifies, it signs with the id inside it; if it's
missing or invalid, it signs a new guest (created: true). Keep it in an httpOnly cookie
where you can.
guestSecret |
At least 32 characters. Keep it on the backend only. Don't derive it from the sk_ |
| Rotation | Pass an array: [new, old]. Signs with the first and verifies with all. A credential verified with an old one is re-signed with the same userId and returned, so it migrates on the next visit |
Guest ids start with g_. As long as logged-in users' ids don't start with g_, the two
spaces don't overlap.
The rest
| Group | Methods |
|---|---|
rooms |
list({type?, cursor?, limit?}), ensure({key?, type, name?, meta?, members?}), ensureDM([a, b]), get, update, delete, custom(roomId, payload), presence(roomId, {full?}), members.list/add/remove |
messages |
send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?}), list(roomId, {before?, after?, limit?, view?, q?}), delete |
users |
list({cursor?, limit?}), update(userId, {name?, avatar?, meta?}), withdraw(userId, {purgeMessages?}), purgeMessages(userId), ban(userId, {until, reason?}), unban(userId), revokeTokens(userId), disconnect(userId, {connectionId?, reason?}) |
events |
list({after?, limit?}) — catches up on missed webhook events |
webhooks |
verify(headers, rawBody, {now?, tolerance?}) — tolerance is in milliseconds |
messages.list takes view — 'main', 'all' (default) or {thread: rootId} — and q, a body search in the room
(substring, case-insensitive, deleted messages excluded). q is secret-key only — a user token gets 403 (an unindexed scan).
A search page's seqs are not contiguous; never use them as a sync cursor.
rooms.list returns the app's rooms, newest first. With no type it is the public listing
(public and channel); pass e.g. type: ['private', 'dm'] for private rooms and DMs. limit
defaults to 50 (max 100), an empty cursor is the last page, and the cursor does not carry
type — start over when the filter changes.
rooms.ensure is get-or-create — it returns the room as-is if it exists, so it's fine to call
on every page load.
rooms.presence(roomId) is {count}; with {full: true} it adds users (at most 1000,
capped: true when cut). An empty room is {count: 0}, not a 404.
rooms.custom(roomId, payload) is a control signal that is not stored. payload is a JSON
object and arrives as-is at room.on('custom', ...). It leaves no history, no unread and no
webhook, so send a signal that must survive a reconnect with
messages.send(roomId, {kind:'system', ...}) instead.
users.ban's until is unix milliseconds and required. For an indefinite ban, pick a
far-future time yourself.
users.purgeMessages(userId) clears that user's messages without withdrawing them. It does
a bounded amount per call, so call again while purgeCapped is true, and for spam ban first.
await chat.users.ban(userId, { until: Date.now() + 7 * 86_400_000, reason: 'spam' })
while ((await chat.users.purgeMessages(userId)).purgeCapped) {}users.list is newest first, limit defaults to 50 and maxes at 100, and cursor is
an opaque string where an empty string marks the last page. Withdrawn users are included too,
and deletedAt marks them. users.* works only after the person has connected at least
once — users come into existence by connecting.
Webhooks
app.post('/chat-hook', express.raw({ type: 'application/json' }), (req, res) => {
const { event, delivery, data } = chat.webhooks.verify(req.headers, req.body.toString('utf8'))
if (seen.has(delivery)) return res.sendStatus(200) // it's at-least-once
res.sendStatus(200) // acknowledge first
void handle(event, data) // process asynchronously
})It must be the raw body. Something parsed and re-serialized is a different string and fails verification.
Keep three things. verify checks the signature and the timestamp (default 5 minutes),
deduplication is on you (by delivery), and you must respond with a 2xx within 10 seconds.
Going over counts as a failure and backoff begins.
The signature spec for other languages is in the webhooks guide.