Skip to content

Write a bot

A Tusile bot is a member of a server that answers slash commands, puts buttons and forms on messages, moderates, and joins voice channels. You write one in Node.js with the free @tusile/bot package (MIT licensed). This page describes version 0.7.0.

A bot dials out: one WebSocket to each community it has been added to, and ordinary HTTPS requests back. It needs no public URL and no open port, so it runs on a laptop, a spare machine or a cheap server, and it is online for as long as the program is running.

Only want to add an existing bot to your server? See Bots for server owners.

  • It has a name and an avatar, shows up in the member list with a BOT tag, holds roles, and has its permissions checked exactly like anybody else’s. It cannot read a channel it has not been let into.
  • It counts towards the server’s member count, and removing it takes its commands with it.
  • Nothing is queued for it. If the bot is offline when somebody runs its command, the interaction times out and the person is told so. A reconnect starts clean.
  1. In the Tusile app, open Settings, Bots (or Discover, Bots, which opens the same screen) and create a bot. Anybody with a confirmed account can make up to ten.
  2. Give it a name and a picture.
  3. Copy the key and the secret. The secret is shown once; a lost one is rotated, not recovered.

Fill in How to talk to it if your bot answers mentions rather than slash commands. It is one line at the top of the bot’s profile card, above its commands; without it a bot with no commands only says “This bot has no commands. Mention it to see if it answers.”

A bot can be handed to another account later, by email address, from the same screen. Its key and secret keep working, so it stays online across the handover.

Rather than assembling one from the pieces below, download a bot that already works and edit it. You need Node.js 20.6 or newer; the script checks.

Download bot-starter.zip

  1. Unpack it. On Windows, double-click setup.bat; on macOS or Linux, run chmod +x setup.sh && ./setup.sh.
  2. It asks for the key and secret, writes them to .env, installs the package and starts the bot. After that, npm start is the whole command.
  3. Edit bot.js and restart to see your own commands.

The bot is online while that command runs on your computer and offline when you stop it. Nothing is typed into a channel or uploaded anywhere: the key and secret are the only link to your server.

Terminal window
npm install @tusile/bot
bot.js
import { Bot } from '@tusile/bot';
const bot = new Bot(); // reads CORE_SERVER_URL, BOT_KEY, BOT_SECRET
bot.command({ name: 'ping', description: 'Check the bot is awake' }, (i) => i.reply('pong'));
await bot.start();
Terminal window
CORE_SERVER_URL=https://api.tusile.com BOT_KEY=... BOT_SECRET=... node bot.js

The package needs Node.js 20 or newer. That bot is live on every community that has added it, and joins new ones by itself. The package handles what nobody should write twice: a token minted for each community (and a fresh one whenever a community refuses the old one), reconnecting with a backoff, heartbeats at the interval the server asks for, and registering the command list on every connect.

new Bot() also takes options instead of environment variables: coreUrl, key, secret, permissions (see Say what your bot needs), onError, and autoDeferMs.

bot.command(
{
name: 'roll',
description: 'Roll a die',
options: [
{ name: 'sides', type: 'integer', description: 'Sides', min: 2, max: 100 },
{ name: 'secret', type: 'boolean', description: 'Only you see it' },
],
},
async (i) => {
const sides = i.options.sides || 6;
await i.reply(`d${sides}: ${1 + Math.floor(Math.random() * sides)}`, {
ephemeral: Boolean(i.options.secret),
});
},
);
Option field What it does
name Lowercase, no spaces.
type string, integer, boolean, user, channel or role.
description Shown beside the input.
required Required options must come before optional ones.
min, max Integers only.
choices [{ name: 'Shown', value: 'sent' }], for string and integer only, at most 25. Turns the option into a picker, so nobody can type a value the bot will refuse.

user, channel and role are pickers of the people, channels and roles on that server, and the bot is handed an ID. At most 25 options per command.

Values arrive already checked against this schema: an integer is a number within its bounds, a choice is one of the ones offered, an ID has the right shape. A bad value is refused before the bot hears about it, with a message naming the option.

