This page builds a bot that answers !ping with pong in one channel. It runs on Node 22.12 or later. The last section runs the same bot against MockServer, an in-memory server that ships with the SDK, so you can try it before you have a bot account.

The steps are:

  1. Create the bot account and its token (done once, by a person).
  2. Construct a SloppyVoiceClient with the bot token.
  3. Join the community and the channel.
  4. Listen for message.created and reply.
  5. Handle errors and shut down cleanly.

Install

npm install https://developer.sloppyvoice.com/downloads/sloppyvoice-sdk-0.1.0.tgz

The SDK has no runtime dependencies. Every file on this page is an ES module with top-level await, so your package.json needs "type": "module". Node 22.18 and later run .ts files directly; on 22.12 to 22.17, run them with node --experimental-strip-types or compile them with tsc first.

Create the bot account

A bot is an account with kind: "bot" on one home server, with an address like any user (05 §15.1). It has no sign-in provider. It authenticates with bot tokens, and each bot token is one device record of the bot, so each process can have its own token and one leaked token can be revoked without stopping the others.

Only a person can create a bot. The rules (05 §15.2):

  • The caller is an active local account of kind: user holding the manage_bots permission in its home server's community. Others get 403 core.forbidden with data.permission: "manage_bots", or bot.permission_required for a caller that isn't an active local user account.
  • The caller signed in, or re-authenticated, within the last 600,000 ms (10 minutes) (05 §9.1). Otherwise the server answers 403 auth.reauth_required, and the client runs the re-authentication procedure of 05 §9.2, then retries the request once.
  • POST /v1/bots answers 201 with the Bot and its first token. The token appears in that response only; the server can't show it again.
  • More tokens come from POST /v1/bots/{local}/tokens, owner only, with the same fresh-authentication rule, up to maxBotTokens active tokens per bot (05 §15.4). A bot token is refused for every /v1/bots* endpoint with bot.not_allowed (05 §15.5), so a bot can't make more of itself.

A client with bot settings does this for the owner, who then copies the token. In code it is BotsApi.create and BotsApi.createToken on the owner's home ServerClient. The owner's client holds a signed-in home session (Sign-in, accounts and bots):

import { isSloppyVoiceError, type ServerClient } from '@sloppyvoice/sdk'
import { localPartOf } from '@sloppyvoice/sdk/address'

/** Run by the owner: a local user holding manage_bots, signed in within the last 10 minutes (05 §15.2). */
export async function createPingBot(owner: ServerClient) {
  if (!owner.isHome) throw new Error('Bots are created at the owner\'s home server')
  try {
    // POST /v1/bots: the bot, and its first token. Store the token now; it is shown only here.
    const { bot, token } = await owner.bots.create({
      name: 'Ping Bot',
      about: 'Answers !ping with pong.',
      deviceName: 'ping-bot 1',
    })
    // POST /v1/bots/{local}/tokens: one more token, for a second process.
    const second = await owner.bots.createToken(localPartOf(bot.account.address), { deviceName: 'ping-bot 2' })
    return { address: bot.account.address, tokens: [token, second.token] }
  } catch (e) {
    if (isSloppyVoiceError(e, 'auth.reauth_required')) {
      // data.maxAgeMs is 600000 here. Re-authenticate (05 §9.2) and call this again.
      throw new Error('Sign in again to confirm it is you, then retry', { cause: e })
    }
    throw e
  }
}

The SDK doesn't retry token-issuing calls after a network error, a timeout or a retryable problem, and throws sdk.invalid_argument if you pass an idempotencyKey, because the server ignores that header there and never replays a response that carries a token (05 §7.4). If a response is lost, list the bot's tokens with BotsApi.listTokens, revoke the device you don't recognise with revokeToken, and create a new token (05 §15.4). For a token that may have leaked, revoke it and create a new one rather than rotating it, because a rotation's grace period keeps the old token working for up to 24 hours.

Let the bot into the community

Bots are never made community members automatically, not even in their home server's community (09 §4.4). A bot becomes an active member only with the approval of someone holding manage_bots, in one of two ways (10 §4.4):

  1. It joins with a valid invite whose creator holds manage_bots when the bot uses it. This is the usual way: the admin creates an invite with InvitesApi.create (POST /v1/invites) and gives the code to the bot's operator.
  2. Its join creates a pending record (202), and a member holding both manage_bots and manage_invites approves it.

Without such an invite, a bot's join is pending under the join policies open and request and under invite with any other valid invite; it fails with community.invite_required under invite without a valid invite, and with community.closed under closed (09 §9.2 step C7).

