Channels
Record Slack, WhatsApp, Messenger and SMS conversations in the inbox with Chat SDK adapters, deliver staff replies on their channel and keep the event store clean.
These helpers in better-supabase/chat-sdk put conversations from a
Chat SDK platform adapter into the inbox, and post
staff replies back on the same platform. All of them take createInbox on
a service transport.
Installations
createChatInstallations records which workspace or number an adapter is
installed on, per organization. The token stays in the
credential provider; the row only keeps its
credential_ref.
import {
createChatInstallations,
sqlTransport,
} from "better-supabase/chat-sdk";
export const installations = createChatInstallations({
transport: sqlTransport(postgres.asService()),
credentials,
});
await installations
.install({
adapter: "slack",
externalId: teamId,
tenant: organizationId,
credentialRef,
})
.orThrow();A reinstall revokes the credential it replaces, uninstall(adapter, externalId)
revokes the current one, and uninstallTenant(tenant) removes every live
install of an organization before it is deleted. get and list read
them back. Organization exports leave out credential_ref, and the
organization purge keeps the
installation rows and doesn't revoke them, so call uninstallTenant first.
Building an adapter with its token
channelAdapter asks the credential provider for the install's token and
hands it to the adapter factory. The first read fails fast when the install
has no credential. The factory also gets resolve, which reads the token
again on each call; pass it where the adapter takes a token function, so a
token that Vercel Connect rotates is never stale:
import { createSlackAdapter } from "@chat-adapter/slack";
import { channelAdapter } from "better-supabase/chat-sdk";
const install = await installations.get("slack", teamId).orThrow();
const slack = await channelAdapter({
credentials,
ref: install.credentialRef,
create: (_token, resolve) => createSlackAdapter({ botToken: resolve }),
});Receiving webhooks
webhook() returns a route handler that verifies the request, stores the
raw event in the inbox's event table and answers 200 at once. Platforms
retry slow endpoints, so the processing happens afterwards:
import { after } from "next/server";
import { webhook } from "better-supabase/chat-sdk";
import { handler, inbox } from "@/lib/chat";
export const POST = webhook({
inbox,
adapter: "whatsapp",
verify: (request, body) => verifyMetaSignature(request, body),
externalId: (body) => JSON.parse(body).entry?.[0]?.id,
after: () => after(() => handler.drain()),
});
export const GET = POST;| Option | Meaning |
|---|---|
adapter | The adapter name the event is replayed into |
credentials and ref | Verify the request with credentials.verifyInbound before storing it |
verify | Verifies the request when no credential ref does |
externalId | The platform's event id, so a retried delivery is stored once |
passthrough, passthroughHandler | Requests answered synchronously, by default GET and Slack's url_verification |
after | Runs after the event is stored |
Without credentials or verify, every request is stored, so set one in
production.
Replaying events into Chat SDK
inboundHandler replays stored events into your Chat instance and
records channel messages in the inbox:
import { inboundHandler } from "better-supabase/chat-sdk";
export const handler = inboundHandler({
chat: bot,
inbox,
inboxes: { whatsapp: whatsappInboxId, slack: slackInboxId },
});
bot.onNewMessage(/.*/, async (thread, message) => {
await handler.mirror(thread, message);
});drain({ limit, maxAttempts }) processes pending events oldest first and
returns { processed, failed }. Delivery status callbacks from WhatsApp,
Messenger, Instagram and Twilio update the matching delivery instead of
reaching Chat SDK; pass parsers to add more. mirror finds or opens the
conversation for the thread, upserts the contact from the message's author
and skips the bot's own messages (author.isMe) and the echoes of replies
deliver posted. Other bots' messages, such as a CI integration posting in
the channel, are recorded.
A replay runs the adapter's own request check again, so an adapter that
rejects old signatures (Slack's five-minute window, or a Vercel Connect
webhookVerifier) fails events older than that window. Drain within it, or
let webhook verify the request and give the adapter a check that accepts
the replay. By default a handler that throws is logged by Chat SDK and the
event counts as processed; pass propagateHandlerErrors: true to fail the
event so drain replays it.
Each file on a channel message becomes a pending attachment on the
message. Platform file URLs usually need the bot's token, so pass
copyFile to return a source the service can read (a signed URL, or a
Storage path you already wrote); without it only files with a public URL
are kept.
importFiles({ write, read, limit }) fetches the pending files, oldest
first, writes each with write to the bucket and path the attachments
block chose, and confirms it so the scan can mark it clean. A file that
can't be read or written is marked failed. Run it from a cron route or a
job after drain:
export async function GET() {
return Response.json(
await handler.importFiles({
write: async (file, data) => {
const { error } = await admin.storage
.from(file.bucket)
.upload(file.path, data, { contentType: file.mimeType });
if (error) {
throw error;
}
},
}),
);
}read defaults to fetching file.source.url; pass it for sources with
only a path, such as the files the upgrade moved from inbox-files.
Receive now, process later
chatWebhookPipeline splits the webhook into two steps so a slow or failing
bot never makes the platform retry the delivery. receive is the route
handler: a handler-less Chat instance on its own state prefix verifies the
request, the sink stores it, and the platform gets its answer. process
replays a stored event from a queue job with deduplicate: false and
propagateHandlerErrors: true, so a handler error fails the job and the
queue retries it.
import { chatWebhookPipeline } from "better-supabase/chat-sdk";
export const pipeline = chatWebhookPipeline({
chat: bot,
receiveChat: receiver,
adapter: "slack",
inbox,
inboxes: { slack: inboxId },
retry: () => ({ retryIn: "1 minute" }),
});
export const POST = pipeline.receive;receiver is a second Chat with the same adapters and no handlers. Give
each Chat its own keyPrefix (chat-sdk and chat-sdk:receive): the
pipeline throws a TypeError when the prefixes or the state objects match,
because the receiver would then mark the event as seen and process would
skip it. retry(error, event) may return { retryIn }; a queue handler
that returns it makes the webhook inbox fail the job and run it again after
that delay.
inboundHandler takes deduplicate: "first-attempt" (the default) lets
Chat SDK drop duplicates on the first attempt only, "always" on every
attempt and "never" on none. ChatInboundEvent.attempt counts the replay
(1 for the first), and the inbound store leases an event while it is
processing, so a crashed worker's event returns after its lease expires.
WhatsApp windows, templates and replies
sendWithinWindowOrTemplate(thread, message, { inbox, conversationId, template }) posts the message while the 24-hour window is open and sends the
template ({ name, language, components }) through the adapter's
sendTemplate once it has closed. Without a template, or when the adapter
has no sendTemplate, it throws a ChatWindowClosedError with the code
CHAT_WINDOW_CLOSED. The window reads last_inbound_at on the
conversation, which each recorded inbound message sets.
whatsappInteractiveOf(payload) lists the button replies, list replies and
template quick replies in a WhatsApp webhook body. Pass onAction (and
actions: chatActions(...)) to inboundHandler and each reply runs through
the same authorization as a Chat SDK action; a body that holds nothing but
replies is not replayed. Deliveries record delivered_at, read_at and
failed_at, and a read message stays read when a late delivered arrives.
Delivering staff replies
A staff reply on a channel inbox queues an inbox_outbound job.
deliver() posts it with the conversation's adapter, records the delivery
with the platform's message id and throws on failure, so the job retries.
When the platform rate-limits the post (a Chat SDK RateLimitError or an
adapter's AdapterRateLimitError), deliver waits the retryAfter it
asks for and tries again, up to rateLimitRetries times (2) and for waits
of at most maxRetryWaitMs (10 seconds):
import { deliver, whatsappWindowOpen } from "better-supabase/chat-sdk";
const send = deliver({
chat: bot,
inbox,
template: async ({ conversation }) =>
conversation.inbox?.channel === "whatsapp" &&
!(await whatsappWindowOpen(inbox, conversation.id))
? { markdown: "We replied to your question. Answer here to continue." }
: null,
});
export const GET = jobs.drainRoute({
secret: process.env.CRON_SECRET,
handlers: { inbox_outbound: (payload) => send(payload) },
});template replaces the message when the channel's reply window is closed,
such as WhatsApp's 24 hours after the contact's last message. The adapter
defaults to the inbox's channel (sms posts with twilio); adapterFor
picks another.
Maintenance
maintain runs the periodic work: it reopens snoozed conversations whose
time came, sends the staff replies scheduled for now, replays events a
crashed request left pending, deletes processed events after keepEvents
(7 days by default) and purges expired state. With
scheduled: { chat, scheduler } it also posts the bot's
scheduled messages that are due and reports
them as posted.
import { maintain } from "better-supabase/chat-sdk";
export async function GET() {
return Response.json(await maintain({ inbox, handler, state }));
}Protect the route with your cron secret like the jobs drain route.
Last updated on
Scheduled messages
stateScheduler and scheduledAdapter, so thread.schedule() works on any Chat SDK adapter, with the messages held in your state adapter until a cron job posts them.
Identities
Run bot jobs as the chat author's linked user, decide approval buttons through the authorization provider, and link approval prompts to the app.