Who may run it. A command that acts on the server can say what the person running it must hold, with requiredPermissions next to its name (for example ['manage_channels', 'manage_roles']). All of them are required, an administrator bypasses the check, and the app does not offer the command to anybody without them. Without it, a command is open to everybody who can talk in the channel.

Registering replaces that bot’s whole command set, and only that bot’s: two bots may register the same command name, and the app says whose is whose.

A bot has ten seconds to answer, or the person is shown “The bot did not respond”. Deferring buys fifteen minutes.

await i.reply('everyone in the channel sees this');
await i.replyPrivately('only the person who asked sees this');
await i.defer(); // buys fifteen minutes; defer({ ephemeral: true }) for a private answer
await i.followUp('still working'); // another message after the first
await i.editReply('done'); // rewrite what it already said
await i.deleteReply();
await i.showModal({ /* ... */ }); // ask them to fill something in
await i.update({ content: 'Confirmed', components: [] }); // rewrite the message a button is on
await i.acknowledge(); // a press that needs no visible change
Response type (on the wire) What happens
message Posted to the channel; everyone sees it.
ephemeral Reaches only the person who asked. Not channel history, and gone within a day.
defer Acknowledges now; answer within 15 minutes. "ephemeral": true here is the only chance to make the answer private.
modal Asks them to fill something in.
update_message Rewrites the message the control is on, in place.
defer_update Acknowledges a press with no visible change.

The last two answer a press, not a command. A confirm that removes its own buttons, a list page that turns, a toggle that redraws: all of them rewrite the message in place. Posting a new message instead moves the exchange to the bottom of the channel and leaves the old buttons working above it.

  • An absent embeds or components leaves that part alone; an empty list removes it.
  • Whether an answer is private is the bot’s decision. The app will not offer to publish a private one.
  • An interaction can be answered once. A second answer is a conflict, and the package refuses it before it leaves the process.
  • If a command or form handler is still working after eight seconds, the package defers for you (change it with autoDeferMs). A button press is left alone, because update is only possible before any answer, so a slow press should defer and follow up.
await i.reply({
content: 'Delete this channel?',
components: [{
type: 'row',
components: [
{ type: 'button', style: 'danger', label: 'Delete', custom_id: 'del:yes' },
{ type: 'button', style: 'secondary', label: 'Keep', custom_id: 'del:no' },
{ type: 'button', style: 'link', label: 'Docs', url: 'https://tusile.com' },
],
}],
});
// Matched on the prefix, so both buttons land here and the ID carries the answer.
bot.component('del', (i) =>
i.update({ content: i.customId === 'del:yes' ? 'Gone.' : 'Kept.', components: [] }),
);
{
type: 'select',
custom_id: 'size',
placeholder: 'Pick one',
min_values: 1,
max_values: 2,
options: [
{ label: 'Small', value: 's' },
{ label: 'Large', value: 'l', description: 'the big one' },
],
}
  • Rows only at the top level, at most 5 rows of 5. A menu takes a row to itself, with up to 25 options.
  • Button styles are primary, secondary, danger and link; anything else draws as a plain button. A link button carries a url and never reaches the bot; every other style carries a custom_id and does.
  • A custom_id is yours, up to 100 bytes. The server echoes it back verbatim and never parses it, so encode whatever state you need in it. An exactly registered ID wins over a prefix, and the longest matching prefix wins.
  • A menu’s min_values and max_values are enforced on the way back too: a submission with too few or too many choices, or the same choice twice, is refused before the bot hears about it.
  • The server checks that a control is really yours: a press names the message that carries it, and that message must be one this bot authored and must contain a control with that ID.
  • Buttons on a private answer, and a form opened in answer to a command, are not messages. They carry source_interaction_id instead (i.sourceInteractionId), and only the person the answer was for can use them.
bot.command({ name: 'feedback', description: 'Send a note' }, (i) =>
i.showModal({
custom_id: 'feedback',
title: 'Tell us more',
fields: [
{ custom_id: 'subject', label: 'Subject', required: true },
{ custom_id: 'body', label: 'Anything else', style: 'paragraph' },
],
}),
);
bot.modal('feedback', (i) => i.replyPrivately(`Noted: ${i.fields.subject}`));

