The TypeScript SDK
Node 24 or newer, ES modules, no runtime dependencies. Generated from bot-sdk-js v3.5.0 (88d52692e249).
The official TypeScript SDK for Mnema Talk bots: the REST API with its rate limits, the gateway with heartbeats, resume and reconnects, slash commands, interactions, message components, modals and the add link.
- Node 24 or newer, ES modules, no runtime dependencies (Node's
fetch,WebSocket,FormDataandBlob). - Types for every wire object; builders return the plain JSON of the bot API, and plain objects work wherever builders do.
- Tested on every change against a real Mnema Talk server (contract tests).
- Published from CI with npm provenance, so npm shows which commit and workflow built each version.
Docs: developer guide · quick start · SDK reference · bot platform reference · Mnemo, a complete bot built on it
Install
npm install @mnema-xyz/bot-sdk
Moving from the mnema-talk-sdk-X.Y.Z.tgz tarball that Mnema Talk's releases
up to 3.1.1 carried: replace the dependency "mnema-talk-sdk": "<tarball URL>"
with "@mnema-xyz/bot-sdk": "^3.1.1" and the imports from 'mnema-talk-sdk'
with '@mnema-xyz/bot-sdk'. The API is the same.
Quick start
Create the bot and its token first (Getting started).
import { Client, Intents, actionRow, button, ButtonStyle } from '@mnema-xyz/bot-sdk'
const bot = new Client({
baseUrl: 'https://talk.example.org',
token: process.env.MNEMA_TOKEN!,
intents: Intents.GuildMessages,
})
bot.on('messageCreate', async (m) => {
if (m.content === '!ping') {
await bot.rest.createMessage(m.channel_id, {
content: 'pong',
components: [actionRow(button({ customId: 'again', label: 'Again', style: ButtonStyle.Primary }))],
})
}
})
bot.on('interactionCreate', async (i) => {
if (i.isButton() && i.customId === 'again') await i.update({ content: 'pong again' })
})
bot.on('error', (err) => console.error(err))
await bot.connect()
connect() checks the token (GET /users/@me), asks GET /gateway for the
gateway address (or derives wss://…/api/bot/v1/gateway from baseUrl),
identifies and resolves with READY; client.user is the bot from it.
client.close() closes the gateway for good and leaves no timers behind.
Examples
examples/ has three bots; each reads MNEMA_URL and
MNEMA_TOKEN:
npm install && npm run build
MNEMA_URL=https://talk.example.org MNEMA_TOKEN=mnb_... node examples/echo.ts
| File | Shows |
|---|---|
echo.ts | MESSAGE_CREATE, replying to !echo <text> |
slash.ts | registering /ping and /roll with options and choices, reply, deferReply + editReply, ephemeral answers |
buttons.ts | buttons, a link button, a select, update(), a modal with showModal() and its submit |
manifest.json | the manifest of the slash command bot |
Configuration
new Client({ baseUrl, token, intents, presence?, logger?, rest?, gateway? })
intents: the sum ofIntents.Guilds(1),Intents.GuildMembers(2),Intents.GuildMessages(512),Intents.GuildMessageReactions(1024), or a list of them. Interactions need none. Asking for more than the admin allowed closes with4014.presence:{ status: 'online' | 'idle' | 'dnd' | 'invisible', activity?: { name, type } }, sent in IDENTIFY.client.setPresence(...)changes it later (op 3, at most 5 a minute, extra ones dropped by the server). Activity types areActivityType.Playing(0),Listening(2),Watching(3),Custom(4),Competing(5).logger: anything withdebug,info,warn,error(for exampleconsole).rest:timeoutMs,maxRetries,localRateLimits,onRateLimit,fetch.gateway:url(a fixed address),reconnect,resumeWindowMs,webSocketFactory.
Events
client.on(event, listener), client.once(...), client.off(...); the
listener types follow the event. A listener that throws or rejects is reported
on error.
| Event | Arguments | Dispatch | Intent |
|---|---|---|---|
ready | Ready (user, session_id, intents, ...) | READY | |
resumed | RESUMED | ||
messageCreate | Message | MESSAGE_CREATE (also the bot's own messages) | GuildMessages |
messageUpdate | Message | MESSAGE_UPDATE | GuildMessages |
messageDelete | { id, channel_id, parent_id } | MESSAGE_DELETE | GuildMessages |
reactionsUpdate | { message_id, channel_id, reactions } | MESSAGE_REACTIONS_UPDATE | GuildMessageReactions |
channelsUpdate | CHANNELS_UPDATE: fetch rest.listChannels() again | Guilds | |
memberAdd | { id, username, display_name, avatar_url } | GUILD_MEMBER_ADD | GuildMembers |
interactionCreate | Interaction | INTERACTION_CREATE | none |
raw | name, data, seq | every dispatch | |
close | { code, reason, reconnect } | the gateway connection closed | |
error | Error | fatal close codes (GatewayError), failing listeners, protocol errors | |
debug | string | connection steps |
REST
client.rest (or new RestClient({ baseUrl, token }) on its own):
| Method | Route |
|---|---|
getMe() | GET /users/@me |
getGateway() | GET /gateway |
listChannels() | GET /channels |
listMessages(channelId, { limit, before, after, around }) | GET /channels/{id}/messages |
getMessage(channelId, messageId) | GET /channels/{id}/messages/{id} |
createMessage(channelId, { content, embeds, components, allowed_mentions, message_reference, parent_id, lifetime_seconds }) | POST /channels/{id}/messages |
editMessage(channelId, messageId, { content?, components? }) | PATCH /channels/{id}/messages/{id} |
deleteMessage(channelId, messageId) | DELETE /channels/{id}/messages/{id} |
addReaction(channelId, messageId, emoji), removeReaction(...) | PUT, DELETE .../reactions/{emoji}/@me |
uploadFile(channelId, { file: Blob | Buffer, name, content?, contentType?, allowed_mentions?, parent_id?, reply_to_id? }) | POST /channels/{id}/upload |
downloadAttachment(id, { maxBytes?, signal?, timeoutMs? }) | GET /media/{id} |
listMembers(), getMember(userId) | GET /members, GET /members/{id} |
listCommands(), setCommands(list), createCommand(cmd), deleteCommand(id) | /commands |
request(method, path, { query, body, form, signal }) | any route under /api/bot/v1 |
lifetime_seconds (60 to 2,592,000, at most the community's ceiling) makes the
server delete the message that long after it is stored; such a message carries
expires_at (RFC 3339) in the answer, in messageCreate and on reads, which
leave it out once that has passed. The server answers 400 when lifetimes are
off or the value is out of bounds
(timed messages).
createMessage and editMessage also take a string (the content). An error
answer throws a RestError with status, code (the bot API's JSON error code, for
example 10003 unknown channel, 50013 missing permissions), message (the
server's), body, method and path. In path, in onRateLimit's info
and in the client's logs an interaction or webhook token is replaced by
:token (for example /interactions/<id>/:token/callback). Redirects are
not followed: a 3xx answer throws a RestError with its status, so the
bot token goes to baseUrl only. A request that gets no answer throws a
RequestFailedError with method, path and the underlying message, the
token replaced there too (cause is kept only on routes without a token);
aborts and timeouts are thrown as they are. The client reads at most 16 MiB
of a JSON or error answer (the same bound as the Go SDK); a larger one is
cancelled and throws ResponseTooLargeError with status and maxBytes.
Downloading attachments
const { contentType, size, filename, stream } = await client.rest.downloadAttachment(attachment.id, {
maxBytes: 10 * 1024 * 1024,
})
downloadAttachment streams a message attachment by its id without following redirects:
- Returns
{ contentType, size, filename, stream }, wherestreamis aReadableStream<Uint8Array>. maxBytes: aborts and throwsMaxBytesExceededErrorif the server'sContent-Lengthheader or the bytes read while streaming exceed the limit.timeoutMs: request timeout in milliseconds (defaults torest.timeoutMs, 15 s).signal: optionalAbortSignalto cancel the download.- Throws
NotFoundError(status 404) when the attachment does not exist, the message was deleted/expired, or the bot lacks permission to view the channel/DM.
Slash commands
await client.commands.set([ // PUT /commands: replaces them all
{ name: 'roll', description: 'Rolls a die',
options: [{ name: 'sides', description: 'How many sides', type: OptionType.Integer, required: true }] },
{ name: 'ban', description: 'Bans a member',
default_member_permissions: ['ban_members'] }, // or Permissions.BanMembers / "524288"
])
await client.commands.create(cmd) // POST: adds or updates by name
await client.commands.list()
await client.commands.delete(id)
Names are 1 to 32 lowercase letters, digits, - or _; at most 50 commands,
10 options each, required options first, string options may list up to 25
choices. The SDK checks this before sending.
Command permissions (default_member_permissions)
A command can restrict who can see and run it in a channel with default_member_permissions:
nullor omitted: available to everyone who can use commands in the channel."0"or[]: available to nobody except the Owner and members with Administrator.- An array of permission keys (e.g.
['ban_members']), a decimal bitfield string (e.g."524288"), orPermissionsbitwise flags (e.g.Permissions.BanMembers).
[!WARNING] Mnema's permission bits have their own values: bit constants from other chat libraries do not match them. Use
Permissionsfrom this SDK, pass permission keys (e.g.['administrator']), or compute the bits from Mnema's catalogue (GET /api/permissions).
Interactions
interactionCreate gives an Interaction:
| Field | Notes |
|---|---|
id, token, type (2 command, 3 component, 5 modal submit), channelId, user, member | always |
commandName, commandId, options (Map<string, string | number | boolean>) | commands |
customId, componentType, values (string[]), resolved, message | components |
customId, fields (Map<string, string>), message (when opened from a component) | modal submits |
raw | the payload as it arrived |
isCommand(), isComponent(), isButton(), isSelect(), isModalSubmit()
tell them apart. i.member.permissions holds the member's channel permissions
as a decimal bitfield string (e.g. "6"). i.hasPermission(Permissions.ManageMessages)
checks whether the member has that permission (or Administrator). Answer within 15 minutes:
| Method | Callback | For |
|---|---|---|
reply({ content, embeds, components, allowed_mentions?, ephemeral? }) | 4 | all |
deferReply({ ephemeral? }) | 5, then editReply | all |
update({ content?, embeds?, components?, allowed_mentions? }) | 7 | components (and modal submits from one) |
deferUpdate() | 6 | components |
showModal(modal(...)) | 9 | commands and components |
editReply({ content?, embeds?, components?, allowed_mentions? }), deleteReply() | PATCH, DELETE .../messages/@original | after the first answer |
followUp({ content, embeds, components, allowed_mentions?, ephemeral? }) | POST .../followups (up to 5 responses in total) | after the first answer |
ephemeral: true sets flags 64: only the member who caused the
interaction sees it, and it is never stored. It belongs to reply,
deferReply and followUp; editReply and update take no ephemeral
(the first response decides, and the server refuses flags on an edit).
allowed_mentions works as on createMessage: without it an answer notifies
the members it names, never @all, @here or a role. i.user is always
set: the server sends the member with every interaction. client.user.handle
(from READY) is the name members mention the bot by (@bot-...);
client.user.username is its display name.
Components and modals
import { actionRow, button, linkButton, stringSelect, userSelect, roleSelect, channelSelect,
modal, textInput, ButtonStyle, TextInputStyle } from '@mnema-xyz/bot-sdk'
const rows = [
actionRow(
button({ customId: 'deploy:v2.4', label: 'Deploy', style: ButtonStyle.Success }),
button({ customId: 'cancel', label: 'Cancel', style: ButtonStyle.Secondary }),
linkButton({ url: 'https://talk.example.org/changes', label: 'Changelog' }),
),
actionRow(stringSelect({ customId: 'env', placeholder: 'Environment',
options: [{ label: 'Staging', value: 'staging' }, { label: 'Production', value: 'prod' }] })),
]
const form = modal({ customId: 'feedback', title: 'Feedback', components: [
textInput({ customId: 'subject', label: 'Subject', maxLength: 80 }),
textInput({ customId: 'body', label: 'What happened?', style: TextInputStyle.Paragraph, required: false }),
] })
The builders check the documented limits and throw a ValidationError at
once: custom_id 1 to 100 characters and unique in a message, 5 buttons or
one select per row, 5 rows, 25 components, button labels up to 80, select
options 1 to 25 (labels and values up to 100, values unique), placeholders
up to 150, min_values 0 to 25 and max_values 1 to 25; a modal has a title
up to 45 and 1 to 5 text inputs (labels up to 45, lengths 0 to 4000). The
same checks run on plain objects passed to createMessage, editMessage
and the interaction answers. The full rules are in
Message components and
Modals.
Rate limits
- REST. The server allows 50 requests per second per bot and 5 messages
per 5 seconds per channel (posts and uploads). The client holds requests
back before they would be refused (
localRateLimits: falseturns that off) and keeps a bucket per route, with the channel id as its major part. A429pauses its bucket (or, withglobal: true, every request) forretry_afterseconds (theRetry-Afterheader when the body has none) and sends the request again, up tomaxRetries(3) times; then it throws aRestErrorwithretryAfterandglobal.onRateLimitis told about every 429. Slow mode answers 429 the same way. Each attempt times out aftertimeoutMs(15 s); passsignaltorequestto cancel. - Gateway. Frames from the bot are at most 4096 bytes (a bigger one throws
FrameTooLargeError) and 120 a minute per connection: ordinary frames wait in a queue past 115, keeping room for heartbeats.
Reconnects
- Heartbeats at the interval from HELLO, the first after a random part of it.
A heartbeat without an ACK by the next one drops the connection (close code
4900, the SDK's own) and reconnects. - After a drop the SDK opens a new connection and sends RESUME with the
session_idand the lastseqwhile it is within the server's 2-minute window (resumeWindowMs, 110 s by default); the server replays what was missed and sendsRESUMED. On INVALID_SESSION it identifies again on the same connection. - Reconnects back off exponentially with jitter, from 1 s up to 60 s
(
gateway: { reconnect: { minDelayMs, maxDelayMs } }); after4008(rate limited) it waits at leastrateLimitedDelayMs(30 s).4000,4003,4005and4007start a new session. 4004(bad, revoked or expired token, disabled or banned bot),4013and4014(intents) are fatal: the SDK stops,connect()rejects with aGatewayErroranderroris emitted.
Add link
import { addBotLink, encodeManifest } from '@mnema-xyz/bot-sdk'
const link = addBotLink('https://talk.example.org', {
manifest_version: 1,
name: 'Dice',
intents: [],
permissions: ['view_channel', 'send_messages'],
commands: [{ name: 'roll', description: 'Rolls a die' }],
})
// https://talk.example.org/admin/bots/add#manifest=<base64url JSON>
encodeManifest(manifest) gives the base64url part alone. Both check the
manifest (version 1, name 1 to 24 characters, an https homepage, a data:
avatar, valid commands). See
Adding a bot from a manifest.
Versioning and support
- Semantic versioning: a minor version adds, a major version may break, and every change is in the changelog.
- Each version names the oldest Mnema Talk server it is tested with in its
changelog entry; CI runs the contract tests against Mnema Talk's
mainand its latest release, so new server releases are covered before they ship and the SDK keeps working with the released server. - Fixes, security fixes included, go into the latest version only. Report a vulnerability privately as SECURITY.md says.
- Questions and bugs: issues. Contributions: CONTRIBUTING.md.
The examples
The examples as they are in the repository at v3.5.0; each reads MNEMA_URL and MNEMA_TOKEN.
buttons.ts
// Buttons, a select and a modal: "!deploy" posts a message with buttons and
// an environment select; the buttons update the message, "Feedback" opens a
// modal and its submit is answered privately.
// Run: MNEMA_URL=https://talk.example.org MNEMA_TOKEN=mnb_... node examples/buttons.ts
import {
actionRow,
button,
ButtonStyle,
Client,
Intents,
linkButton,
modal,
stringSelect,
textInput,
TextInputStyle,
} from '@mnema-xyz/bot-sdk'
const client = new Client({
baseUrl: process.env.MNEMA_URL ?? 'https://talk.example.org',
token: process.env.MNEMA_TOKEN ?? '',
intents: Intents.GuildMessages,
})
const environments = stringSelect({
customId: 'env',
placeholder: 'Environment',
options: [
{ label: 'Staging', value: 'staging', default: true },
{ label: 'Production', value: 'prod' },
],
})
function deployRows(env: string) {
return [
actionRow(
button({ customId: `deploy:${env}`, label: `Deploy to ${env}`, style: ButtonStyle.Success }),
button({ customId: 'cancel', label: 'Cancel', style: ButtonStyle.Secondary }),
button({ customId: 'feedback', label: 'Feedback', emoji: '📝' }),
linkButton({ url: 'https://talk.example.org/changes', label: 'Changelog' }),
),
actionRow(environments),
]
}
client.on('messageCreate', async (m) => {
if (m.user_id === client.user?.id || m.content !== '!deploy') return
await client.rest.createMessage(m.channel_id, { content: 'Deploy v2.4?', components: deployRows('staging') })
})
client.on('interactionCreate', async (i) => {
if (i.isSelect() && i.customId === 'env') {
const env = i.values[0] ?? 'staging'
await i.update({ content: `Deploy v2.4 to ${env}?`, components: deployRows(env) })
} else if (i.isButton() && i.customId.startsWith('deploy:')) {
const env = i.customId.slice('deploy:'.length)
await i.update({ content: `${i.user.display_name} deployed v2.4 to ${env}.`, components: [] })
} else if (i.isButton() && i.customId === 'cancel') {
await i.update({ content: 'Deploy cancelled.', components: [] })
} else if (i.isButton() && i.customId === 'feedback') {
await i.showModal(
modal({
customId: 'feedback-form',
title: 'Feedback',
components: [
textInput({ customId: 'subject', label: 'Subject', maxLength: 80 }),
textInput({ customId: 'body', label: 'What happened?', style: TextInputStyle.Paragraph, required: false }),
],
}),
)
} else if (i.isModalSubmit() && i.customId === 'feedback-form') {
await i.reply({ content: `Thanks! Noted: "${i.fields.get('subject')}"`, ephemeral: true })
}
})
client.on('error', (err) => console.error(err))
process.on('SIGINT', () => void client.close().then(() => process.exit(0)))
await client.connect()
echo.ts
// Echo bot: answers "!echo <text>" with the text, as a reply.
// Run: MNEMA_URL=https://talk.example.org MNEMA_TOKEN=mnb_... node examples/echo.ts
// (after `npm run build`; the bot needs View channels and Send messages).
import { Client, Intents } from '@mnema-xyz/bot-sdk'
const client = new Client({
baseUrl: process.env.MNEMA_URL ?? 'https://talk.example.org',
token: process.env.MNEMA_TOKEN ?? '',
intents: Intents.GuildMessages,
presence: { status: 'online', activity: { name: '!echo', type: 2 } },
})
client.on('ready', (ready) => console.log(`connected as ${ready.user.username}`))
client.on('messageCreate', async (message) => {
// The bot's own messages arrive too: ignore them.
if (message.user_id === client.user?.id || !message.content.startsWith('!echo ')) return
await client.rest.createMessage(message.channel_id, {
content: message.content.slice('!echo '.length),
message_reference: { message_id: message.id },
allowed_mentions: { parse: [] },
})
})
client.on('error', (err) => console.error(err))
process.on('SIGINT', () => void client.close().then(() => process.exit(0)))
await client.connect()
slash.ts
// Slash command bot: /ping answers at once, /roll defers and then edits its
// answer, and either can answer only to the member who ran it.
// Run: MNEMA_URL=https://talk.example.org MNEMA_TOKEN=mnb_... node examples/slash.ts
import { Client, OptionType } from '@mnema-xyz/bot-sdk'
const client = new Client({
baseUrl: process.env.MNEMA_URL ?? 'https://talk.example.org',
token: process.env.MNEMA_TOKEN ?? '',
intents: 0, // interactions need no intent
})
client.on('ready', async () => {
const commands = await client.commands.set([
{
name: 'ping',
description: 'Replies with pong',
options: [{ name: 'private', description: 'Only you see the answer', type: OptionType.Boolean }],
},
{
name: 'roll',
description: 'Rolls a die',
options: [
{ name: 'sides', description: 'How many sides', type: OptionType.Integer, required: true },
{ name: 'label', description: 'What the roll is for', type: OptionType.String, choices: ['attack', 'defence', 'luck'] },
],
},
])
console.log(`registered ${commands.map((c) => '/' + c.name).join(', ')}`)
})
client.on('interactionCreate', async (i) => {
if (!i.isCommand()) return
if (i.commandName === 'ping') {
await i.reply({ content: 'pong', ephemeral: i.options.get('private') === true })
return
}
if (i.commandName === 'roll') {
await i.deferReply()
const sides = Number(i.options.get('sides'))
if (!Number.isInteger(sides) || sides < 2) {
await i.editReply('A die needs at least 2 sides.')
return
}
const label = i.options.get('label')
const result = 1 + Math.floor(Math.random() * sides)
await i.editReply(`${i.user.display_name} rolled **${result}** (d${sides}${label ? `, ${label}` : ''})`)
}
})
client.on('error', (err) => console.error(err))
process.on('SIGINT', () => void client.close().then(() => process.exit(0)))
await client.connect()