The invite belongs to the community the bot joins, which is not necessarily the bot's home: a bot homed on sloppyvoice.com that should work in general@example.org needs an invite from a manage_bots holder at example.org.

Connect

The bot reads three values from its environment, and a fourth that is optional:

Variable Example Meaning
SV_BOT_TOKEN svb_QEFC… The bot token.
SV_HOME sloppyvoice.com The bot's home domain.
SV_CHANNEL general@sloppyvoice.com The channel's canonical address (document 01).
SV_INVITE 7kq2-m9xp-4hrt Optional: the invite code from the community's admin.
import { SloppyVoiceClient, botToken } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'

const sv = new SloppyVoiceClient({
  client: 'ping-bot/1.0',
  home: process.env.SV_HOME!,
  auth: botToken(process.env.SV_BOT_TOKEN!),
  txt: nodeTxtResolver(),
})
const home = await sv.home()
const me = await home.me.get()
console.log(`Signed in as ${me.account.address} (${me.account.kind})`)

What each option does:

  • client is the product and version, 1 to 128 printable ASCII characters. It is sent in session.hello (03 §5.4) and as the User-Agent product.
  • auth: botToken(…) sends the token as Authorization: Bot <token> (03 §3.1). The SDK sends it only to the bot's home server, because a token goes only to the server that issued it (03 §3.2 rule 3). botTokenProvider does the same and also checks the token's svb_ format first.
  • txt: nodeTxtResolver() from @sloppyvoice/sdk/node looks up _sloppyv TXT records with Node's DNS resolver, which native discovery needs to find each server's base URL (02 §5.2, Discovery).

Nothing is sent until the first call. SloppyVoiceClient.home resolves the home domain, checks its metadata and returns a ServerClient with every resource API. me.get() is GET /v1/me; it is a cheap way to check the token at start-up.

For a channel on another server, SloppyVoiceClient.serverFor resolves that server and returns its client, which creates a remote session there silently the first time a request needs one: the home server signs a HomeAssertion for the bot, and the other server exchanges it for a session token of its own (06 §4, 06 §6.10). The bot token never leaves the home server. For a channel on the home server, serverFor returns the home client.

Join the community and the channel

import type { ServerClient } from '@sloppyvoice/sdk'

declare const server: ServerClient // from sv.serverFor(channelAddress)
declare const channelAddress: string
declare const invite: string | undefined

// POST /v1/community/join: 200 when the bot is a member, 202 when it waits for approval (09 §4.3).
const joined = await server.community.join(invite ? { invite } : {})
if (joined.status === 202) throw new Error('Waiting for a manage_bots holder to approve the bot (09 §4.4)')

// GET /v1/channels: every channel the bot can view; then POST /v1/channels/{id}/join.
const channel = (await server.channels.list()).items.find((c) => c.address === channelAddress)
if (!channel) throw new Error(`No channel ${channelAddress} that this bot can view`)
await server.channels.join(channel.ctx)
console.log(`Joined ${channel.name} (${channel.ctx})`)

CommunityApi.join and ChannelsApi.join are both idempotent, so the bot calls them on every start. Joining an already-joined community returns 200 and doesn't use up the invite (09 §4.3).

A community join can fail with a gate error instead (09 §9.2), such as community.invite_required or community.closed from the bot rules above, or community.rules_acceptance_required when the community requires its rules to be accepted: its data.rulesVersion is the value to send back as acceptRules in the next join, which also applies to a bot (09 §4.3). Posting in a channel the bot isn't a member of fails with channel.join_required (09 §9.3 H8), which is why the bot joins the channel before it listens; a client that gets it later joins the channel again and resends (09 §9.5).

The channel's ctx (ch:<UUIDv7>) is the stream name for events and the path parameter for messages. Keep it; the address can change when the channel is renamed, the ctx can't.

Listen and reply

import { isWithheldPayload, type ChannelRef, type ServerClient } from '@sloppyvoice/sdk'

declare const server: ServerClient
declare const ctx: ChannelRef // channel.ctx, `ch:<UUIDv7>`
declare const me: string  // the bot's own canonical address

const events = server.events({ subscribe: [ctx] })
events.on('message.created', (e) => {
  if (e.ctx !== ctx || isWithheldPayload(e.d)) return
  const { mid, sender, content } = e.d
  // Never answer yourself or a webhook (no addr), and only answer !ping.
  if (!sender.addr || sender.addr === me || content?.text.trim() !== '!ping') return
  server.messages.send(ctx, 'pong', { replyTo: { mid, author: sender.addr } }).catch((err) => console.error(err))
})
await events.connect()