The submission arrives in i.fields, keyed by each field’s custom_id. style: 'paragraph' draws a multi-line box; anything else is one line. A form holds up to 5 fields. A submission carrying a field the form never declared, a blank required field, or a value over 4000 bytes is refused before the bot hears about it.

embeds: [{
title: 'Now playing',
url: 'https://example.com/track',
description: 'a song',
color: 5793266,
author: { name: 'Jukebox', icon_url: 'https://...' },
fields: [{ name: 'Length', value: '3:21', inline: true }],
image: { url: 'https://...' },
thumbnail: { url: 'https://...' },
footer: { text: 'queued by Ada' },
}]

color is 24-bit RGB. Only http and https URLs.

Limit Value
Embeds per message 10
Fields per embed 25
Title, author name, field name 256 bytes
Description 4096 bytes
Field value 1024 bytes
Footer text 2048 bytes
All embed text on one message 6000 bytes

Bytes, not characters, so Arabic or Polish text reaches a limit at about half the character count and CJK at about a third. A payload past a limit is refused when it is sent, with a message naming the field.

Each handler gets i.server, the community the interaction came from; outside a handler, bot.servers holds every connected community by ID. server.request(method, path, body) reaches anything not in these tables, so an endpoint newer than your copy of the package is one line away. A refused call throws an ApiError (named TusileApiError) with status and the server’s reason, never silence.

Reading

Method What it does
history(channelId, { limit, before }) Channel history, newest first; limit up to 100, before (a message ID) to page.
message(id) One message.
channels() The channels it can see.
members() Members with their roles.
member(userId) One member with their roles, held for a minute. member(id, { fresh: true }) skips the held copy, forgetMembers() drops it.
roles() The server’s roles.
serverInfo() The server’s name, icon, and member and channel counts.
commands() The commands this bot has registered here.
rateLimit What was left of the rate limit on the last call.

Talking

Method What it does
send(channelId, message) A string, or { content, embeds, components, reply_to_id, attachment_url }. persona: { name, avatar_url, source } posts under another name and picture, for a bridge (needs post_as_others).
editMessage(id, message) Edit its own message, embeds and components included.
deleteMessage(id) Its own, or anybody’s with Manage Messages.
deleteMessages(channelId, ids) Up to 100 at once, with Manage Messages.
typing(channelId) Show it is working on something.
thinking(channelId) Shows the bot as thinking until you call the function it returns. It repeats for you, so it lasts through a long model call.
react(id, emoji), unreact(id, emoji) Add and remove its reaction. Adding twice leaves one reaction rather than toggling it off.
pin(id), unpin(id) With Manage Messages.

Moderating and managing

Method Needs
addRole(userId, roleId), removeRole(userId, roleId) Manage Roles
timeout(userId, seconds, reason), clearTimeout(userId) Timeout Members
kick(userId) Manage Members
ban(userId, reason), unban(userId), bans() Manage Members
createChannel, updateChannel, deleteChannel Manage Channels
categories(), createCategory, updateCategory, deleteCategory Manage Channels
channelPermissions(id), setChannelPermission, removeChannelPermission Manage Channels or Manage Roles
createRole, updateRole, deleteRole Manage Roles
setNickname(userId, name) '@me' renames the bot itself, which needs nothing
joinVoice(channelId, { speaking }), setVoiceState(channelId, { speaking }), leaveVoice(channelId) Connect; a live mic needs Speak
voiceToken(channelId) A media token, for publishing audio

Rules the server keeps whatever the bot asks for:

  • A bot cannot create a role above its own, or allow a permission (in a role or a channel) that it does not hold itself. Denying is not capped, so a bot locking a channel down does not need every permission it switches off.
  • It cannot act on another bot.
  • Running a command needs View and Send in the channel, plus whatever requiredPermissions names. Pressing a control the bot already posted needs only View, so buttons work in a read-only announcements channel. The bot needs View there as well.

member() is a saving, not a source of truth: the held copy can carry a role taken away a minute ago. It cannot grant anybody anything, because the community checks every action against the real roles, but pass { fresh: true } when the answer is a decision rather than a label.

A community’s member list knows when somebody joined and nothing else. Facts about a person live on Tusile’s core service, through bot.core:

const profile = await bot.core.profile(userId); // last_seen, is_guest, username, ...
const name = await bot.core.displayName(userId); // what to call them, remembered
const owner = (await bot.core.community(serverId))?.owner_id;
Method Returns
profile(userId) The public profile, or null.
displayName(userId) Their name, cached for ten minutes, or null.
community(serverId) A community’s public record, which names its owner, or null.
request(method, path, body) Anything else on the core service, with the bot’s own credentials.

These three return null rather than throwing, so a bot sweeping two hundred members does not lose the pass to one lookup. The community itself protects the owner: a bot’s kick, ban, timeout or rename of somebody else is refused when aimed at the owner, or at anybody whose highest role is not below the bot’s own.

import { Bot, Permissions } from '@tusile/bot';
const bot = new Bot();
bot.command({
name: 'setup',
description: 'Build the standard channels',
// Only somebody who could do this by hand may ask the bot to.
requiredPermissions: ['manage_channels', 'manage_roles'],
}, async (i) => {
await i.defer();
const s = i.server;
const staff = await s.createRole({ name: 'Staff', permissions: Permissions.view_channel });
const team = await s.createCategory({ name: 'Team' });
const general = await s.createChannel({ name: 'general', type: 'text', category_id: team.id });
const inner = await s.createChannel({ name: 'staff-only', type: 'text', category_id: team.id });
// The part that makes it a server rather than a pile of channels.
const everyone = (await s.roles()).find((r) => r.is_default);
await s.setChannelPermission(inner.id, { role: everyone.id, deny: 'view_channel' });
await s.setChannelPermission(inner.id, { role: staff.id, allow: 'view_channel' });
await s.addRole(i.userId, staff.id);
await s.send(general.id, 'Set up. #staff-only is for the Staff role.');
await i.editReply('Done.');
});
await bot.start();

allow and deny take a permission name, a list of names, or a number. The names, as exported in Permissions:

view_channel, send_messages, manage_messages, manage_channels, manage_roles, manage_members, administrator, connect, speak, mute_members, deafen_members, manage_server, create_invite, attach_files, stream, use_camera, manage_emojis, manage_emoji_policy, timeout_members, use_soundboard, manage_soundboard, post_as_others, add_soundboard_sounds.

A name the package does not know throws, rather than quietly denying nothing.

Whoever adds your bot is shown the permissions it asks for and ticks what they allow. Declare them in code, next to the commands that need them:

const bot = new Bot({
permissions: ['view_channel', 'send_messages', 'manage_channels', 'connect', 'speak'],
});
  • A declaration grants nothing by itself. The bot ends up with what the person ticked and nothing more, so asking for less is a bot more people will add. To give a bot more, give it a role.
  • An unknown name throws at startup. The owner can tick the same list in Settings, Bots, and the declaration in code wins when the bot starts.
  • Ask for view_channel if your bot does anything in a channel. A bot that cannot see a channel is not handed the interactions there, so a bot that asks only for send_messages will look installed and answer nothing.
  • The bot learns what it was actually granted when it connects (the ready frame carries it), so it can say “I was not given Speak” instead of retrying a call that will always be refused.

joinVoice puts the bot in the channel; the audio goes through LiveKit, the same path the app uses.

Terminal window
npm install @livekit/rtc-node
import { Room, AudioSource, LocalAudioTrack, TrackPublishOptions, TrackSource, AudioFrame }
from '@livekit/rtc-node';
await i.server.joinVoice(channelId, { speaking: true });
const { token, url } = await i.server.voiceToken(channelId);
const room = new Room();
await room.connect(url, token, { autoSubscribe: false });
const source = new AudioSource(48000, 1);
const options = new TrackPublishOptions();
options.source = TrackSource.SOURCE_MICROPHONE;
await room.localParticipant.publishTrack(LocalAudioTrack.createAudioTrack('tone', source), options);
// 10 ms frames of signed 16-bit samples at 48 kHz.
await source.captureFrame(new AudioFrame(samples, 48000, 1, 480));
  • Which channel: i.userVoiceChannelId is the voice channel the person who ran the command is sitting in, so /play can use the room they are in. It is '' when they are in none (or the community is too old to send it).
  • speaking: true is what the channel shows. Without it the bot is drawn with a crossed-out microphone while it plays. It needs Connect to be in the channel and Speak to claim a live microphone.
  • Files: decode them to the same frames, 48 kHz, signed 16-bit, mono or stereo. Nothing in Tusile transcodes for you.
