SDK guide
Messages, reactions and attachments
Send, read, edit, delete and react to messages with the SDK, and use typing, read state, presence, attachments and webhooks.
Specification: 11 Messages, attachments, read state and presence, 03 Client transport, envelopes and errors, 14 Sealed messages, history visibility and sharing
Everything on this page is a resource API of a ServerClient: messages, reactions, typing, readState, presence, attachments and webhooks. Most methods map to one endpoint of document 11, and the protocol side of it is explained on Messages and attachments. The methods here send the insecure carrier; secure contexts are covered at the end.
Most samples after the first assume a server (the ServerClient that hosts the context) and a ctx (the context ID of a channel, DM or group DM), declared with declare const so each sample typechecks on its own.
Sending a message
MessagesApi.send turns text into a MessageContent, checks it against 11 §3 and the server's maxMessageBytes, and posts it to POST /v1/contexts/{ctx}/messages (11 §4.1). It answers with an EntryAck, which gives the assigned seq.
import { SloppyVoiceClient, botToken } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
const sv = new SloppyVoiceClient({
client: 'notes-bot/1.0',
home: 'example.com',
auth: botToken(process.env.SV_BOT_TOKEN!),
txt: nodeTxtResolver(),
})
// The server that hosts the channel; a remote session is created if it isn't the home server.
const server = await sv.serverFor('lobby@example.com')
const ctx = 'ch:01938a11-2b3c-7d4e-8f90-112233445566'
const ack = await server.messages.send(ctx, 'Hello')
console.log(ack.mid, ack.seq, ack.createdAt)The text is prepared the way 11 §3.2 asks: CR LF and lone CR become LF, the text is put in NFC and trimmed. Content that breaks a rule throws sdk.invalid_argument before any request is made, with data.field and data.reason in the same form as the server's message.invalid_content.
The mid and idempotency
Every entry carries a mid, a lowercase UUIDv7 the client generates when the user creates the entry (11 §2.4). It is the idempotency key for the context, so Idempotency-Key isn't used on this endpoint and send ignores the idempotencyKey option (11 §4.6). A resend with the same mid, kind and target from the same account answers 201 with the stored EntryAck and changes nothing, even after the entry was deleted, for at least 30 days.
Because of that rule the SDK marks the request idempotent and retries network failures, timeouts, problems with retryable: true and bare 429, 502, 503 and 504 answers itself, up to 5 attempts per call by default (03 §2.7). send picks a new mid with MessagesApi.newMid unless you pass one, so pass the mid yourself whenever the message must survive a crash or a longer outage:
import type { CtxRef, ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
const mid = server.messages.newMid()
// Store { ctx, mid, text } durably here, before the first attempt.
await server.messages.send(ctx, 'Nightly backup finished', { mid })An outbox
11 §13 requires every client that sends, bots included (11 §1.1), to keep a persistent outbox: send in creation order with one request in flight per context, keep items up to 7 days, and resend the stored body byte for byte with the same mid (11 §13.4 rule 3). The SDK doesn't store anything for you, but it gives you the pieces:
- buildMessageContent and assertValidContent build and check the content once, so you can store the exact PostEntry.
- MessagesApi.post sends a stored PostEntry unchanged.
- outboxDecision maps an error to the item's next state from the table in 11 §13.3, with any step you must take first (
join_channel,reseal,reencode_secure,reupload_attachments,find_successor). - outboxRetryDelayMs gives the backoff of 11 §13.4 rule 2: 1, 2, 4, 8, 16, 30 and 60 s, then every 60 s, with ±20 % jitter, never sooner than
retryAfterMs.
import {
assertValidContent,
buildMessageContent,
outboxDecision,
outboxRetryDelayMs,
type EntryAck,
type PlainPostEntry,
type CtxRef,
type ServerClient,
} from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
const content = buildMessageContent('Deploy of build 1432 started')
assertValidContent('message', content, { maxMessageBytes: server.messages.maxMessageBytes })
const entry: PlainPostEntry = { mid: server.messages.newMid(), content }
// Persist `entry` as the outbox item's lastBody here.
async function deliver(entry: PlainPostEntry): Promise<EntryAck | null> {
for (let attempt = 0; ; attempt++) {
try {
return await server.messages.post(ctx, entry)
} catch (e) {
const next = outboxDecision(e, { kind: 'message' })
if (next.state === 'sent') return null
if (next.action || (next.state !== 'sending' && next.state !== 'waiting_for_server')) throw e
await new Promise((r) => setTimeout(r, outboxRetryDelayMs(attempt, next.retryAfterMs)))
}
}
}
await deliver(entry)A failed item is one nothing will fix by itself; show it neutrally as "Not sent. Tap to retry or delete." and never as a security warning (11 §13.5). outboxExpired tells you when an item has passed the 7-day limit.
Content helpers
The content schema of 11 §3 is the same in both security modes, and these exported functions implement it:
| Function | What it does |
|---|---|
| buildMessageContent | Text to MessageContent, with mentions and mentionAll computed from the tokens, replyTo and attachments filled in (11 §3.2). |
| buildEditContent, buildReactionContent, buildDeleteContent | The operation content objects of 11 §3.7. |
| contentIssues, assertValidContent | Every rule of 11 §3 and the size limit; the first returns a list, the second throws. |
| contentSize, maxMessageBytes | The JCS length the server measures, and the limit from ServerMetadata limits (the 8,192-byte floor when absent) (11 §2.3, 11 §3.8). |
| prepareOutgoingText, sanitizeReceivedText | Line endings, NFC and trimming before sending; U+FFFD for forbidden characters in decrypted text before display. |
| receivedContentIssues | The structural checks a receiver applies before showing an entry (11 §3.9). |
text is at most 4,000 Unicode scalar values and may be empty only when there are attachments; mentions has at most 50 addresses and attachments at most 10 (11 §3.2). Check the size before the user presses send, because the server refuses anything over maxMessageBytes with 413 message.too_large:
import { buildMessageContent, contentIssues, contentSize, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const draft: string
const content = buildMessageContent(draft)
const size = contentSize(content)
if (size > server.messages.maxMessageBytes) {
console.log(`Message is ${size} bytes; this server allows ${server.messages.maxMessageBytes}.`)
}
// Pass the server's limit; without it contentIssues checks against the 8,192-byte floor.
for (const issue of contentIssues('message', content, { maxMessageBytes: server.messages.maxMessageBytes })) {
console.log(issue.field, issue.reason, issue.message)
}Replies and mentions
Pass replyTo to reply to a root message. A ReplyRef has the parent's mid, its sender's canonical author, and ping (default true), which decides whether the reply notifies the author (11 §3.5). Replies are one level deep and always point at a root message in the same context.
Mentions live in the text as tokens: <@addr> for an account, <#addr> for a channel and <@everyone> (11 §3.4). mentionToken and channelToken format them and throw for an address that isn't canonical, because a non-canonical token is literal text. When you pass text, send computes mentions and mentionAll from the tokens, so they always agree with the text, which an insecure server requires (11 §3.4 rule 4); a MessageContent you pass is sent as given.
import { EVERYONE_TOKEN, mentionToken, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
const parent = await server.messages.get(ctx, '01938f2f-77aa-7c10-9b2e-0c1d2e3f4a5b')
await server.messages.send(ctx, `Thanks ${mentionToken('bob@b.com')}, merged.`, {
replyTo: { mid: parent.mid, author: parent.sender.addr!, ping: false },
})
// Notifies everyone only if the sender has mention_everyone; otherwise it is recorded as false.
await server.messages.send(ctx, `${EVERYONE_TOKEN} The server restarts at 22:00 UTC.`)The server refuses more distinct addresses than the AntiSpamPolicy mentionLimit (default 20) with 400 message.too_many_mentions, and accepts <@everyone> from a sender without mention_everyone but records mentionAll: false and notifies nobody (11 §4.4).
On the receiving side, use mentionsOf to decide whether a message concerns the reader: by a token naming them (the tokens are authoritative, not mentions), by a reply to them with ping not false, or by <@everyone> when the server-validated mentionAll of the Message is true. honoursMentionAll answers only the last question, for rendering <@everyone> as a highlight or as plain text.
import { mentionsOf, type Message } from '@sloppyvoice/sdk'
declare const message: Message
if (message.content) {
const m = mentionsOf(message.content, 'alice@a.com', { validatedMentionAll: message.mentionAll })
if (m.any) console.log('Highlight', m.byName ? 'mention' : m.byReply ? 'reply' : '@everyone')
}Reading history
MessagesApi.history (also available as list) walks the timeline of GET /v1/contexts/{ctx}/messages and returns a Pager: iterate it with for await to get items across pages, call page() for the first page only, or pages() to go page by page (11 §7.1, 03 §13.1).
- No parameters: the newest page first, then older pages. Items come out newest first.
before: N: items belowN, then older. Items come out newest first.after: N: items aboveN, then newer. Items come out oldest first.
Each next page uses the first item's seq as before (backwards) or the last item's seq as after (forwards), and iteration stops when hasMore is false or a page is empty. limit is 1 to 100, default 50.
import type { CtxRef, ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
// The 200 newest root messages, newest first.
let n = 0
for await (const item of server.messages.history(ctx, { limit: 100 })) {
if (item.type !== 'message') continue // a SystemItem such as member.joined
console.log(item.seq, item.sender.name, item.deleted ? '(deleted)' : item.content?.text)
if (++n === 200) break
}
// Everything after seq 4182, oldest first.
for await (const item of server.messages.history(ctx, { after: 4182 })) {
console.log(item.seq, item.type)
}Timeline items are root messages (tombstones included) and system items owned by other documents; edits, reactions and deletes change a Message instead of adding items. A TimelineItem is either a Message with type: "message" or a SystemItem with type: "event". Render the system items you know as their owner says, and count the seq of the ones you don't as covered.
The page object, a MessagePage, carries what a cache needs besides the items: headSeq, the ranges the caller may read, grants, withheldBeforeSeq and purgedThroughSeq. Use page() or pages() when you need them:
import type { CtxRef, ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
const newest = await server.messages.history(ctx, { limit: 50 }).page()
console.log(newest.headSeq, newest.ranges, newest.purgedThroughSeq)
for await (const page of server.messages.history(ctx, { before: 4183, limit: 100 }).pages()) {
// Items within a page are in ascending seq whichever way you walk.
console.log(page.items.length, page.hasMore)
}A seq or headSeq from a page never advances your event-stream position; only processing events in order on the socket, or a resync, does (03 §2.8).
Jumping to a message
To show a reply's parent or jump to a linked message, fetch it with MessagesApi.get and load the items around its seq with MessagesApi.around: up to floor(limit / 2) items before it, the item at it and the rest after, with hasMoreBefore and hasMoreAfter (11 §7.1, 11 §7.2). get answers 404 message.target_not_found for a message that isn't visible, has expired or whose tombstone was dropped.
import { isSloppyVoiceError, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
try {
const target = await server.messages.get(ctx, '01938f30-1b2c-7d4e-8f90-a1b2c3d4e5f6')
const page = await server.messages.around(ctx, target.seq, { limit: 50 })
console.log(page.items.length, page.hasMoreBefore, page.hasMoreAfter)
} catch (e) {
if (!isSloppyVoiceError(e, 'message.target_not_found')) throw e
console.log('Original message was deleted')
}Changes since a sync point
After a session.resync_required, or when you start with a cache but no socket history, MessagesApi.changes reads the changes feed: items whose updatedSeq is above changedAfter, optionally only those with seq up to through, in ascending updatedSeq (11 §7.4). The pager uses the last item's updatedSeq (a SystemItem's seq) as the next changedAfter. A 410 message.changes_expired means the sync point is older than the server keeps; discard the cache and reload from the newest page (11 §7.6).
import { isSloppyVoiceError, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
declare const syncedSeq: number // highest seq applied to the cache
declare const heldSeq: number // highest item held in the cache
try {
for await (const item of server.messages.changes(ctx, { changedAfter: syncedSeq, through: heldSeq })) {
console.log(item.type === 'message' ? item.updatedSeq : item.seq)
}
} catch (e) {
if (!isSloppyVoiceError(e, 'message.changes_expired')) throw e
// Discard the cache and start again from the newest page.
}Live events
Subscribe to the context on the event WebSocket to keep the view current. The events of 11 §8.1 are typed by the SDK's EventMap; a durable payload may be the reduced form { "withheld": true }, which isWithheldPayload detects (11 §8.3). Apply an edit, delete or reaction event only if its seq is greater than the cached Message's updatedSeq, which shouldApplyEvent checks (11 §7.6).
import { isWithheldPayload, shouldApplyEvent, type Message, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
declare const cache: Map<string, Message>
const events = server.events({ subscribe: [ctx] })
events.on('message.created', (e) => {
if (isWithheldPayload(e.d)) return
console.log('new', e.d.mid, e.d.content?.text) // deduplicate by mid: your own messages arrive here too
})
events.on('message.edited', (e) => {
if (isWithheldPayload(e.d)) return
const cached = cache.get(e.d.target)
if (cached && e.seq !== undefined && shouldApplyEvent(cached, e.seq)) {
if (e.d.content) {
const { target: _target, ...content } = e.d.content
cached.content = content
}
cached.mentionAll = e.d.mentionAll
cached.editedAt = e.d.createdAt
cached.updatedSeq = e.seq
}
})
await events.connect()Editing
MessagesApi.edit posts an edit entry whose EditContent completely replaces the message's content (11 §3.7.1, 11 §6.2). An edit never changes replyTo and can remove attachments but never add them, so edit needs the message's current content as previous when you pass new text: it copies replyTo and keeps every attachment.
import type { CtxRef, ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
const mid = '01938f30-1b2c-7d4e-8f90-a1b2c3d4e5f6'
const message = await server.messages.get(ctx, mid)
if (message.content) {
await server.messages.edit(ctx, mid, 'Hello, everyone in **Lobby**', { previous: message.content })
}To remove an attachment, build the EditContent with buildEditContent and a keepAttachments filter, then pass it to edit with the same previous so the SDK can check it against 11 §3.7.1:
import { buildEditContent, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
declare const mid: string
declare const dropId: string
const message = await server.messages.get(ctx, mid)
if (message.content) {
const edit = buildEditContent(mid, message.content, message.content.text, {
keepAttachments: (ref) => ref.id !== dropId,
})
await server.messages.edit(ctx, mid, edit, { previous: message.content })
}Only the author can edit, only a root message that isn't deleted, and only with the carrier type it was sent with; otherwise the server answers 404 message.target_not_found, 403 message.not_author, 409 message.target_deleted or 409 message.not_editable (11 §6.2). Webhook messages can't be edited. There is no time limit and no edit history: show "(edited)" with editedAt.
Deleting
MessagesApi.delete posts a delete entry for one of your own root messages (11 §6.3). It needs no permission and isn't blocked by a timeout. The message becomes a tombstone (deleted set, no content), and its edits, reactions and files go with it. "Delete for everyone" is the only delete, so never promise that copies are gone from other members' devices.
import { isSloppyVoiceError, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
try {
await server.messages.delete(ctx, '01938f36-0000-7a00-8b00-000000000001')
} catch (e) {
// A delete of something already deleted is done (11 §6.3).
if (!isSloppyVoiceError(e, 'message.target_deleted')) throw e
}Deleting someone else's message is a moderation action with manage_messages, made through ModerationApi.deleteMessages; see Roles and moderation.
Reactions
A reaction is a reaction entry posted to the same endpoint, and removing one is a delete of the reaction entry's mid, not the message's (11 §3.7.2, 11 §6.5). ReactionsApi.add checks the key first: exactly one emoji (one grapheme cluster matching UTS #51 possible_emoji), at most 64 bytes of UTF-8. Keep the EntryAck's mid so you can remove the reaction later.
import { isSloppyVoiceError, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
const messageMid = '01938f30-1b2c-7d4e-8f90-a1b2c3d4e5f6'
let reactionMid: string
try {
reactionMid = (await server.reactions.add(ctx, messageMid, '👍')).mid
} catch (e) {
// You already reacted with this key: data.mid names your existing entry (11 §6.5).
if (!isSloppyVoiceError(e, 'reaction.already_exists')) throw e
reactionMid = e.data?.['mid'] as string
}
await server.reactions.remove(ctx, reactionMid)The server allows at most 20 live reactions per account per message and 20 distinct plain keys per message, each answered with 409 reaction.too_many; adding needs add_reactions, removing your own needs nothing.
A Message carries plain reactions as ReactionSummary objects (key, count, me) and up to 100 sealed reaction entries. mergeReactions combines the plain summaries with the sealed entries you have decrypted (passed as its second argument) for display, grouping by key with U+FE0F removed, so "❤" and "❤️" are one reaction, and counting each account once per key (11 §5.5). For "who reacted with 👍", or sealed entries beyond the 100, page through ReactionsApi.list (11 §7.3):
import { mergeReactions, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
const message = await server.messages.get(ctx, '01938f30-1b2c-7d4e-8f90-a1b2c3d4e5f6')
for (const r of mergeReactions(message)) console.log(r.key, r.count, r.me ? '(you)' : '')
for await (const entry of server.reactions.list(ctx, message.mid, { key: '👍' })) {
console.log(entry.sender.name, entry.createdAt)
}Typing
TypingApi sends POST /v1/contexts/{ctx}/typing with start, stop or set (11 §10.1). Rather than timing those calls yourself, use TypingNotifier, which follows 11 §10.3: typing: true on the first change to a non-empty draft and again every 6 s while it keeps changing, typing: false when the draft empties or you call left() because the user left, and nothing after the message is sent, because the server clears the mark itself. With enabled: false, for a user who turned off "Show when I'm typing" (typing_indicators), it never calls the endpoint.
On the receiving side, TypingTracker shows an account until its typing.stopped, its message.created, or 10 s after its last typing.started, because ephemeral events can be dropped. typingLine formats the line.
import { TypingNotifier, TypingTracker, isWithheldPayload, typingLine, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
const notifier = new TypingNotifier(server.typing, ctx, { onError: (e) => console.warn(e) })
await notifier.draftChanged('Hel') // sends typing: true
// After sending the draft as a message:
notifier.sent()
const tracker = new TypingTracker()
const events = server.events({ subscribe: [ctx] })
events.on('typing.started', (e) => tracker.started(e.d))
events.on('typing.stopped', (e) => tracker.stopped(e.d))
events.on('message.created', (e) => {
if (!isWithheldPayload(e.d)) tracker.messageFrom(e.d.sender)
})
await events.connect()
setInterval(() => console.log(typingLine(tracker.active().map((s) => s.name))), 1000)Read state
Read state is one number per account per context, readSeq, shared by the account's devices and never shown to other people (11 §9). ReadStateApi wraps the endpoints:
get(ctx)returns one ReadState, withunreadCount,mentionCountandunreadCapped.markRead(ctx, seq)storesmax(old, seq);markUnread(ctx, seq)lets it go down.list()pages through every context you can see on the server (limit1 to 1,000, default 200). Call it at start-up and after a resync of themestream instead of one request per context (11 §9.2).
ReadMarker implements 11 §9.3 rule 1: report each root message that has been on screen in a focused window with seen(seq), and it advances readSeq at most once every 2 s per context, then once more on leave().
import { ReadMarker, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
for await (const state of server.readState.list()) {
console.log(state.ctx, state.unreadCount, state.unreadCapped ? '999+' : '', state.mentionCount)
}
const current = await server.readState.get(ctx)
const marker = new ReadMarker(server.readState, ctx, { initialReadSeq: current.readSeq })
marker.seen(4190)
// When the user leaves the context:
await marker.leave()Every change is echoed as read.updated on the me stream of each of the account's sessions on that server, the caller's included.
Presence
Presence is per server and never federated (11 §11.1). The home server holds the chosen status; the client reads it there and copies it to every other server it is connected to, home first on a change (11 §11.6 rule 2). PresenceApi has two writers, matching the two kinds of PUT /v1/me/presence body (11 §11.2):
setStatussendsstatus,statusText,statusEmojiandclearAttogether, as the spec requires.statusTextis at most 128 Unicode scalar values,statusEmojione emoji,clearAtnullor a future time at most 30 days ahead.setIdlesends only this session'sidleflag. Set it after 10 minutes without input and clear it on the next input (11 §11.6 rule 1).
statusOf takes the account-level members from an OwnPresence, without idle, so a copy never changes another session's flag.
import { statusOf, type SloppyVoiceClient } from '@sloppyvoice/sdk'
declare const sv: SloppyVoiceClient
const home = await sv.home()
const own = await home.presence.setStatus({
status: 'dnd',
statusText: 'In a meeting until 3',
statusEmoji: '📅',
clearAt: new Date(Date.now() + 2 * 3_600_000).toISOString(), // a future time, at most 30 days ahead
})
for (const server of sv.servers()) {
if (!server.isHome) await server.presence.setStatus(statusOf(own))
}
await home.presence.setIdle(true)Other people's presence arrives as presence.snapshot when you subscribe to a context and presence.updated after that. Pass a received status through normalizeEffectiveStatus, which treats an unknown value as online, and show nothing for offline.
Attachments
Files are uploaded to the context's hosting server before the message that references them (11 §14.2). AttachmentsApi.uploadAttachment runs the whole flow and returns the server's Attachment and the AttachmentRef to put in the content:
- Before anything is sent, it checks the size against the server's advertised
maxAttachmentBytes(the spec default is 25 MiB; the SDK assumes the 8 MiB floor when the server advertises none, 11 §2.3), because 11 §14.6 asks clients never to start an upload they know will fail, and it refuses empty files, which 11 §3.6 doesn't support. - It creates the upload,
PUTs the bytes toupload.urland completes it. The session token goes only to a URL under the server's base URL; a pre-signed capability URL gets noAuthorization(11 §14.2). - On 422 attachment.size_mismatch or attachment.hash_mismatch it uploads the bytes once more, and if the upload URL expired it deletes the upload and starts again once (11 §13.3).
Images and video should have a thumbnail of at most 512 px on the longer side, WebP, JPEG or PNG, and at most 256 KiB, uploaded first with AttachmentsApi.uploadThumbnail, which checks the type, dimensions and size before uploading (11 §14.3). You must remove location data (EXIF GPS and equivalent) from photos and videos before uploading, unless the user turned that off (11 §14.3); the SDK uploads the bytes you give it unchanged.
import { readFile } from 'node:fs/promises'
import type { CtxRef, ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
const photo = new Uint8Array(await readFile('site.jpg'))
const preview = new Uint8Array(await readFile('site-thumb.webp'))
const thumb = await server.attachments.uploadThumbnail(ctx, preview, {
secure: false,
mime: 'image/webp',
width: 384,
height: 512,
})
const file = await server.attachments.uploadAttachment(ctx, photo, {
secure: false,
name: 'site.jpg',
mime: 'image/jpeg',
width: 3024,
height: 4032,
thumb: thumb.ref,
})
await server.messages.send(ctx, 'Site photo', { attachments: [file.ref] })Reference an upload within 24 h; after that the entry fails with 410 attachment.expired and you upload again, which gives new IDs (11 §14.5). Posting the entry binds the attachment to it, and a blob binds to one message only. To cancel an upload you won't use, call AttachmentsApi.delete; a bound one answers 409 attachment.already_bound. Each account may hold at most 50 unbound uploads per server, beyond which the server answers 429 attachment.quota_exceeded.
If you need the individual steps, create, put (or putContent for the server's own endpoint) and complete are there too.
Downloading
AttachmentsApi.downloadFile downloads a referenced file and checks its size, and sha256 where the reference has one; in a secure context it also decrypts it (11 §14.3, 11 §14.4). AttachmentsApi.downloadResponse returns the raw Response for streaming, with an optional single byte range, and download returns the bytes without checks. A redirect to a capability URL is followed without Authorization.
import type { CtxRef, Message, ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
declare const message: Message
for (const ref of message.content?.attachments ?? []) {
// The thumbnail first; the full file only when the user opens it.
if (ref.thumb) {
const preview = await server.attachments.downloadFile(ctx, ref.thumb, { secure: false })
console.log(ref.name, 'preview', preview.length, 'bytes')
}
}
const first = message.content?.attachments?.[0]
if (first) {
const res = await server.attachments.downloadResponse(ctx, first.id, { range: { start: 0, end: 65535 } })
console.log(res.status, res.headers.get('content-length'))
}Never open or run a downloaded file automatically. Show image/png, image/jpeg, image/gif, image/webp, video/mp4, video/webm, audio/ogg, audio/mpeg, audio/mp4 and audio/webm inline, and everything else as a card with its name, size and "Save". In a DM that is still a message request, don't fetch attachments until the user accepts (11 §14.4).
Webhooks
A webhook lets an outside service post into one insecure channel with a secret token, without being a member (11 §15). The feature is optional: check for webhooks in ServerMetadata features instead of probing (11 §15.1). In a secure channel, creating, enabling, rotating or executing one answers 403 security.context_secure_unsupported.
Managing webhooks needs manage_channels (11 §15.3). WebhooksApi.create returns the token once, in token; the server keeps only a hash, so show it to the user right away with "Anyone with this token can post in this channel." list, get, update, rotateToken and delete cover the rest; rotating stops the old token at once, and deleting a webhook leaves its messages in place. At most 15 webhooks per channel, beyond which the server answers 409 message.webhook_limit.
import { WEBHOOKS_FEATURE, type CtxRef, type ServerClient } from '@sloppyvoice/sdk'
declare const server: ServerClient
declare const ctx: CtxRef
if (server.metadata.features.includes(WEBHOOKS_FEATURE)) {
const hook = await server.webhooks.create(ctx, { name: 'CI', allowMentionAll: false })
console.log(hook.id, hook.token) // the token is never shown again
}The service that posts doesn't need an account: an anonymous client and the webhook token are enough. WebhooksApi.execute sends the token as a Bearer token, never in the URL, and accepts only text, mentions and mentionAll (11 §15.4); buildWebhookContent builds that from text. Send a mid so a retry can't post twice: with one the request is idempotent and retried automatically, without one it isn't.
import { SloppyVoiceClient, buildWebhookContent, uuidv7 } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'
const sv = new SloppyVoiceClient({ client: 'ci-notify/1.0', txt: nodeTxtResolver() })
const server = await sv.server('example.com')
await server.webhooks.execute(
'ch:01938a11-2b3c-7d4e-8f90-112233445566',
'01938f50-1a2b-7c3d-8e4f-5a6b7c8d9e0f',
process.env.SV_WEBHOOK_TOKEN!,
{ mid: uuidv7(), content: buildWebhookContent('Build 1432 passed on main.') },
)A bad token, or a missing or disabled webhook, answers 401 without saying which, and each webhook may execute at most 30 times per minute. When a channel is upgraded to secure, its webhooks are disabled permanently with disabledReason: "secure_context" (11 §15.5).
Secure contexts
Secure contexts only
In a secure context the server refuses the insecure carrier that send, edit, delete, reactions.add and reactions.remove post, because the content must travel inside a SealedMessage: 409 channel.plaintext_rejected in a channel and 409 sealed.required in a DM (11 §4.7). Build the secure carrier with MessagesApi.secureEntry from the content object and the sealing inputs of document 14 (K_hist, epoch, device and signer), store it in the outbox, and send it with MessagesApi.post; MessagesApi.sendSealed posts a SealedMessage you built yourself. A retry in the same epoch resends the stored bytes (11 §13.4 rule 3). Upload files with secure: true, which encrypts each one with SVF1 under its own key and puts key and sha256 in the reference (11 §14.3), and download them with downloadFile(ctx, ref, { secure: true }). See Secure messages (MLS) for the format.