How it works:

  • ServerClient.events returns the server's EventSocket. There is at most one socket per client session per server (03 §5.12), so later calls return the same socket and ignore their options. subscribe lists the streams to follow at level full; the me stream is always followed.
  • One bot token is one client session, so run one process per token: a second socket opened with the same token replaces the first, which the server closes with 4010 (03 §5.12, 05 §15.7).
  • connect() opens {base}/v1/events, sends session.hello with the bot token and resolves at session.ready (03 §5.4, Event WebSocket). After that the socket reconnects and resumes from its last position by itself (03 §5.11).
  • on('message.created', …) is typed by the SDK's event map: e.d is the Message without ctx and seq (11 §8.1), and e.ctx and e.seq are on the envelope. Durable events reach the listener at most once each, in seq order per stream.
  • The socket already drops events in the withheld form {"withheld": true}, which carry no content (03 §7.2 D4a). The event map still types e.d as the Message or that form, so the isWithheldPayload check narrows the type before the code reads sender and content.
  • The bot's own replies arrive as message.created too, so it checks sender.addr === me to avoid answering itself.
  • MessagesApi.send turns the text into a MessageContent, validates it against 11 §3 and posts it to POST /v1/contexts/{ctx}/messages. replyTo makes it a reply (11 §3.5).

Listeners are synchronous, so the listener catches the promise of send itself; an uncaught rejection would end the Node process.

Bots have their own rate limits on top of the per-session ones, applied per bot account across all its tokens: by default 50 requests per second (burst 100), and 5 messages per second per context and 30 per second in total (05 §15.7). A bot that replies to every message in a busy channel can reach them, and then gets core.rate_limited.

Handle errors

Every non-2xx response becomes a SloppyVoiceError carrying the server's problem object (03 §10): code, status, title, detail, retryable, retryAfterMs, userAction and data. A failure with no response (DNS, TCP, TLS, timeout) is a SloppyVoiceNetworkError, a subclass with code sdk.network_error. A check the SDK makes before sending (an invalid argument, a closed client) throws a SloppyVoiceError too, with an sdk.* code and status 0. Test for a code with isSloppyVoiceError:

import { isSloppyVoiceError } from '@sloppyvoice/sdk'

export function report(err: unknown): void {
  if (isSloppyVoiceError(err, 'core.rate_limited')) {
    console.warn(`Rate limited; the server asks for ${err.retryAfterMs ?? '?'} ms`)
  } else if (isSloppyVoiceError(err, 'channel.join_required')) {
    console.warn('Not a channel member: join the channel again and resend (09 §9.5)')
  } else if (isSloppyVoiceError(err, ['core.forbidden', 'member.not_member', 'moderation.banned'])) {
    console.error(`Not allowed here: ${err.code}`)
  } else if (isSloppyVoiceError(err)) {
    console.error(`${err.code} (${err.status}): ${err.detail ?? err.title}`)
  } else {
    console.error(err)
  }
}

The SDK already retries what may be retried:

  • It retries network errors, timeouts, problems with retryable: true such as core.rate_limited, and bare 429, 502, 503 and 504 responses, but only for idempotent requests, at most 5 attempts in all, with full-jitter backoff that never waits less than Retry-After (03 §2.7, 03 §15). A non-idempotent request is never retried after a failure that may have reached the server.
  • Every call this bot makes is idempotent: community.join and channels.join by their definition (09 §4.3, 09 §4.5), and messages.send because every message carries a client-generated mid, so a retry after a lost response can't post twice (11 §4.6). A rejection of one of them comes after those retries.

Authentication failures are different for bots. A bot token has no refresh token, so when the home server answers 401 core.unauthenticated there is nothing to recover: the token was revoked or rotated, and the bot stops and reports it to its operator (03 §3.3). On another server, the SDK first recreates the remote session silently from the bot token, and the failure is final only when the home server refuses the token too. The event socket does the same. It stops reconnecting and emits stopped on its lifecycle emitter with a reason such as unauthenticated, session_ended or update_required (03 §5.10):

import type { EventSocket, EventMap } from '@sloppyvoice/sdk'

declare const events: EventSocket<EventMap>
declare function shutdown(exitCode: number): Promise<void>