bot.on('ready', (me, server) => {}); // connected to a community
bot.on('message', (message, server) => {}); // said in a channel the bot can see
bot.on('messageUpdate', (data, server) => {}); // a message there was edited
bot.on('messageDelete', (data, server) => {}); // a message there was deleted
bot.on('joined', (server) => {}); // added to a community
bot.on('left', (serverId) => {}); // removed from one
bot.on('error', (err, context) => {}); // anything that went wrong

The package also passes on the rest of what a community announces, each as (data, server): reactionAdd, reactionRemove, channelCreate, channelUpdate, channelDelete, categoryUpdate, memberJoin, memberLeave and memberUpdate. Channel events reach the bot only for channels it can see.

A bot that replies to plain messages must check message.author_id !== bot.me.id first, or it answers itself, forever. Without an error listener, errors are printed to stderr.

Per bot per community: 60 writes a minute with a burst of 20, and 300 reads a minute with a burst of 60. A bot on many communities gets that allowance on each of them.

Every response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset (seconds until the budget is full). Over the limit is a 429 with Retry-After, which the package waits out and retries. A bot removed from a community stops reconnecting to it; credentials that are refused (a deleted bot, a rotated secret) stop the bot entirely rather than being retried.

For writing a bot in another language, or reaching something the package has no method for. Two hosts: Tusile’s core service (https://api.tusile.com) holds the bot’s identity, and each community holds its own data.

Authorization: Bot base64(key:secret) # to the core service, and only there
GET /bots/me # id, name, avatar
GET /bots/me/servers # [{server_id, api_url}]; ?wait=25 holds it open
POST /bots/token {"server_id": "..."} # a token for one community, good for an hour
Authorization: Bearer <that token> # to that community, and nowhere else
WS /bot/gateway # send {"type":"auth","token":"..."} first
PUT /bot/commands # the command list, on every connect
POST /bot/interactions/{id}/callback # answer, within ten seconds
POST /bot/interactions/{id}/followup # again, within fifteen minutes
PATCH, DELETE /bot/interactions/{id}/response
POST /bot/channels/{id}/messages # and the rest of the tables above

The gateway sends:

  • ready, with the bot’s granted permissions, the channels it can see, and heartbeat_interval_seconds, which a bot must honour or be dropped;
  • interaction_create when somebody runs a command or presses a control;
  • message_create, message_update and message_delete for channels the bot can see, and the other community events listed above.
{
"type": "interaction_create",
"data": {
"id": "...", "type": "command", "command": "roll",
"options": {"sides": 20, "secret": true},
"channel_id": "...", "user_id": "...",
"custom_id": "", "values": [], "fields": {},
"message_id": "", "source_interaction_id": "",
"user_voice_channel_id": "..."
}
}

Close reasons to handle:

  • bot_uninstalled: the bot was removed. Stop reconnecting to that community.
  • server_retired: the community has left that host, usually for one of its own. Ask the core service for the server list again before reconnecting. A community keeps its ID when it moves and only its api_url changes, so reconcile connections on the address as well as the ID, or the bot reads as offline there until restarted.
  • Anything else: retry with a backoff.

A per-community token means a community never sees a credential that works anywhere else. It expires in an hour, so mint a fresh one on every connect.

Not there Why
Direct messages A bot cannot DM anybody. One-to-one messages can be end-to-end encrypted, and a bot has no key for them. It can answer privately in a channel instead.
Autocomplete on options Choices are fixed when the command is registered.
Context-menu commands Only slash commands and controls.
A status line A bot cannot set a “playing” line. It shows as online while its gateway is connected.
Gateway resume A reconnect does not replay what was missed.
Webhooks Deliberately gone. This replaced them, and it is why a bot needs no public address.

Questions about writing a bot? Ask in the official Tusile community at app.tusile.com/j/tusile.