events.lifecycle.on('stopped', ({ reason, problem }) => {
  console.error(`Event socket stopped: ${reason}${problem ? ` (${problem.code})` : ''}`)
  void shutdown(1)
})
events.lifecycle.on('reconnecting', ({ reconnecting }) => {
  if (reconnecting) console.warn('Reconnecting…')
})

A rejection of connect() means the socket stopped, or was closed, before it was ready.

Shut down cleanly

SloppyVoiceClient.close closes every event socket with code 1000, stops the remote-session renewal timers and the discovery timers (03 §5.3). It doesn't end sessions at the servers, so the bot token keeps working for the next start.

import type { SloppyVoiceClient } from '@sloppyvoice/sdk'

declare const sv: SloppyVoiceClient

let stopping = false
async function shutdown(exitCode = 0): Promise<void> {
  if (stopping) return
  stopping = true
  await sv.close()
  process.exitCode = exitCode
}
process.once('SIGINT', () => void shutdown())
process.once('SIGTERM', () => void shutdown())

When every socket and timer is closed, Node has nothing left to wait for and exits by itself with process.exitCode.

The whole bot

Save this as ping-bot.ts, set the variables from Connect, and run node ping-bot.ts (Node 22.18 or later; see Install):

import { SloppyVoiceClient, botToken, isSloppyVoiceError, isWithheldPayload } from '@sloppyvoice/sdk'
import { nodeTxtResolver } from '@sloppyvoice/sdk/node'

/** Join the channel at `channelAddress` and answer !ping with pong. Resolves once the bot is listening. */
export async function startPingBot(sv: SloppyVoiceClient, channelAddress: string, invite?: string) {
  const me = (await (await sv.home()).me.get()).account.address
  const server = await sv.serverFor(channelAddress)

  const joined = await server.community.join(invite ? { invite } : {})
  if (joined.status === 202) throw new Error('Waiting for a manage_bots holder to approve the bot (09 §4.4)')
  const channel = (await server.channels.list()).items.find((c) => c.address === channelAddress)
  if (!channel) throw new Error(`No channel ${channelAddress} that this bot can view`)
  const ctx = channel.ctx
  await server.channels.join(ctx)

  const events = server.events({ subscribe: [ctx] })
  events.on('message.created', (e) => {
    if (e.ctx !== ctx || isWithheldPayload(e.d)) return
    const { mid, sender, content } = e.d
    if (!sender.addr || sender.addr === me || content?.text.trim() !== '!ping') return
    server.messages.send(ctx, 'pong', { replyTo: { mid, author: sender.addr } }).catch(report)
  })
  await events.connect()
  return { me, server, ctx, events }
}

function report(err: unknown): void {
  if (isSloppyVoiceError(err)) console.error(`${err.code} (${err.status}): ${err.detail ?? err.title}`)
  else console.error(err)
}

const { SV_BOT_TOKEN, SV_HOME, SV_CHANNEL, SV_INVITE } = process.env
if (!SV_BOT_TOKEN || !SV_HOME || !SV_CHANNEL) throw new Error('Set SV_BOT_TOKEN, SV_HOME and SV_CHANNEL')

const sv = new SloppyVoiceClient({
  client: 'ping-bot/1.0',
  home: SV_HOME,
  auth: botToken(SV_BOT_TOKEN),
  txt: nodeTxtResolver(),
})

let stopping = false
async function shutdown(exitCode = 0): Promise<void> {
  if (stopping) return
  stopping = true
  await sv.close()
  process.exitCode = exitCode
}
process.once('SIGINT', () => void shutdown())
process.once('SIGTERM', () => void shutdown())

try {
  const { me, events } = await startPingBot(sv, SV_CHANNEL, SV_INVITE)
  events.lifecycle.on('stopped', ({ reason }) => {
    console.error(`Event socket stopped: ${reason}`)
    void shutdown(1)
  })
  console.log(`${me} is answering !ping in ${SV_CHANNEL}`)
} catch (err) {
  report(err)
  await shutdown(1)
}

Run it against MockServer

MockServer, from @sloppyvoice/sdk/testing, is an in-memory server for insecure-mode flows. It serves discovery, the HTTP API and the event WebSocket through its own fetch, WebSocket and TXT resolver, so the SDK's real client runs against it unchanged. This program starts a server, creates the accounts and channel with its test controls, runs startPingBot from above unchanged, sends !ping from a second client signed in as a user, and waits for the reply. Save it as ping-bot-mock.ts and run node ping-bot-mock.ts:

import { SloppyVoiceClient, botToken, isSloppyVoiceError, isWithheldPayload, staticToken, type TokenProvider } from '@sloppyvoice/sdk'
import { MockServer } from '@sloppyvoice/sdk/testing'

// The same function as in "The whole bot".
async function startPingBot(sv: SloppyVoiceClient, channelAddress: string, invite?: string) {
  const me = (await (await sv.home()).me.get()).account.address
  const server = await sv.serverFor(channelAddress)

  const joined = await server.community.join(invite ? { invite } : {})
  if (joined.status === 202) throw new Error('Waiting for a manage_bots holder to approve the bot (09 §4.4)')
  const channel = (await server.channels.list()).items.find((c) => c.address === channelAddress)
  if (!channel) throw new Error(`No channel ${channelAddress} that this bot can view`)
  const ctx = channel.ctx
  await server.channels.join(ctx)

  const events = server.events({ subscribe: [ctx] })
  events.on('message.created', (e) => {
    if (e.ctx !== ctx || isWithheldPayload(e.d)) return
    const { mid, sender, content } = e.d
    if (!sender.addr || sender.addr === me || content?.text.trim() !== '!ping') return
    server.messages.send(ctx, 'pong', { replyTo: { mid, author: sender.addr } }).catch(report)
  })
  await events.connect()
  return { me, server, ctx, events }
}

function report(err: unknown): void {
  if (isSloppyVoiceError(err)) console.error(`${err.code} (${err.status}): ${err.detail ?? err.title}`)
  else console.error(err)
}

// A server for alpha.test. The first account created holds every permission.
const mock = await MockServer.create({ domain: 'alpha.test', pingIntervalMs: null })
const alice = mock.createUser({ local: 'alice', name: 'Alice' })
const bot = mock.createBot({ local: 'pingbot', name: 'Ping Bot' })
const general = mock.createChannel('General') // general@alpha.test

// Point a client at the mock: its fetch, WebSocket and TXT resolver replace the network.
function mockClient(name: string, auth: TokenProvider) {
  return new SloppyVoiceClient({
    client: name,
    home: 'alpha.test',
    auth,
    fetch: mock.fetch,
    WebSocket: mock.WebSocket,
    txt: mock.txt,
    allowSpecialUseDomains: true, // .test is a special-use domain (02 §5.1); never set this in production
  })
}
const sv = mockClient('ping-bot/1.0', botToken(bot.token))
const aliceSv = mockClient('quickstart-user/1.0', staticToken(alice.token)) // Alice's access token, Bearer

try {
  const { me, ctx, events } = await startPingBot(sv, general.address)
  console.log(`${me} is listening in ${general.address}`)

  // Wait for the bot's own reply, which arrives on its socket like any message.
  const reply = new Promise<string>((resolve) => {
    events.on('message.created', (e) => {
      if (!isWithheldPayload(e.d) && e.d.sender.addr === me) resolve(e.d.content?.text ?? '')
    })
  })

  // Alice opens the channel and sends !ping.
  const aliceHome = await aliceSv.home()
  await aliceHome.channels.join(ctx)
  await aliceHome.messages.send(ctx, '!ping')
  console.log(`${alice.address}: !ping`)
  console.log(`${me}: ${await reply}`)
} catch (err) {
  report(err)
  process.exitCode = 1
} finally {
  await aliceSv.close()
  await sv.close()
  mock.close()
}

Expected output:

pingbot@alpha.test is listening in general@alpha.test
alice@alpha.test: !ping
pingbot@alpha.test: pong

The mock differs from a real server in ways that matter here:

  • createBot and createUser are test controls: the mock doesn't implement /v1/bots, sign-in or roles. Its first account holds every permission; the others hold the defaults.
  • The mock makes every local account a community member, bots included, so community.join answers 200 at once without an invite. A real server never admits a bot without a manage_bots holder's approval (09 §4.4).
  • pingIntervalMs: null turns off the server's session.ping timer so the process can exit; a real server pings every 30 s (03 §5.9).

To test failure handling, MockServer.failNext makes the next matching requests fail with any registered error code. endSession(bot.token) closes the bot's socket with 4004, and the socket stops with session_ended. revokeToken(bot.token) makes later requests and session.hello messages with the token fail with core.unauthenticated but leaves an open socket alone; after disconnectAll(1012, { reason: 'server_shutdown', reconnect: true, retryAfterMs: 0 }) the socket reconnects at once, is refused, and stops with unauthenticated. The MockServer reference lists what else it implements.